Android Adapter getView - android

Sorry, this issue has been treated several times but I still can not solve it.
I have a Navigation Drawer with Fragment that works fine, but if I use it only with Activity I get error
You must supply a resource ID for a TextView.
This is my adapter, I do not think anything wrong. Thanks for the help
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.text1);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
return convertView;
}
}
and XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp" >
<ImageView
android:id="#+id/icon"
android:layout_width="35dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:contentDescription="#string/desc_list_item_icon"
android:src="#drawable/img_1" />
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/icon"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/icon"
android:gravity="center_vertical"
android:paddingLeft="5dp"
android:text="tt"
android:textSize="18sp" />
</RelativeLayout>
in my Activity class
mTitle = mDrawerTitle = getTitle();
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.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
navDrawerItems = new ArrayList<NavDrawerItem>();
//items to array
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, 0)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, 0)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, 0)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, 0)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, 0)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, 0)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, 0)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, 0)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons.getResourceId(8, 0)));
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
mDrawerList.setAdapter(adapter);
getActionBar().setDisplayHomeAsUpEnabled(true);
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) {
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);

just create a holder class and use textview inside the getview() like this.
holder.textview = (TextView) convertView.findViewById(R.id.text1);
and below class for Holder class.
public class Holder {
TextView textview;
//CheckBox check;
}

Related

Add section to navigation drawer

i have the below code :
activity.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" >
<!-- 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:background="#color/list_background"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</android.support.v4.widget.DrawerLayout>
MainActivity.java
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav 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 adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
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
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
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) {
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);
}
}
/**
* Slide menu item click listener
* */
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);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, 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);
}
/**
* 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);
}
}
and for the section i have the below xml :
<?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="wrap_content"
android:background="#FFF" >
<TextView
android:id="#+id/navmenusection_label"
style="?android:attr/listSeparatorTextViewStyle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#BBB"
android:paddingBottom="7dp"
android:paddingTop="7dp"
android:text="Section"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</RelativeLayout>
So how can i add the section in the navigation drawer. ?
i have change the NavDrawerListAdapter.java file :
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);
/*
* convertView = mInflater.inflate(R.layout.navdrawer_section,
* parent, false);
*/
}
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;
}
}
convertView = mInflater.inflate(R.layout.navdrawer_section,
parent, false);
i have put this in getView() but i am getting the error .
Logcat :
FATAL EXCEPTION: main
Process: com.novumlogic.euphoria, PID: 26846
java.lang.NullPointerException
at com.novumlogic.euphoria.adapter.NavDrawerListAdapter.getView(NavDrawerListAdapter.java:59)
at android.widget.AbsListView.obtainView(AbsListView.java:2338)
at android.widget.ListView.makeAndAddView(ListView.java:1812)
at android.widget.ListView.fillDown(ListView.java:698)
at android.widget.ListView.fillFromTop(ListView.java:759)
at android.widget.ListView.layoutChildren(ListView.java:1631)
at android.widget.AbsListView.onLayout(AbsListView.java:2149)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:702)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:374)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2317)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2023)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1189)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6223)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:560)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
how can i add the section ?
first remove any changes that you have done which causes a null pointer exception then go to drwer_list_item.xml and add text view for your section part, then go to NavDrawerItem.class and add:
private String section;
change your constructor to this:
public NavDrawerItem(String title, int icon,String section){
this.title = title;
this.icon = icon;
this.section= section;
}
you also have to add getters and setters for your private section instanse:
public String getSection(){
return this.section;
}
public void setSection(String section){
this.section = section;
}
then go to navDrewerListAdapter.class and add this:
TextView txtSection = (TextView) convertView.findViewById(R.id.section);
last thing you have to do is to change your navDrawerItems.add from this:
navDrawerItems.add(new NavDrawerItem(navMenuTitles[index], navMenuIcons
.getResourceId(index, -1)));
to this:
navDrawerItems.add(new NavDrawerItem(navMenuTitles[index], navMenuIcons
.getResourceId(index, -1),"String Section"));
hope this will help.

Center aligning of title in action bar of activity and fragments

