Cara Membuat Navigation Drawer + Webview



     Cara Membuat Navigation Drawer + Webview Hallo sahabat mozilla, ini pertama kalinya penulis memposting artikel tentang android barangkali bermanfaat bagi kalian, berawal dari salah satu teman yang ingin membuat salah satu aplikasi yang sudah terintegrasi navigation drawer dengan tambahan fiture getlink ke web atau yang biasa kita sebut dengan web view.

     Sempat terpikir daripada pengetahuan dasar ini disimpan didalam laptop sendiri lebih baik saya sempatkan menuliskan kedalam blog.

Untuk pembuatan navigation drawer, pertama kali buat layout activity_main.xml

<android.support.v4.widget.DrawerLayout 
xmlns:android="http://schemas.android.com/apk/res/android"     
xmlns:ads="http://schemas.android.com/apk/res-auto" 
android:id="@+id/drawer_layout"     
android:layout_width="match_parent" 
android:layout_height="match_parent" >

<!-- The main content view -->
<FrameLayout         
android:id="@+id/frame_container" 
android:layout_width="match_parent" 
android:layout_height="match_parent" >


</FrameLayout>
 
 <!-- The navigation drawer list -->
<ListView 
android:id="@+id/slider_list" 
android:layout_width="240dp"         
android:layout_height="match_parent" 
android:layout_gravity="start" 
android:background="#ffffff" 
android:choiceMode="singleChoice" 
android:divider="#dddddd"         
android:dividerHeight="1dp"        />


</android.support.v4.widget.DrawerLayout>

Jangan Lupa Tambahkan list_item.xml

 
<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="48dp" 
android:padding="5dp" >

<ImageView 
android:id="@+id/icon" 
android:layout_width="50dp"         
android:layout_height="wrap_content"         
android:layout_alignParentLeft="true" 
android:layout_centerVertical="true" 
android:layout_marginLeft="12dp" 
android:layout_marginRight="12dp" 
android:contentDescription="@string/imgdesc" 
/>

    <TextView         
android:id="@+id/title" 
android:layout_width="wrap_content"         
android:layout_height="match_parent"         
android:layout_marginTop="7dp"         
android:layout_toRightOf="@id/icon" 
android:gravity="center_vertical"         
android:textColor="#000000"         
android:textSize="20sp"  
/>

</RelativeLayout>

Untuk aktor utamanya tambahkan web_fragment.xml
<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout     
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:ads="http://schemas.android.com/apk/res-auto" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
 
<WebView 
android:id="@+id/webview1"         
android:layout_width="match_parent"         
android:layout_height="match_parent"         
android:layout_alignParentLeft="true" />

</RelativeLayout>

Logikanya bisa ditambahkan seperti ini di MainActivity.java

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;



public class MainActivity extends Activity {



   String[] menutitles;
   TypedArray menuIcons;
   String[] pageUrl;

   // nav drawer title 
 private CharSequence mDrawerTitle;
   private CharSequence mTitle;

   private DrawerLayout mDrawerLayout;
   private ListView mDrawerList;
   private ActionBarDrawerToggle mDrawerToggle;

   private List<RowItem> rowItems;
   private CustomAdapter adapter;

   @SuppressLint("NewApi")
   @Override   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

     
      mTitle = mDrawerTitle = getTitle();

      menutitles = getResources().getStringArray(R.array.titles);
      menuIcons = getResources().obtainTypedArray(R.array.icons);
      pageUrl = getResources().getStringArray(R.array.pageurl);

      mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
      mDrawerList = (ListView) findViewById(R.id.slider_list);

      rowItems = new ArrayList<RowItem>();

