The main activity is displaying but there is no toolbar for navigation drawer.
Ill post my codes below. Im beginner to android and i need your help guys.thanks in advance.
BASE ACTIVITY.class
public class BaseActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
protected RelativeLayout _completeLayout, _activityLayout;
// nav drawer title
private CharSequence mDrawerTitle;
private Toolbar topToolBar;
// used to store app title
private CharSequence mTitle;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer);
// if (savedInstanceState == null) {
// // on first time display view for first nav item
// // displayView(0);
mTitle = mDrawerTitle = " ";
topToolBar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(topToolBar);
topToolBar.setLogo(R.drawable.logo);
topToolBar.setLogoDescription(" ");
}
public void set(String[] navMenuTitles,TypedArray navMenuIcons) {
mTitle = mDrawerTitle = " ";
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items
if(navMenuIcons==null){
for(int i=0;i<navMenuTitles.length;i++){
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i]));
}}else{
for(int i=0;i<navMenuTitles.length;i++){
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i],navMenuIcons.getResourceId(i, -1)));
}
}
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// getSupportActionBar().setIcon(R.drawable.ic_drawer);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout
, // nav menu toggle icon
R.string.app_name, // nav drawer open - description for
// accessibility
R.string.app_name // nav drawer close - description for
// accessibility
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(" ");
// calling onPrepareOptionsMenu() to show action bar icons
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(" ");
// calling onPrepareOptionsMenu() to hide action bar icons
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private class SlideMenuClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
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);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
switch (position) {
case 0:
Intent intent = new Intent(this, Doctor.class);
startActivity(intent);
finish();
break;
case 1:
Intent intent1 = new Intent(this, Hospital.class);
startActivity(intent1);
finish();
break;
default:
break;
}
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle("");
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#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);
}
}
DRAWER.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="64dp"
android:layout_gravity="left"
android:background="#ffffff"
android:minHeight="?attr/actionBarSize" />
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Add content here -->
</FrameLayout>
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#ffffff"/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
drawer_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:paddingTop="12dp"
android:paddingBottom="12dp"
android:background="#drawable/selector_navigation_drawer"
>
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:gravity="center|start"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:src="#drawable/icon"
android:layout_marginTop="16dp"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/icon"
android:gravity="center|start"
android:layout_marginLeft="24dp"
android:text="no text"
android:textColor="#000000"
android:layout_alignTop="#+id/icon"
android:textSize="20dp"
android:paddingRight="40dp"
android:layout_alignBottom="#+id/icon"/>
</RelativeLayout>
styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
NavDrawerListAdapter.class
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
#Override
public int getCount() {
return navDrawerItems.size();
}
#Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
return convertView;
}
}
add these lines in your onCreate() method
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
Drawer Layout only takes 2 children.. one is main content and other is the drawer
In your case you just need to modify your layout file like below:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="64dp"
android:layout_gravity="left"
android:background="#ffffff"
android:minHeight="?attr/actionBarSize" />
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Add content here -->
</FrameLayout>
</LinearLayout>
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#ffffff"/>
</android.support.v4.widget.DrawerLayout>
Your Drawerlayout has to be parent layout and rest 2 childs i.e. linearlayout and listview
Also go through this documentation, it may help clear the picture
http://developer.android.com/training/implementing-navigation/nav-drawer.html
Related
I have added slider menu in android app. But unable to open after clicking side menu. after clicking on side menu it is not opening list. When i debugged i found that adapter =NULL & mdrawertoggle=NULL.
I am adding code please provide me solution if anyone have.
Thanks.
Attached image is showing side menu but unable to get list after clicking .
MainActivity
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adater ;
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// data of json url
private static final String url = "http://milagro.in/wip/apps/n/THDC2.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
//mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
//actionBar.setDisplayHomeAsUpEnabled(true);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Profile
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// About
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Emi Calculator
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Currency Converter
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// PayInstallments/EMI
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// Social Feed
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
// Feedback
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
//Settings
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adater= new NavDrawerListAdapter(getApplicationContext(),navDrawerItems);
mDrawerList.setAdapter(adater);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.menu, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
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
//displayView(0);
}
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("tata_project_name"));
movie.setThumbnailUrl(obj.getString("project_logo_url"));
movie.setParkingUrl(obj.getString("parking"));
movie.setPowerbackupUrl(obj.getString("powerbackup"));
movie.setFitnessUrl(obj.getString("fitness"));
movie.setLiftUrl(obj.getString("lift"));
movie.setParkUrl(obj.getString("park"));
movie.setSecurityUrl(obj.getString("security"));
movie.setSwimmingUrl(obj.getString("swimming"));
movie.setTypology(obj.getString("project_Typology"));
movie.setPrice(obj.getString("price"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#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);
}
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Profile();
break;
case 1:
fragment = new About();
break;
case 2:
fragment = new EMICalculator();
break;
case 3:
fragment = new CurrencyConverter();
break;
case 4:
fragment = new PayInstallment();
break;
case 5:
fragment = new SocialFeed();
break;
case 6 :
fragment =new Feedback();
break;
case 7:
fragment =new Settings();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#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);
}
public void bottomMenuClick(View v)
{
int pos = Integer.parseInt(v.getTag().toString());
switch (pos)
{
case 1: // enquiry screen
startActivity(new Intent(MainActivity.this,Enquiry.class));
break;
case 2: // contact screen
startActivity(new Intent(MainActivity.this, Contact.class));
break;
case 3: // Instant Call Back screen
startActivity(new Intent(MainActivity.this, CallBack.class));
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/app_name"
>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<FrameLayout
android:id="#+id/container_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"/>
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
</android.support.v4.widget.DrawerLayout>
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_row_selector"
android:background="#color/list_background"/>
<!-- <LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_below="#+id/content_frame"
>-->
<!-- <LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"></LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"></LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"></LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<Button
android:id="#+id/MyButton"
android:layout_width="370dp"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#01458e"
android:textColor="#FFFFFF"
android:text="#string/button_text"></Button>
</LinearLayout>
</LinearLayout>-->
<!-- </LinearLayout>-->
<!--
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!– Framelayout to display Fragments –>
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!– Listview to display slider menu –>
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
</android.support.v4.widget.DrawerLayout>-->
<!--<RelativeLayout
android:id="#+id/topLay"
android:layout_width="match_parent"
android:layout_height="#dimen/topLayHt"
android:layout_alignParentTop="true"
android:background="#drawable/header_bg">
<!–<ImageView
android:id="#+id/settingBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/setting_btn_highlight"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="#dimen/setting_btn_mg_rt"
android:clickable="true"
android:onClick="settingClick"
android:visibility="visible"/>
<ImageView
android:id="#+id/menu_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/menu_btn_highlight"
android:layout_marginLeft="#dimen/menu_btn_mg_lft"
android:clickable="true"
android:onClick="menuClick"/>
<ImageView
android:id="#+id/homeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/home_btn_highlight"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="#dimen/home_btn_mg_rt"
android:clickable="true"
android:onClick="homeClick"
android:visibility="gone"/>
<ImageView
android:id="#+id/backBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/back_btn_highlight"
android:layout_centerVertical="true"
android:layout_marginLeft="#dimen/back_btn_mg_lft"
android:clickable="true"
android:onClick="backClick"
android:visibility="gone"/>–>
</RelativeLayout>-->
<include
android:id="#+id/menu_lay"
layout="#layout/bottom_layout" />
</RelativeLayout>
NavdrawerlistAdapter.java
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
#Override
public int getCount() {
return navDrawerItems.size();
}
#Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
// displaying count
// check whether it set visible or not
if(navDrawerItems.get(position).getCounterVisibility()){
txtCount.setText(navDrawerItems.get(position).getCount());
}else{
// hide the counter view
txtCount.setVisibility(View.GONE);
}
return convertView;
}
}
drawerlist_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:background="#drawable/list_selector">
<ImageView
android:id="#+id/icon"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:contentDescription="#string/desc_list_item_icon"
android:src="#drawable/ic_home"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#id/icon"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#color/list_item_title"
android:gravity="center_vertical"
android:paddingRight="40dp"/>
<TextView android:id="#+id/counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/counter_bg"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="8dp"
android:textColor="#color/counter_text_color"/>
</RelativeLayout>
Navdraweritem.java
public class NavDrawerItem {
private String title;
private int icon;
private String count = "0";
// boolean to set visiblity of the counter
private boolean isCounterVisible = false;
public NavDrawerItem(){}
public NavDrawerItem(String title, int icon){
this.title = title;
this.icon = icon;
}
public NavDrawerItem(String title, int icon, boolean isCounterVisible, String count){
this.title = title;
this.icon = icon;
this.isCounterVisible = isCounterVisible;
this.count = count;
}
public String getTitle(){
return this.title;
}
public int getIcon(){
return this.icon;
}
public String getCount(){
return this.count;
}
public boolean getCounterVisibility(){
return this.isCounterVisible;
}
public void setTitle(String title){
this.title = title;
}
public void setIcon(int icon){
this.icon = icon;
}
public void setCount(String count){
this.count = count;
}
public void setCounterVisibility(boolean isCounterVisible){
this.isCounterVisible = isCounterVisible;
}
}
first you have to put your whole view inside a drawerlayout like this
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:orientation="vertical">
<include
layout="#layout/activity_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/activity_main_drawer"/>
</android.support.v4.widget.DrawerLayout>
here activity layout is the main layout with all the views
activity_main.xml should be like this:
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<FrameLayout
android:id="#+id/container_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"/>
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_row_selector"
android:background="#color/list_background"/>
</android.support.v4.widget.DrawerLayout>
I am new to android, I am trying to develop an application. In this application there is a base activity which is extended in all the remaining activities. The main problem is that I want to implement a navigation drawer, I don't know how to implement this without fragments. Can anyone help me to solve this problem.
Thanx
Nina
You can either convert some Activities to Fragments, or you can put the logic for the NavigationDrawer in the BaseActivity.
Check this sample code:
And you can learn more about Navigation Drawers from this link:
http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
And for doing it without Fragments I wrote a code below and used ViewPager:
This is my activity_main.xml:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Instead of using Fragments I used ViewPager here -->
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
</android.support.v4.widget.DrawerLayout>
This is drawer_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:background="#drawable/list_selector">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toLeftOf="#+id/button_delete_city"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingRight="40dp"
android:textAppearance="?android:attr/textAppearanceListItemSmall"/>
<Button
android:id="#+id/button_delete_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="X" />
</RelativeLayout>
This is NavDrawerListAdapter:
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> navDrawerItems;
MainActivity act;
public NavDrawerListAdapter(Context context, ArrayList<String> navDrawerItems, Activity act){
this.context = context;
this.navDrawerItems = navDrawerItems;
this.act = (MainActivity) act;
}
#Override
public int getCount() {
return navDrawerItems.size();
}
#Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
Button btn_delete = (Button)convertView.findViewById(R.id.button_delete_city);
btn_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
act.actionDelete(position);
}
});
}
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
txtTitle.setText(navDrawerItems.get(position));
txtTitle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
act.displayView(position);
}
});
return convertView;
}
public void addItem(String item){
navDrawerItems.add(item);
notifyDataSetChanged();
}
public void removeItem(int position){
navDrawerItems.remove(position);
notifyDataSetChanged();
}
}
And this is my MainActivity:
private ArrayList<String> navDrawerItems;
private NavDrawerListAdapter drawerAdapter;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//...
//...other codes to implement ViewPager
//...
navDrawerItems = new ArrayList<String>();
// setting the nav drawer list adapter
drawerAdapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems, this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
mDrawerList.setAdapter(drawerAdapter);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
// calling onPrepareOptionsMenu() to show action bar icons
}
public void onDrawerOpened(View drawerView) {
// calling onPrepareOptionsMenu() to hide action bar icons
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
public void displayView(int position) {
mPager.setCurrentItem(position, true);
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
Hi all i want to put navigation drawer in all activity.
Layout file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/left_drawer"
android:layout_width="275dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/black"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:paddingLeft="5dp" />
</android.support.v4.widget.DrawerLayout>
In other activity i am extending this class. But this this not working only this is the drawer logo is coming in the other activity page.
Please tell what i am doing wrong here.
Thanks in advance.
I find the solution. Thanks for your kind help.
Update:
Please find my answer below.
Create a layout drawer_layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/left_drawer"
android:layout_width="275dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/black"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:paddingLeft="5dp" />
drwaer_custom_layout_file This is for each single row in drawer.(Customize based on requirement):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="5dp" >
<LinearLayout
android:id="#+id/itemLayoutColor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/drawer_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:contentDescription="#string/sku_search"
android:paddingLeft="15dp" />
<TextView
android:id="#+id/drawer_itemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="10dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/white" />
</LinearLayout>
<View
android:id="#+id/dividerView"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#191919"
android:paddingLeft="15dp" >
</View>
Create an Adapter class. (Remove the element which is not relevant for you):
public class CustomDrawerAdapter extends ArrayAdapter<DrawerItem> {
Context context;
List<DrawerItem> drawerItemList;
int layoutResID;
int selectedPosition;
public CustomDrawerAdapter(Context context, int layoutResourceID,
List<DrawerItem> listItems, int selectedPosition) {
super(context, layoutResourceID, listItems);
this.context = context;
this.drawerItemList = listItems;
this.layoutResID = layoutResourceID;
this.selectedPosition = selectedPosition;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
DrawerItemHolder drawerHolder;
View view = convertView;
if (view == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
drawerHolder = new DrawerItemHolder();
view = inflater.inflate(layoutResID, parent, false);
drawerHolder.ItemName = (TextView) view
.findViewById(R.id.drawer_itemName);
drawerHolder.icon = (ImageView) view.findViewById(R.id.drawer_icon);
drawerHolder.itemLayoutColor = (LinearLayout) view
.findViewById(R.id.itemLayoutColor);
// drawerHolder.dividerView = (View) view
// .findViewById(R.id.dividerView);
view.setTag(drawerHolder);
} else {
drawerHolder = (DrawerItemHolder) view.getTag();
}
DrawerItem dItem = (DrawerItem) this.drawerItemList.get(position);
drawerHolder.ItemName.setTypeface(tfNormal);
drawerHolder.ItemName.setText(dItem.getItemName());
if (dItem.getImgResID() != 0) {
drawerHolder.icon.setImageDrawable(view.getResources().getDrawable(
dItem.getImgResID()));
} else {
drawerHolder.ItemName.setTextColor(context.getResources().getColor(
R.color.black));
drawerHolder.itemLayoutColor.setBackgroundColor(context
.getResources().getColor(R.color.pGray));
drawerHolder.icon.setVisibility(View.GONE);
// drawerHolder.dividerView.setBackgroundColor(Color.GREEN);
}
if(selectedPosition == position){
drawerHolder.itemLayoutColor.setBackgroundColor(context
.getResources().getColor(R.color.lightyellow));
}
return view;
}
private static class DrawerItemHolder {
TextView ItemName;
ImageView icon;
LinearLayout itemLayoutColor;
// View dividerView;
}
}
Create a class that will extends Activity write below methods:
#Override
public void setContentView(int layoutResID) {
mDrawerLayout = (DrawerLayout) getLayoutInflater().inflate(
R.layout.navigation_drawer_layout, null);
actContent = (FrameLayout) mDrawerLayout
.findViewById(R.id.content_frame);
getLayoutInflater().inflate(layoutResID, actContent, true);
super.setContentView(mDrawerLayout);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
}
return true;
}
protected void navigationDrawer(DrawerLayout mDrawerLayout,
ListView mDrawerList, int selectedPosition) {
this.selectedPosition = selectedPosition;
activity = (Activity) NavigationDrawerBaseActivity.this;
actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
this.mDrawerLayout = mDrawerLayout;
this.mDrawerList = mDrawerList;
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// set up the drawer's list view with items and click listener
mDataList = new ArrayList<DrawerItem>();
**********Here add the items in the list***********
i.e.
mDataList.add(new DrawerItem(DrawerConstant.LOGOUT,
R.drawable.ic_signout));
adapter = new CustomDrawerAdapter(this,
R.layout.drawer_custom_single_layout, mDataList,
selectedPosition);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
public class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (position != selectedPosition) {
selectItem(position);
}
}
protected void selectItem(int position) {
// update the main content by replacing fragments
switch (position) {
case 0:
// Call the another activity
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(mDrawerList);
break;
case 1:
// Call the another activity
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(mDrawerList);
break;
case 2:
// Call the another activity
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(mDrawerList);
break;
default:
break;
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
}
Add the below code in Activity wherever you want to put Navigation Drawer:
Extends the NavigationDrawerBaseActivity class.
After setContentView call below method:
// set Naviagtion Drawer
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ListView mDrawerList = (ListView) findViewById(R.id.left_drawer);
super.navigationDrawer(mDrawerLayout, mDrawerList, 1);
Add below method in same Activity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
}
}
Create a BaseActivity class that implements the drawer, and let all your activities extend this BaseActivity.
#Override
public void setContentView(int layoutResID) {
mDrawerLayout = (DrawerLayout) getLayoutInflater().inflate(R.layout.activity_main, null);
actContent = (FrameLayout) mDrawerLayout.findViewById(R.id.frame_container);
setContentView(mDrawerLayout);
getLayoutInflater().inflate(layoutResID, actContent, true);
}
Set the drawer layout as main content
I have achieved the asked scenario in the following procedure.
Xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/venue_bg"
android:orientation="vertical" >
<!-- The navigation drawer -->
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayoutMain"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/frameLayoutContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ExpandableListView
android:id="#+id/ExpandableList"
android:layout_width="#dimen/drawer_size"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#drawable/left_drawer_item_gradient"
android:choiceMode="singleChoice"
android:clickable="true"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
<!-- content layout -->
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
setcontentView inside NavigationDrawerBaseActivity
#Override
public void setContentView(int layoutID)
{
// TODO Auto-generated method stub
fullLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.main_menu_activity_container, null);
pocketFrame = (FrameLayout) fullLayout.findViewById(R.id.frameLayoutContent);
getLayoutInflater().inflate(layoutID, pocketFrame, true);
super.setContentView(fullLayout);
}
In your NavigationDrawerBaseActivity make a method which sets setcontentView & take layout as an argument, & in every extended child class override that method & pass layout in argument. In xml #+id/ExpandableList is a list which is in left & #+id/frameLayoutContent acts like a container for incoming argument layouts, this will give you the replica of fraqgments replacing in a container.
Note: This is just a work around, recommended is Fragments.
You can add an abstract method to get the layout for the activity which it's extending your navigation drawer: public abstract int NavigatonDrawerBaseActivity(); and make your class an abstract class (here use setContentView(NavigatonDrawerBaseActivity())). Then in the class which it's extending the Navigation drawer implements the method and pass it your xml layout (not use the setContentView method):
#Override
public int NavigatonDrawerBaseActivity() {
return R.layout.yourLayout;
}
And finally in your layout you need to add the same code of your NavigationDrawerBaseActivity xml:
This works form me using fragments. Hope it helps.
this work for me
public class MyDrawer extends AppCompatActivity {
ActionBarDrawerToggle toggle;
protected RelativeLayout fullLayout;
protected FrameLayout frameLayout;
#Override
public void setContentView(final int layoutResID) {
fullLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.mydrawer, null);
frameLayout = (FrameLayout) fullLayout.findViewById(R.id.drawer_frame);
getLayoutInflater().inflate(layoutResID, frameLayout, true);
super.setContentView(fullLayout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout3);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
drawer.closeDrawers();
int itemId = menuItem.getItemId();
Toast.makeText(getApplicationContext(), menuItem.getTitle().toString(),
Toast.LENGTH_LONG).show();
//navigationView.getMenu().findItem(R.id.drawer_5_reasons).setChecked(true);
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (toggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="0dp"
android:id="#+id/drawer_framelayout">
<FrameLayout
android:id="#+id/drawer_frame2"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start"
>
<FrameLayout
android:id="#+id/drawer_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<android.support.design.widget.NavigationView android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main2"
app:menu="#menu/activity_main_drawer"
android:background="#fefefd" />
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
for use:
public class yourclass extends MyDrawer {
is .setOnItemClickListener work?yes
<android.support.v4.widget.DrawerLayout>
<FrameLayout>
your main content stuff here
</android.support.v4.widget.DrawerLayout>
<FrameLayout>
your main content stuff here(.setOnItemClickListener)
I am trying to implement both navigation drawer and view pager in same activity. Navigation drawer works fine but the view pager is not working, also i am getting null pointer on right swipe when navigation drawer is opened (Null pointer at android. support. v4. widget. DrawerLayout. isContentView(DrawerLayout.java:840). I am attaching the main xml layout and code below.
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</android.support.v4.view.ViewPager>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
Activity class is given below
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
private MainActivity mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
ViewPager vp = (ViewPager) findViewById(R.id.viewpager);
CustomPagerAdapter adapter = new CustomPagerAdapter(mContext);
vp.setAdapter(adapter);
vp.setPageTransformer(false, new ViewPager.PageTransformer() {
#Override
public void transformPage(View page, float position) {
final float normalizedposition = Math.abs(Math.abs(position) - 1);
page.setScaleX(normalizedposition / 2 + 0.5f);
page.setScaleY(normalizedposition / 2 + 0.5f);
}
});
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /*
* "open drawer" description for
* accessibility
*/
R.string.drawer_close /*
* "close drawer" description for
* accessibility
*/
) {
#Override
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
// view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
return true;
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
public class CustomPagerAdapter extends PagerAdapter {
private Context context;
int index = 2;
// public CustomPagerAdapter(Context context, Vector<View> pages) {
// this.context = context;
// this.pages = pages;
// }
public CustomPagerAdapter(Context context) {
this.context = context;
this.index = 2;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = (LayoutInflater.from(container.getContext()));
// View page = pages.get(position);
View view = null;
if (position == 0) {
view = inflater.inflate(R.layout.page_one_views, null);
((ViewPager) container).addView(view);
}
else {
// page.setBackgroundColor(colors.get(position));
// container.addView(page);
view = inflater.inflate(R.layout.page_two, null);
((ViewPager) container).addView(view);
}
return view;
}
#Override
public int getCount() {
return index;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}
Please help me. Thanks in advance
The DrawerLayout should be the root element. Put the ViewPager inside it.
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:layout_below="#+id/top_bar"
android:background="#android:color/darker_gray"
android:choiceMode="singleChoice"
android:divider="#android:color/background_dark"
android:dividerHeight="1dp" />
</android.support.v4.widget.DrawerLayout>
To achieve something like this:
Use simple one:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</android.support.v4.view.ViewPager>
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
In my application i want to show google map in a Fragment. My activity class is given below.
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_launcher, R.string.app_name,
R.string.action_settings) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_websearch:
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, "Nothing", Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
onItemSelected(mPlanetTitles[position]);
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void onItemSelected(String link) {
DetailFragment fragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detailFragment);
fragment.setText(link);
}
}
As shown in the code in the Activity i am using a DrawyerLayout inside that there are four items. When the user press the Item. I am showing Fragment where the MapFragment kept inside.
Please see the Main Xml layout file.
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment
android:id="#+id/detailFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
class="com.example.mynavigation.DetailFragment"
android:visibility="invisible" >
</fragment>
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
My Fragment Class.
public class DetailFragment extends Fragment {
GoogleMap map ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
System.out.println("kkkkkkkkkkkk");
View view = inflater.inflate(R.layout.fragment_rssitem_detail,
container, true);
return view;
}
public void setText(String item) {
System.out.println("set Tewxt");
TextView view = (TextView) getView().findViewById(R.id.detailsText);
view.setText(item);
}
}
And the fragment_rssitem_detail.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/detailsText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_marginTop="20dip"
android:text="Default Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<FrameLayout
android:id="#+id/map_frame"
android:layout_width="fill_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp" />
</FrameLayout>
<!-- <ListView
android:id="#+id/list_fragment"
android:name="com.myapp.ListFragment"
android:layout_width="wrap_content"
android:layout_height="fill_parent" /> -->
</LinearLayout>
Put only LinearLayout at where you want to put map in your xml and push map programatically as below:
private SupportMapFragment mapFragment;
mapFragment = new SupportMapFragment();
addFragment(lnrMap.getId(), mapFragment); //lnrMap is your LinearLayout from xml.
googleMap = mapFragment.getExtendedMap();
AddFragment Method(),Put this method in your DetailFragment class:
public void addFragment(int layoutId, Fragment fragment) {
FragmentManager fm = getChildFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(layoutId, fragment);
ft.commit();
}