My HomeActivity consists of Sliding Menu where each option in Sliding Menu opens a new Fragment with different title. I want that title in action bar of fragments and activity appear in center.I tried using custom layout for fragment-
final ActionBar ab = getActivity().getActionBar();
ab.setHomeButtonEnabled(true);
ab.setDisplayHomeAsUpEnabled(true);
ab.setDisplayShowTitleEnabled(false);
// actionBar.setDisplayShowHomeEnabled(false);
ab.setCustomView(R.layout.action_bar);
ab.setDisplayShowCustomEnabled(true);
actionbar.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:fontFamily="sans-serif"
android:maxLines="1"
android:text="title"
android:textSize="20sp"
android:gravity="center"/>
</RelativeLayout>
This aligns the title in center but the sliding menu disappears.I want that all my fragments display title in center of action bar and sliding menu should not vanish.Here is my code for manifest,styles.xml,activity and one of the fragment and also xml file for Home Activity..
Manifest
<activity
android:name=".ui.slidingmenu.Home"
android:label="#string/app_name"
android:theme="#style/MyTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Styles.xml
<style name="MyTheme" parent="#android:style/Theme.Holo.Light">
<item name="android:actionBarStyle">#style/MyActionBar</item>
<item name="android:actionBarTabStyle">#style/MyTheme.ActionBar.TabView</item>
<item name="android:actionBarTabTextStyle">#style/MyTheme.ActionBar.TabText</item>
<style name="MyActionBar" parent="#android:style/Widget.Holo.Light.ActionBar">
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:background">#12ABEE</item>
<item name="android:gravity">center</item>
<item name="android:actionMenuTextColor">#ffffff</item>
<item name="android:titleTextStyle">#style/myTheme.ActionBar.Text</item>
</style>
<style name="myTheme.ActionBar.Text" parent="#android:style/TextAppearance">
<item name="android:textColor">#ffffff</item>
<item name="android:textStyle">bold</item>
<item name="android:gravity">center</item>
</style>
HomeActivity
public class Home extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle, mTitle;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
private String mName, mProfileimage;
private LinearLayout linearLayout;
private TextView nameTextView;
private ImageView profileImageView;
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = 40;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slidermenu);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
mTitle = mDrawerTitle = getTitle();
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
linearLayout = (LinearLayout) findViewById(R.id.left_drawer_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
nameTextView = (TextView) findViewById(R.id.username);
profileImageView = (ImageView) findViewById(R.id.drawer_profile_image);
navDrawerItems = new ArrayList<NavDrawerItem>();
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(Home.this);
mName = app_preferences.getString("name", "null");
mProfileimage = app_preferences.getString("profileimage", "null");
nameTextView.setText(mName);
try {
URL url = new URL(mProfileimage);
Bitmap lProfileBitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
lProfileBitmap = getRoundedCornerBitmap(lProfileBitmap);
BitmapDrawable lProfileDrawable = new BitmapDrawable(lProfileBitmap);
profileImageView.setBackgroundDrawable(lProfileDrawable);
} catch (Exception e) {
Log.d("error in image", e.toString());
}
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons.getResourceId(8, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuIcons.getResourceId(9, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[10], navMenuIcons.getResourceId(10, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[11], navMenuIcons.getResourceId(11, -1)));
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
mDrawerList.setAdapter(adapter);
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);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
displayView(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(this.linearLayout);
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 HF();
break;
case 1:
fragment = new NF();
break;
case 2:
fragment = new FD();
break;
case 3:
fragment = new FDFD();
break;
case 4:
fragment = new VideosFragment();
break;
case 5:
fragment = new DG();
break;
case 6:
fragment = new DSF();
break;
case 7:
fragment = new FDSF();
break;
case 8:
fragment = new DFSD();
break;
case 9:
fragment = new DFSF();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(this.linearLayout);
} 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);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
displayView(position);
}
}
}
VideosFragment
public class VideosFragment extends Fragment {
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
ActionBar actionBar;
private int countClick;
private FragmentActivity myContext;
private ViewPager viewPager;
private String[] tabs = {"All Teams Videos", "Player Videos", "My Team Videos"};
public VideosFragment() {
}
#Override
public void onAttach(Activity activity) {
myContext = (FragmentActivity) activity;
super.onAttach(activity);
}
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.videos, container, false);
actionBar = getActivity().getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
return rootView;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_search2:
Intent i = new Intent();
i.setClass(myContext, LS.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
slidermenu.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">
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/left_drawer_view"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#drawable/bgmenu"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_weight="0">
<ImageView
android:id="#+id/drawer_profile_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:scaleType="centerCrop"
android:src="#drawable/profileblock">
</ImageView>
<ImageView
android:id="#+id/drawer_profile_image"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_alignLeft="#+id/drawer_profile_background"
android:layout_alignRight="#+id/drawer_profile_background"
android:layout_centerHorizontal="true"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="4dp"
android:scaleType="centerCrop"></ImageView>
<ImageView
android:id="#+id/settingicon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/drawer_profile_background"
android:layout_marginLeft="-15dp"
android:layout_toRightOf="#+id/drawer_profile_background"
android:background="#drawable/settings" />
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/drawer_profile_background"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#android:color/white"></TextView>
</RelativeLayout>
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="start"
android:layout_marginTop="2dp"
android:layout_weight="4"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="2dp"
android:listSelector="#drawable/menuselector" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Try adding the following to your TextView of your custom ActionBar layout to center the text.
android:layout_gravity="center"
Also, to explain, when you set gravity="center" that just centers the text in the TextView layout.
Next, your icon hides because your custom layout overlaps the icon for the navigation drawer (siding menu). To fix this, the easiest way is to set a margin for your entire layout (in your case, the relative layout of your custom actionbar layout). I think 30dp should be enough to cover all screen sizes.
android:layout_marginRight="30dp"

How to close navigation drawer through touch on the Screen in android

I have success fully open 4 different navigation drawer from left side when I click 4 different background button. Now when I click 1st button the 1st navigation drawer opening and closing as well. But problem is that when I click 2nd button drawer is opening but not closing onclick of list item and touch outside of the drawer. See below image want.
see code public class MainActivity extends Activity {
private ListView mDrawerList;
private CharSequence mDrawerTitle;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private RelativeLayout leftRL;
private RelativeLayout rightRL;
private RelativeLayout byleft;
private RelativeLayout toleft;
private DrawerLayout drawerLayout;
final String[] data ={"one","two","three"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// I'm removing the ActionBar.
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
mTitle = mDrawerTitle = getTitle();
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
final ListView navList = (ListView) findViewById(R.id.drawer);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
leftRL = (RelativeLayout)findViewById(R.id.whatYouWantInLeftDrawer);
rightRL = (RelativeLayout)findViewById(R.id.YouWantInRightDrawer);
byleft = (RelativeLayout)findViewById(R.id.WantInRightDrawer);
toleft = (RelativeLayout)findViewById(R.id.InRightDrawer);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
}
public void onLeft(View view)
{
drawerLayout.openDrawer(leftRL);
}
public void ToLeft(View view)
{
drawerLayout.openDrawer(rightRL);
drawerLayout.setFocusableInTouchMode(true);
}
public void byLeft(View view)
{
drawerLayout.openDrawer(byleft);
}
public void throughLeft(View view)
{
drawerLayout.openDrawer(toleft);
}
}
<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" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#0F0FF0"
>
<Button
android:id="#+id/home_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:background="#drawable/ic_home"
android:onClick="onLeft" />
<Button
android:id="#+id/profile_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/home_btn"
android:background="#drawable/ic_people"
android:onClick="ToLeft"
android:clickable="true"
/>
<Button
android:id="#+id/chat_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/profile_btn"
android:background="#drawable/ic_photos"
android:onClick="byLeft"
android:clickable="true"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/chat_btn"
android:background="#drawable/ic_whats_hot"
android:onClick="throughLeft"
android:clickable="true"
/>
</RelativeLayout>
<!-- Left Drawrer -->
<RelativeLayout
android:id="#+id/YouWantInRightDrawer"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="left" >
<ListView
android:id="#+id/firsr_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_green_light" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/WantInRightDrawer"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="left" >
<ListView
android:id="#+id/second_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_blue_light" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/InRightDrawer"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="left" >
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_green_dark" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/whatYouWantInLeftDrawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start">
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/list_background"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
Hi friends i got the solution see code below
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0000" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Open Drawer1" />
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Open Drawer2" />
<Button
android:id="#+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Open Drawer3" />
<Button
android:id="#+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Open Drawer4" />
</LinearLayout>
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
android:cacheColorHint="#00000000"
android:choiceMode="singleChoice"
android:divider="#android:color/black" >
</ListView>
</android.support.v4.widget.DrawerLayout>
Java:
public class MainActivity extends Activity {
private Button btn1, btn2, btn3, btn4;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
String[] string = { "one", "two", "three", "four", "five" };
String[] string2 = { "one", "two", "three" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_drawer_layout);
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
btn3 = (Button) findViewById(R.id.button3);
btn4 = (Button) findViewById(R.id.button4);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_list_item_1,
string);
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
mDrawerList.setVisibility(View.INVISIBLE);
} else {
mDrawerList.setAdapter(arrayAdapter);
mDrawerLayout.openDrawer(mDrawerList);
mDrawerList.invalidate();
}
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_list_item_1,
string2);
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
mDrawerList.setVisibility(View.INVISIBLE);
} else {
mDrawerList.setAdapter(arrayAdapter1);
mDrawerLayout.openDrawer(mDrawerList);
mDrawerList.invalidate();
}
}
});
}
}
Happy coding!!!!