      for (int i = 0; i < menutitles.length; i++) {
         RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(
               i, -1), pageUrl[i]);
         rowItems.add(items);
      }

      menuIcons.recycle();

      adapter = new CustomAdapter(getApplicationContext(), rowItems);

      mDrawerList.setAdapter(adapter);

      mDrawerList.setOnItemClickListener(new SlideitemListener());

      // enabling action bar app icon and behaving it as toggle button       
      getActionBar().setDisplayHomeAsUpEnabled(true);
      getActionBar().setHomeButtonEnabled(true);

      mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer, R.string.app_name,
            R.string.app_name) {
         public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            // calling onPrepareOptionsMenu() to show action bar icons             
invalidateOptionsMenu();
         }

         public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            // calling onPrepareOptionsMenu() to hide action bar icons 
 invalidateOptionsMenu();
         }
      };
 
 
 mDrawerLayout.setDrawerListener(mDrawerToggle);

      if (savedInstanceState == null) {
         // on first time display view for first nav item         updateDisplay(0);

      }



   }






   class SlideitemListener implements ListView.OnItemClickListener {
      @Override      public void onItemClick(AdapterView<?> parent, 
View view, int position,
            long id) {
         updateDisplay(position);
      }

   }

   private void updateDisplay(int position) {

      String url = rowItems.get(position).getPageUrl();

      Fragment fragment = new MyWebViewFragment();

      Bundle bundle = new Bundle();
      bundle.putString("url", url);

      fragment.setArguments(bundle);

      FragmentManager fragmentManager = getFragmentManager();
      fragmentManager.beginTransaction()
            .replace(R.id.frame_container, fragment).commit();

      setTitle(menutitles[position]);
      mDrawerLayout.closeDrawer(mDrawerList);

   }

   @Override   public void setTitle(CharSequence title) {
      mTitle = title;
      getActionBar().setTitle(mTitle);
   }

   @Override   public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }

   @Override   public boolean onOptionsItemSelected(MenuItem item) {
      // toggle nav drawer on selecting action bar app icon/title       
if (mDrawerToggle.onOptionsItemSelected(item)) {
         return true;
      }
 // Handle action bar actions click       
switch (item.getItemId()) {
      case R.id.action_settings:
         return true;
      default:
         return super.onOptionsItemSelected(item);
      }
   }

   /*** * Called when invalidateOptionsMenu() is triggered    */    
@Override   public boolean onPrepareOptionsMenu(Menu menu) {
      // if nav drawer is opened, hide the action items 
 boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
      menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
      return super.onPrepareOptionsMenu(menu);
   }


 
 @Override   protected void onPostCreate(Bundle savedInstanceState) {
      super.onPostCreate(savedInstanceState);
      // Sync the toggle state after onRestoreInstanceState has occurred.       
mDrawerToggle.syncState();
   }

   @Override   public void onConfigurationChanged(Configuration newConfig) {
      super.onConfigurationChanged(newConfig);
      // Pass any configuration change to the drawer toggls 
 mDrawerToggle.onConfigurationChanged(newConfig);
   }


}

Tambahkan CustomAdapter.java


import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomAdapter extends BaseAdapter {

   Context context;
   List<RowItem> rowItem;

   CustomAdapter(Context context, List<RowItem> rowItem) {
      this.context = context;
      this.rowItem = rowItem;
   }

   private class ViewHolder {
      ImageView icon;
      TextView title;
   }

   @Override   public View getView(int position, View convertView, ViewGroup parent) {

      ViewHolder holder = null;
      convertView = null;
      LayoutInflater mInflater = (LayoutInflater) context             
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
      if (convertView == null) {
         convertView = mInflater.inflate(R.layout.list_item, null);
         holder = new ViewHolder();
         holder.icon = (ImageView) convertView.findViewById(R.id.icon);
         holder.title = (TextView) convertView.findViewById(R.id.title);

         RowItem row_pos = rowItem.get(position);
         // setting the image resource and title          
         holder.icon.setImageResource(row_pos.getIcon());
         holder.title.setText(row_pos.getTitle());
         convertView.setTag(holder);

      }
      return convertView;

   }

   @Override   public int getCount() {
      return rowItem.size();
   }

   @Override   public Object getItem(int position) {
      return rowItem.get(position);
   }

   @Override   public long getItemId(int position) {
      return rowItem.indexOf(getItem(position));
   }

}

Tambahkan indikator pada RowItem.java

 
public class RowItem {

   private String title;
   private int icon;
   private String pageUrl;

   public RowItem(String title, int icon, String pageUrl) {
      this.title = title;
      this.icon = icon;
      this.pageUrl = pageUrl;
   }

   public String getTitle() {
      return title;
   }

   public void setTitle(String title) {
      this.title = title;
   }

   public int getIcon() {
      return icon;
   }

   public void setIcon(int icon) {
      this.icon = icon;
   }