Android: 2 Listviews in NavigationDrawer

I've done a Navigation Drawer in my app and the works ok. But I'm trying to put another Listview below the above but I can not get the new display on the screen. I have put the Navigation Drawer in BaseActivity class. What can be the error? This is my code:
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" >
<LinearLayout
...
</LinearLayout>
<LinearLayout android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="vertical">
<ListView
android:id="#+id/listview_drawer"
style="#style/scrollbar"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/grisTransparente"
android:choiceMode="singleChoice"
android:divider="#color/negro"
android:dividerHeight="1dp" />
<ListView
android:id="#+id/listview_drawer2"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/negro"
android:dividerHeight="1dp"
android:background="#color/grisTransparente"
style="#style/scrollbar"/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
BASEACTIVITY
private void cargarDrawerLayout(Bundle b) {
mTitle = mDrawerTitle = getTitle();
textosMenuLateral = getResources().getStringArray(R.array.titulos_drawer);
textosMenuLateral2 = getResources().getStringArray(R.array.titulos_drawer2);
iconosMenuLateral = getResources()
.obtainTypedArray(R.array.iconos_drawer);
iconosMenuLateral2 = getResources()
.obtainTypedArray(R.array.iconos_drawer2);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.listview_drawer);
mDrawerList2 = (ListView) findViewById(R.id.listview_drawer2);
View header = getLayoutInflater().inflate(R.layout.drawer_header, null);
mDrawerList.addHeaderView(header);
mDrawerList2.addHeaderView(header);
int[] colores = {0, 0xFFFFFFFF, 0};
mDrawerList.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colores));
mDrawerList.setDividerHeight(4);
mDrawerList2.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colores));
mDrawerList2.setDividerHeight(4);
navDrawerItems = new ArrayList<DrawerItem>();
navDrawerItems2 = new ArrayList<DrawerItem>();
navDrawerItems.add(new DrawerItem(textosMenuLateral[0], iconosMenuLateral.getResourceId(0, -1)));
navDrawerItems.add(new DrawerItem(textosMenuLateral[1], iconosMenuLateral.getResourceId(1, -1)));
navDrawerItems.add(new DrawerItem(textosMenuLateral[2], iconosMenuLateral.getResourceId(2, -1)));
navDrawerItems2.add(new DrawerItem(textosMenuLateral2[0], iconosMenuLateral2.getResourceId(0, -1)));
iconosMenuLateral.recycle();
iconosMenuLateral2.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
mDrawerList2.setOnItemClickListener(new SlideMenuClickListener2());
adapter = new DrawerListAdapter(getApplicationContext(),
navDrawerItems,
perfilObj.getColor(),
pos);
mDrawerList.setAdapter(adapter);
adapter2 = new DrawerListAdapter(getApplicationContext(),
navDrawerItems2,
perfilObj.getColor(),
pos2);
mDrawerList2.setAdapter(adapter2);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.drawable.icono_drawer,
R.string.app_name,
R.string.app_name
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private class SlideMenuClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView textView = (TextView) view.findViewById(R.id.title);
textView.setTypeface(null, Typeface.BOLD);
opcionesPanelLateral(position);
}
}
private class SlideMenuClickListener2 implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView textView = (TextView) view.findViewById(R.id.title);
textView.setTypeface(null, Typeface.BOLD);
opcionesPanelLateral2(position);
}
}
private void opcionesPanelLateral(int position) {
Intent i;
switch (position - 1) {
case 0:
case 1:
case 2:
case 3:
break;
default:
break;
}
mDrawerList.setItemChecked(pos, true);
mDrawerList.setSelection(pos);
setTitle(textosMenuLateral[pos]);
mDrawerLayout.closeDrawer(mDrawerList);
}
private void opcionesPanelLateral2(int position) {
Intent i;
switch (position) {
case 0:
break;
default:
break;
}
mDrawerList2.setItemChecked(pos, true);
mDrawerList2.setSelection(pos);
mDrawerLayout.closeDrawer(mDrawerList2);
}
Have you tried adding layout weight to your ListViews? A ListView will naturally match it's parent's size.
Layout Weight I hope it helps.
<ListView
android:id="#+id/listview_drawer"
style="#style/scrollbar"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/grisTransparente"
android:choiceMode="singleChoice"
android:divider="#color/negro"
android:dividerHeight="1dp"
android:layout_weight="1"/>
<ListView
android:id="#+id/listview_drawer2"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/negro"
android:dividerHeight="1dp"
android:background="#color/grisTransparente"
style="#style/scrollbar"
android:layout_weight="1"/>