   public String getPageUrl() {
      return pageUrl;
   }

   public void setPageUrl(String pageUrl) {
      this.pageUrl = pageUrl;
   }

}

Pada Fragmen tambahkan Fragment Webview di   MyWebViewFragment.java

 
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

public class MyWebViewFragment extends Fragment {


   private AdView mAdView;

   ProgressDialog mProgress;
   WebView webview;

   @Override   public View onCreateView(LayoutInflater inflater, ViewGroup container,
         Bundle savedInstanceState) {




      View rootView = inflater.inflate(R.layout.web_fragment, container,false);



      Bundle bundle = getArguments();

      String url = bundle.getString("url");

      mAdView = (AdView) rootView.findViewById(R.id.adView);
      mAdView.loadAd(new AdRequest.Builder().build());

      webview = (WebView) rootView.findViewById(R.id.webview1);

      WebSettings settings = webview.getSettings();
      settings.setJavaScriptEnabled(true);

      mProgress = ProgressDialog.show(getActivity(), "Loading",
            "Please wait for a moment...");
      webview.loadUrl(url);




      webview.setWebViewClient(new WebViewClient() {
         @Override         public boolean shouldOverrideUrlLoading(WebView view, 
String url) {

            view.loadUrl(url);
            return true;
         }


         @Override         public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mProgress.isShowing()) {
               mProgress.dismiss();
            }
         }
      });

      return rootView;
   }


}

Oke, untuk logika java nya sudah kita buat dan kemudian tambahkan pada folder string.xml

 
<?xml version="1.0" encoding="utf-8"?><resources>

    <string name="app_name">Web View Navigation</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="imgdesc">imgdesc</string>

    <!-- Title -->    <string-array name="titles">
        <item>Linkedin</item>
        <item>Blogger</item>
        <item>Yahoo</item>
        <item>Wordpress</item>

    </string-array>
    <!-- Page Url -->    <string-array name="pageurl">
        <item>http://www.linkedin.com</item>
        <item>http://www.blogger.com</item>
        <item>https://yahoo.com</item>
        <item>https://wordpress.com</item>

    </string-array>
    <!-- Icons -->    <array name="icons">
        <item>@drawable/linkedin</item>
        <item>@drawable/blogger</item>
        <item>@drawable/yahoo</item>
        <item>@drawable/wordpress</item>

    </array>

</resources>

Jika sudah selesai semua sesuai alur petunjuk diatas, jangan lupa samakan gambar yang terdapat di drawable dengan koding yang ada di dalam MainActivity.java, kalian bisa samakan gambarnya seperti ini










Dan terakhir tambahkan permission di AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Maka tampilannya seperti ini










Jika sesuai dengan alur petunjuk diatas, kalian bisa coba jalan dengan menekan tombol "Run" kiri atas Bar

Semoga bermanfaat :)
Share on Google Plus

About reza

Hallo, nama saya Muhamad Reza Maulana Si tampan dari gua hantu :D , Saya seorang mahasiswa yang siap menghadapi Tugas Akhir, Ketertarikan saya belajar android ketika alkisah saya bekerja disebuah perusahaan start up yang mengharuskan saya untuk belajar android studio, ketika pertama kali saya belajar banyak sekali kendala beruntung banyak sekali mastah-mastah android yang mengajari saya. Dari sana saya bertekad untuk berbalas budi dengan memberikan sedikit pengetahuan saya kepada teman-teman seperjuangan dalam pemahaman android meskipun saya sendiri masih newbie , but saya yakin ilmu dapat mempersatuan semua :D Dengan Sedikit sharing pengalaman,masalah ataupun tutorial di website ini semoga dapat memberikan manfaat bagi kita semua, sekian ceramah kali ini terima gajih, eh kasih :D
    Blogger Comment
    Facebook Comment

4 komentar:

  1. misi a, boleh minta projectnya ga?
    kirim ke rivahsatria@gmail.com ya :) makasih

    BalasHapus
  2. mohon source codenya gan, kirim ke bruryarismanto@gmail.com

    BalasHapus
  3. Bro kok error di MyWebviewFragment.java ya.

    BalasHapus
  4. ngajarin nya setengah setengah.. klo kagak niat mending jangan di publish, kasian ngebingungin orang

    BalasHapus