How to Add icons adjacent to titles for Android Navigation Drawer

I am currently working on an android app for 4.2.2 that uses the new NavigationDrawer. It works like a charm except for adding icons.
I found some sample code in which the List view becomes a Relative layout in which 2 parallel arrays are nested and rendered by an Array Adapter based on a menu model a way that they are synchronized, I think.
Here is the MainActivity:
package com.sorin.medisynced.main;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.sorin.medisynced.R;
import com.sorin.medisynced.filepickerio.FilepickerSaver;
import com.sorin.medisynced.filepickerio.FilepickerViewer;
import com.sorin.medisynced.qr.IntentIntegrator;
public class MediSyncedMainActivity extends Activity {
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private String[] menuItemsData;
private String[] menuItemsTools;
private ActionBarDrawerToggle mDrawerToggle;
private String[] menuItemsEmergency;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_drawer);
mTitle = mDrawerTitle = getTitle();
// set click listener for list drawer
// mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
_initMenu();
// 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 */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(getString(R.string.drawer_close));
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(getString(R.string.drawer_open));
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// selectItem(0);
}
}
private void _initMenu() {
NsMenuAdapter mAdapter = new NsMenuAdapter(this);
// Add First Header
mAdapter.addHeader(R.string.menu_data);
// Add first block
menuItemsData = getResources().getStringArray(R.array.menu_data);
String[] menuDataIcons = getResources().getStringArray(
R.array.data_menu_icons);
int dataIcons = 0;
for (String item : menuItemsData) {
int id_data_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_data_icon = getResources()
.getIdentifier(menuDataIcons[dataIcons], "drawable",
this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_data_title,
id_data_icon);
mAdapter.addItem(mItem);
dataIcons++;
}
// Add second header
mAdapter.addHeader(R.string.menu_tools);
// Add second block
menuItemsTools = getResources().getStringArray(R.array.menu_tools);
String[] menuToolsIcons = getResources().getStringArray(
R.array.tools_menu_icons);
int toolsIcons = 0;
for (String item : menuItemsTools) {
int id_tools_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_tools_icon = getResources().getIdentifier(
menuToolsIcons[toolsIcons], "drawable",
this.getPackageName());
// creating drawer menu model
NsMenuItemModel mItem = new NsMenuItemModel(id_tools_title,
id_tools_icon);
mAdapter.addItem(mItem);
toolsIcons++;
}
// Add third header
mAdapter.addHeader(R.string.menu_emergency);
// Add third block
menuItemsEmergency = getResources().getStringArray(
R.array.menu_emergency);
String[] menuEmerIcons = getResources().getStringArray(
R.array.emergency_menu_icons);
int emerIcons = 0;
for (String item : menuItemsEmergency) {
int id_emer_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_emer_icon = getResources()
.getIdentifier(menuEmerIcons[emerIcons], "drawable",
this.getPackageName());
// creating drawer menu model
NsMenuItemModel mItem = new NsMenuItemModel(id_emer_title,
id_emer_icon);
mAdapter.addItem(mItem);
emerIcons++;
}
mDrawerList = (ListView) findViewById(R.id.drawer);
if (mDrawerList != null)
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
#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);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#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);
menu.findItem(R.id.action_save).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
/*
* The action bar home/up should open or close the drawer.
* ActionBarDrawerToggle will take care of this.
*/
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch (item.getItemId()) {
case R.id.action_qrscan:
IntentIntegrator integrator = new IntentIntegrator(
MediSyncedMainActivity.this);
integrator.initiateScan();
Toast.makeText(this, "Scan Qr Code", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_filepicker_save:
startActivity(new Intent(this, FilepickerSaver.class));
Toast.makeText(this, "Save data on cloud", Toast.LENGTH_SHORT)
.show();
return true;
case R.id.action_filepicker_view:
startActivity(new Intent(this, FilepickerViewer.class));
Toast.makeText(this, "View data from cloud", Toast.LENGTH_SHORT)
.show();
return true;
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_SEARCH);
intent.putExtra(SearchManager.QUERY, getApplicationContext()
.getDatabasePath(DROPBOX_SERVICE));
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.search_database,
Toast.LENGTH_LONG).show();
}
return true;
default:
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// Highlight the selected item, update the title, and close the
// drawer
// update selected item and title, then close the drawer
mDrawerList.getCount();
mDrawerList.setItemChecked(position, true);
String text = "menu click... should be implemented";
Toast.makeText(MediSyncedMainActivity.this, text, Toast.LENGTH_LONG)
.show();
mDrawerLayout.closeDrawer(mDrawerList);
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
}
Here is the menu model:
package com.sorin.medisynced.main;
public class NsMenuItemModel {
public int title;
public int iconRes;
public boolean isHeader;
public NsMenuItemModel(int title, int iconRes,boolean header) {
this.title = title;
this.iconRes = iconRes;
this.isHeader=header;
}
public NsMenuItemModel(int title, int iconRes) {
this(title,iconRes,false);
}
}
Here ist the ArrayAdapter implementation:
package com.sorin.medisynced.main;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.sorin.medisynced.R;
public class NsMenuAdapter extends ArrayAdapter<NsMenuItemModel> {
/*
* public NsMenuAdapter(Context context, int resource, int
* textViewResourceId, String[] objects) { super(context,
* R.layout.ns_menu_row, textViewResourceId, objects); }
*/
public NsMenuAdapter(Context context) {
super(context, 0);
}
public void addHeader(int title) {
add(new NsMenuItemModel(title, -1, true));
}
public void addItem(int title, int icon) {
add(new NsMenuItemModel(title, icon, false));
}
public void addItem(NsMenuItemModel itemModel) {
add(itemModel);
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return getItem(position).isHeader ? 0 : 1;
}
#Override
public boolean isEnabled(int position) {
return !getItem(position).isHeader;
}
public static class ViewHolder {
public final TextView textHolder;
public final ImageView imageHolder;
public ViewHolder(TextView text1, ImageView image1) {
this.textHolder = text1;
this.imageHolder = image1;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
NsMenuItemModel item = getItem(position);
ViewHolder holder = null;
View view = convertView;
if (view == null) {
int layout = R.layout.ns_menu_row;
if (item.isHeader)
layout = R.layout.ns_menu_row_header;
view = LayoutInflater.from(getContext()).inflate(layout, null);
TextView text1 = (TextView) view.findViewById(R.id.menurow_title);
ImageView image1 = (ImageView) view.findViewById(R.id.menurow_icon);
view.setTag(new ViewHolder(text1, image1));
}
if (holder == null && view != null) {
Object tag = view.getTag();
if (tag instanceof ViewHolder) {
holder = (ViewHolder) tag;
}
}
if(item != null && holder != null)
{
if (holder.textHolder != null)
holder.textHolder.setText(item.title);
if (holder.imageHolder != null) {
if (item.iconRes > 0) {
holder.imageHolder.setVisibility(View.VISIBLE);
holder.imageHolder.setImageResource(item.iconRes);
} else {
holder.imageHolder.setVisibility(View.GONE);
}
}
}
return view;
}
}
The string-array xml:
<string-array name="menu_data">
<item>menu_data_patient_profile</item>
<item>menu_data_hospital_staff</item>
<item>menu_data_xray_results</item>
<item>menu_data_lab_results</item>
<item>menu_data_medical_supplies_index</item>
<item>menu_data_hospital_forms_index</item>
<item>menu_data_prescriptions_index</item>
<item>menu_data_illness_index</item>
<item>menu_data_drugs_index</item>
<item>menu_data_hospital_interactive_map</item>
</string-array>
<string-array name="menu_tools">
<item>menu_tools_ecg</item>
<item>menu_tools_pulse</item>
<item>menu_tools_microscope_feed</item>
<item>menu_tools_blood_pressure</item>
<item>menu_tools_temperature</item>
<item>menu_tools_radiation_levels</item>
<item>menu_tools_movement_log</item>
</string-array>
<string-array name="menu_emergency">
<item>menu_emergency_call_ambulance</item>
<item>menu_emergency_call_helicopter</item>
<item>menu_emergency_call_nurse</item>
<item>menu_emergency_call_doctor</item>
</string-array>
<array name="data_menu_icons">
<item>ic_patient_profile</item>
<item>ic_hospital_staff</item>
<item>ic_xray_results</item>
<item>ic_lab_results</item>
<item>ic_medical_supplies_index</item>
<item>ic_hospital_forms_index</item>
<item>ic_prescription_index</item>
<item>ic_illness_index</item>
<item>ic_drugs_index</item>
<item>ic_hospital_interactive_map</item>
</array>
<array name="tools_menu_icons">
<item>ic_ecg</item>
<item>ic_pulse</item>
<item>ic_microscope_feed</item>
<item>ic_blood_pressure</item>
<item>ic_body_temperature</item>
<item>ic_radiation_levels</item>
<item>ic_movement_logger</item>
</array>
<array name="emergency_menu_icons">
<item>ic_call_ambulance</item>
<item>ic_call_helicopter</item>
<item>ic_call_nurse</item>
<item>ic_call_doctor</item>
</array>
and the main layout:
<!-- The main content view -->
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MediSyncedMainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/drawer_text" />
</RelativeLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#DADADC"
android:choiceMode="singleChoice"
android:divider="#android:color/darker_gray"
android:dividerHeight="1dp"
android:showDividers="middle" />
How can I simplify the approach. Is there a way to use one array instead of such a complicated structure.
B.t.w. you can find my project on github under:
https://github.com/greenspand/MediSynced
It is a medical app, hence the name.
Thx y'all.
You can use a custom list view along with the list adapter to display the counter besides the list item in the drawer. And then add whatever code you want to your counter method.
Here's the code I implemented in my navigation drawer supported android app :
getter/setter methods class for the drawer :
package info.aea.drawer;
public class NavDrawerItem {
private String title;
private String tag;
private int icon;
private String count = "0";
// boolean to set visibility of the counter
private boolean isCounterVisible = false;
public NavDrawerItem(){}
public NavDrawerItem(String title, String tag, int icon){
this.title = title;
this.tag = tag;
this.icon = icon;
}
public NavDrawerItem(String title, String tag, int icon, boolean isCounterVisible, String count){
this.title = title;
this.tag = tag;
this.icon = icon;
this.isCounterVisible = isCounterVisible;
this.count = count;
}
public String getTitle(){
return this.title;
}
public String getTag(){
return this.tag;
}
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 setTag(String tag){
this.tag = tag;
}
public void setIcon(int icon){
this.icon = icon;
}
public void setCount(String count){
this.count = count;
}
public void setCounterVisibility(boolean isCounterVisible){
this.isCounterVisible = isCounterVisible;
}
}
This is the list adapter I used to display the list. check the display count method in the end :
package info.aea.drawer;
import info.aea.snippets.R;
import java.util.ArrayList;
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 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 txtTag = (TextView) convertView.findViewById(R.id.tag);
TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
txtTag.setText(navDrawerItems.get(position).getTag());
// 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;
}
}
Corresponding list layout :
<?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="match_parent"
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:textStyle="bold"
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"/>
<TextView
android:id="#+id/tag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/icon"
android:layout_alignParentBottom="true"
android:layout_marginLeft="12dp"
android:textColor="#999967"
android:textSize="13sp"
android:textStyle="italic"
android:text="sample" />
</RelativeLayout>
and here's the main N-drawer class :
package info.aea.launch;
import info.aea.drawer.NavDrawerItem;
import info.aea.drawer.NavDrawerListAdapter;
import info.aea.snippets.R;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
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.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class LaunchActivity_NavDrawer extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private String[] navMenuTags;;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SnippetsDB_Helper logindb;
logindb=new SnippetsDB_Helper(this);
//logindb=logindb.open();
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// load slide menu tags
navMenuTags = getResources().getStringArray(R.array.nav_drawer_tags);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuTags[0], navMenuIcons.getResourceId(0, -1), true, "22" ));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuTags[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuTags[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuTags[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuTags[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuTags[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuTags[6], navMenuIcons.getResourceId(6, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuTags[7], navMenuIcons.getResourceId(7, -1), true, "22"));
// empty list
navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuTags[8], navMenuIcons.getResourceId(8, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuTags[9], navMenuIcons.getResourceId(9, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[10], navMenuTags[10], navMenuIcons.getResourceId(10, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[11], navMenuTags[11], navMenuIcons.getResourceId(11, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[12], navMenuTags[12], navMenuIcons.getResourceId(12, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[13], navMenuTags[13], navMenuIcons.getResourceId(13, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[14], navMenuTags[14], navMenuIcons.getResourceId(14, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[15], navMenuTags[15], navMenuIcons.getResourceId(15, -1)));
// Recycle the typed array
navMenuIcons.recycle();
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
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
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) {
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);
}
}
/**
* Slide menu item click listener
* */
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, 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:
Toast.makeText(getApplicationContext(), "code", Toast.LENGTH_LONG).show();
// Create new fragment and transaction
Fragment newFragment = new Fragment_Java();
// consider using Java coding conventions (upper char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.frame_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
return true;
case R.id.item1:
Toast.makeText(getApplicationContext(), "send a suggestion", Toast.LENGTH_LONG).show();
return true;
case R.id.item2:
Toast.makeText(getApplicationContext(), "Meet developers", Toast.LENGTH_LONG).show();
return true;
case R.id.item3:
Toast.makeText(getApplicationContext(), "Rate this app", Toast.LENGTH_LONG).show();
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);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Fragment_a();
break;
case 1:
fragment = new Fragment_b();
break;
case 2:
fragment = new Fragment_C();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, 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);
}
/**
* 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);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent result) {
super.onActivityResult(requestCode, resultCode, result);
}
}
here's my layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/drawer_item_icon"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10sp"
android:layout_marginRight="10sp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/drawer_item_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:paddingTop="8sp"
android:paddingBottom="8sp"
android:paddingLeft="15sp" />
</LinearLayout>
Simplest way I did it is this way:
1. Make this as your drawer xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tashan="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:orientation="horizontal"
android:padding="#dimen/spacing_small" >
<ImageView
android:id="#+id/drawer_item_icons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/spacing_small"
android:layout_marginStart="#dimen/spacing_small"
android:contentDescription="#string/test_string"/>
<TextView
android:id="#+id/drawer_item_labels"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/spacing_normal"
android:layout_marginStart="#dimen/spacing_small"
android:paddingLeft="#dimen/spacing_small"
android:paddingRight="#dimen/spacing_small"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#58585b" />
</LinearLayout>
2. Add these values to your 'dimens.xml'. Never hardcode values!
<dimen name="spacing_normal">16dp</dimen>
<dimen name="spacing_small">8dp</dimen>
3. For Icons array add this String Array to 'strings.xml
<string-array name="array_main_menu">
<item>#drawable/1</item>
<item>#drawable/2</item>
<item>#drawable/3</item>
<item>#drawable/4</item>
<item>#drawable/5</item>
</string-array>
4. In your Adapter access this array by using a Typed Array instance.
TypedArray typedArray=getResources().obtainTypedArray(R.array.array_main_menu);
5. Inside the getView of your adapter, set image to Imageview like this.
mIcon.setImageResource(typedArray.getResourceId(position, -1));
here mIcon is your ImageView.
With recent versions of Support Library, the easiest way is to use a NavigationView. Here is a nice tutorial, and here is the official documentation.
A NavigationView is included as second view in the DrawerLayout (instead of ListView from OP code), for example:
<android.support.design.widget.NavigationView
android:id="#+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/left_menu" />
Then, the menu should be populated with titles and icons, like (left_menu.xml):
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group
android:id="#+id/leftMenuId"
android:checkableBehavior="single">
<item
android:id="#+id/item1"
android:icon="#drawable/ic_zzblack_24dp"
android:title="Title1" />
<item
android:id="#+id/settings"
android:icon="#drawable/ic_settings_black_24dp"
android:title="Settings" />
</group>
</menu>
For more details, please refer to the first link.

Categories

Resources