I am trying to add icons to my Navigation Drawer in Android. I have the following code in my main
public class MainActivity extends ActionBarActivity {
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
private myAdapter MyAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() {
String[] osArray = {"Math", "Physics", "Chemistry"};
MyAdapter = new myAdapter(this);
mDrawerList.setAdapter(MyAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position) {
case 0:
Intent a = new Intent(MainActivity.this, MathActivity.class);
startActivity(a);
break;
case 1:
Intent b = new Intent(MainActivity.this, PhysicsActivity.class);
startActivity(b);
break;
case 2:
Intent c = new Intent(MainActivity.this, ChemistryActivity.class);
startActivity(c);
break;
default:
}
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#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) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
class myAdapter extends BaseAdapter {
private Context context;
String SchoolCategories[];
int[] images = {R.drawable.math_icon,R.drawable.physics_icon,R.drawable.chemistry_icon};
public myAdapter(Context context){
this.context = context;
SchoolCategories = context.getResources().getStringArray(R.array.school);
}
#Override
public int getCount() {
return SchoolCategories.length;
}
#Override
public Object getItem(int position) {
return SchoolCategories[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = null;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.custom_row, parent, false);
}
else{
row =convertView;
}
TextView titleTextView =(TextView) row.findViewById(R.id.textViewRow1);
ImageView titleImageView = (ImageView) row.findViewById(R.id.imageViewRow1);
titleTextView.setText(SchoolCategories[position]);
titleImageView.setImageResource(images[position]);
return row;
}
}
}
And the following XML Layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/math_icon"
android:id="#+id/imageViewRow1"
/>
<TextView
android:layout_margin="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textViewRow1"
/>
</LinearLayout>
I am simple just trying to add icons to the navigation drawer, but this does not work and I am not sure what goes wrong. The application just shuts down. All help is really appreciated!
Here is my log-cat:
05-25 12:27:33.053 3909-3909/oscarorellana.nowwetryitmyway.physicsproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: oscarorellana.nowwetryitmyway.physicsproject, PID: 3909
android.content.ActivityNotFoundException: Unable to find explicit activity class {oscarorellana.nowwetryitmyway.physicsproject/oscarorellana.nowwetryitmyway.physicsproject.MathActivity}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1761)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1485)
at android.app.Activity.startActivityForResult(Activity.java:3736)
at android.app.Activity.startActivityForResult(Activity.java:3697)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:820)
at android.app.Activity.startActivity(Activity.java:4007)
at android.app.Activity.startActivity(Activity.java:3975)
at oscarorellana.nowwetryitmyway.physicsproject.MainActivity$1.onItemClick(MainActivity.java:57)
This was solved with changing this line:
inflater.inflate(R.layout.custom_row, parent, false);
To this line:
row = inflater.inflate(R.layout.custom_row, parent, false);
Related
I am creating an app with a slider and it was working fine and then I added another view and implemented an OnClickListener() for the newly added Views after that I am getting the following error when I open my app
Process: com.spintum.preexam, PID: 31905
java.lang.NoClassDefFoundError: com.spintum.preexam.CustomList$DrawerItemHolder
at com.spintum.preexam.CustomList.getView(CustomList.java:38)
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:1645)
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:931)
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:5292)
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)
The class in which the logcat shows the NoClassDefFound error is as follows
public class CustomList extends ArrayAdapter<DrawerItem> {
Context context;
List<DrawerItem> drawerItemList;
int layoutResID;
public CustomList(Context context, int layoutResourceID,
List<DrawerItem> listItems) {
super(context, layoutResourceID, listItems);
this.context = context;
this.drawerItemList = listItems;
this.layoutResID = layoutResourceID;
}
#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_item_text);
drawerHolder.icon = (ImageView) view.findViewById(R.id.drawer_item_icon);
view.setTag(drawerHolder);
} else {
drawerHolder = (DrawerItemHolder) view.getTag();
}
DrawerItem dItem = (DrawerItem) this.drawerItemList.get(position);
drawerHolder.icon.setImageDrawable(view.getResources().getDrawable(
dItem.getImgResID()));
drawerHolder.ItemName.setText(dItem.getItemName());
return view;
}
private static class DrawerItemHolder {
TextView ItemName;
ImageView icon;
}
}
The error is shown in drawerHolder = new DrawerItemHolder(); line.
I have not made any changes to this class so I am thinking the problem might be caused by the extra views that I added in my original activity that acts as a fragment container. The activity's code is as follows
public class Home extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
private static int pos;
List<DrawerItem> dataList = new ArrayList<DrawerItem>();
View statistics,test,syllabus,share;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
this.getActionBar().setBackgroundDrawable(
getResources().getDrawable(R.color.background));
this.overridePendingTransition(R.layout.fade_in, R.layout.fade_out);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
statistics=findViewById(R.id.statistics_container);
test=findViewById(R.id.test_container);
syllabus=findViewById(R.id.syllabus_container);
share=findViewById(R.id.share_container);
statistics.setOnClickListener(mBottomDrawerListener);
syllabus.setOnClickListener(mBottomDrawerListener);
test.setOnClickListener(mBottomDrawerListener);
share.setOnClickListener(mBottomDrawerListener);
TextView image=(TextView)findViewById(R.id.statistics_image);
TextView text=(TextView)findViewById(R.id.statistics);
image.setTextColor(Color.parseColor("#03a9f4"));
text.setTextColor(Color.parseColor("#03a9f4"));
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,GravityCompat.START);
int width = getResources().getDisplayMetrics().widthPixels;
DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawerList.getLayoutParams();
//params.width = (width * 75) / 100;
mDrawerList.setLayoutParams(params);
// set up the drawer's list view with items and click listener
/*
* mDrawerList.setAdapter(new ArrayAdapter<String>(this,
* R.layout.list_item, mPlanetTitles));
*/
dataList.add(new DrawerItem("Home", R.drawable.home));
dataList.add(new DrawerItem("Intelligence Questionnaire",
R.drawable.bulb));
dataList.add(new DrawerItem("Change Country", R.drawable.location));
dataList.add(new DrawerItem("LeaderBoard", R.drawable.cup));
dataList.add(new DrawerItem("How to play", R.drawable.help));
dataList.add(new DrawerItem("Exam Tips", R.drawable.tip));
mDrawerList.setAdapter(new CustomList(Home.this, R.layout.list_item,dataList));
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 */) {
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);
if (savedInstanceState == null) {
selectItem(0);
}
Typeface iconfont=FontManager.getTypeface(getApplicationContext(),FontManager.FONTAWESOME);
FontManager.markAsIconContainer(findViewById(R.id.btm_nav_bar),iconfont);
}
public View.OnClickListener mBottomDrawerListener=new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager=getFragmentManager();
setBlackText(v);
TextView image,text;
switch (v.getId()){
case R.id.statistics_container:
fragmentManager.beginTransaction().replace(R.id.content_frame,new HomePage()).commit();
image=(TextView)v.findViewById(R.id.statistics_image);
text=(TextView)v.findViewById(R.id.statistics);
image.setTextColor(Color.parseColor("#03a9f4"));
text.setTextColor(Color.parseColor("#03a9f4"));
break;
case R.id.syllabus_container:
image=(TextView)v.findViewById(R.id.syllabus_image);
text=(TextView)v.findViewById(R.id.syllabus_btm);
image.setTextColor(Color.parseColor("#03a9f4"));
text.setTextColor(Color.parseColor("#03a9f4"));
break;
case R.id.test_container:
image=(TextView)v.findViewById(R.id.test_image);
text=(TextView)v.findViewById(R.id.Tests);
image.setTextColor(Color.parseColor("#03a9f4"));
text.setTextColor(Color.parseColor("#03a9f4"));
break;
case R.id.share_container:
image=(TextView)v.findViewById(R.id.share_image);
text=(TextView)v.findViewById(R.id.share_btm);
image.setTextColor(Color.parseColor("#03a9f4"));
text.setTextColor(Color.parseColor("#03a9f4"));
break;
}
}
};
public void setBlackText(View v){
TextView img[]=new TextView[4];
TextView t1,t2,t3,t4;
img[0]=(TextView)findViewById(R.id.statistics_image);
t4=(TextView)findViewById(R.id.statistics);
img[1]=(TextView)findViewById(R.id.test_image);
t1=(TextView)findViewById(R.id.Tests);
img[2]=(TextView)findViewById(R.id.syllabus_image);
t2=(TextView)findViewById(R.id.syllabus_btm);
img[3]=(TextView)findViewById(R.id.share_image);
t3=(TextView)findViewById(R.id.share_btm);
for(TextView singleTextView:img){
singleTextView.setTextColor(Color.parseColor("#000000"));
}
t1.setTextColor(Color.parseColor("#000000"));
t2.setTextColor(Color.parseColor("#000000"));
t3.setTextColor(Color.parseColor("#000000"));
t4.setTextColor(Color.parseColor("#000000"));
}
/*
* #Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater
* inflater = getMenuInflater(); inflater.inflate(R.menu.activity_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_websearch).setVisible(!drawerOpen); 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
switch (item.getItemId()) {
case 1:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available,
Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* 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 the main content by replacing fragments
/*
* Fragment fragment = new HomePage(); Bundle args = new Bundle();
* args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
* fragment.setArguments(args);
*/
pos = position;
FragmentManager fragmentManager = getFragmentManager();
switch (pos) {
case 0:
fragmentManager.beginTransaction().replace(R.id.content_frame, new Fragment_Statistics()).commit();
break;
case 1:
break;
case 2:
fragmentManager.beginTransaction().replace(R.id.content_frame, new Country()).commit();
case 3:break;
case 4:break;
case 5:break;
}
// update selected item and title, then close the drawer
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);
// 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);
}
}
The DrawerItem class used in the Home activity is given below
public class DrawerItem {
String ItemName;
int imgResID;
public DrawerItem(String itemName, int imgResID) {
super();
ItemName = itemName;
this.imgResID = imgResID;
}
public String getItemName() {
return ItemName;
}
public void setItemName(String itemName) {
ItemName = itemName;
}
public int getImgResID() {
return imgResID;
}
public void setImgResID(int imgResID) {
this.imgResID = imgResID;
}}
Can someone see where I am going wrong? Thanks in advance..
DrawerItemHolder class should be public, or at least it should not be private.
I am trying to implement recycler view instead of an expandable list view,so that when I click a navigation drawer menu item,t should expand.Her is my code,I don't how to implement.
activity_main.xml:
<include
layout="#layout/app_bar_main"
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_main"
app:menu="#menu/activity_main_drawer"
app:itemTextAppearance="#style/NavDrawerTextStyle"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#fff">
</android.support.v7.widget.RecyclerView>
and this is Adapter
public class ExpandableListCustomAdapter extendsRecyclerView.Adapter{
private List<SubMenuItems> subMenuItemses_list=new ArrayList<>();
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView sample_text;
public MyViewHolder(View itemView) {
super(itemView);
sample_text=(TextView)itemView.findViewById(R.id.sample_text);
}
}
public ExpandableListCustomAdapter(List<SubMenuItems> subMenuItemses_list){
this.subMenuItemses_list=subMenuItemses_list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.expandable_list_custom_adapter,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
SubMenuItems subMenuItems=subMenuItemses_list.get(position);
holder.sample_text.setText(subMenuItems.getItem1());
}
#Override
public int getItemCount() {
return subMenuItemses_list.size();
}
}
MainActivity.java
ExpandableListCustomAdapter expandableListCustomAdapter=new ExpandableListCustomAdapter(subMenuItemses2);
layoutManager=new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
prepareSubMenu();
//here we configured text,images and added to a list
recyclerView.setAdapter(expandableListCustomAdapter);
private void prepareSubMenu(){
SubMenuItems subMenuItems4=new SubMenuItems("Main");
subMenuItemses2.add(subMenuItems4);
subMenuItems4=new SubMenuItems("Starters");
subMenuItemses2.add(subMenuItems4);
subMenuItems4=new SubMenuItems("Dessert");
subMenuItemses2.add(subMenuItems4);
expandableListCustomAdapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.home_id) {
/*Toast.makeText(MainActivity.this, "Wait on....", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MediaStore.ACTION_IMAGE_CAPTURE));*/
// Handle the camera action
} else if (id == R.id.menu_id) {
} else if (id == R.id.my_order_id) {
} else if (id == R.id.about_id) {
} else if (id == R.id.contact_id) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer != null) {
drawer.closeDrawer(GravityCompat.START);
}
return true;
}
}
Result is showing,that's not an issue.I need to implement this when someone click an item in Nav Drawer,and shows an expand list.Here I am using RecyclerView.Is it possible or I have to use ExpandableList ?
If you want to add Expandable list in your drawer try to follow expandable-navigation-drawer
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
private ExpandableListView mExpandableListView;
private ExpandableListAdapter mExpandableListAdapter;
private List<String> mExpandableListTitle;
private Map<String, List<String>> mExpandableListData;
private TextView mSelectedItemView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
mExpandableListView = (ExpandableListView) findViewById(R.id.navList);
mSelectedItemView = (TextView) findViewById(R.id.selected_item);
LayoutInflater inflater = getLayoutInflater();
View listHeaderView = inflater.inflate(R.layout.nav_header, null, false);
mExpandableListView.addHeaderView(listHeaderView);
mExpandableListData = ExpandableListDataSource.getData(this);
mExpandableListTitle = new ArrayList(mExpandableListData.keySet());
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() {
mExpandableListAdapter = new CustomExpandableListAdapter(this, mExpandableListTitle, mExpandableListData);
mExpandableListView.setAdapter(mExpandableListAdapter);
mExpandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
getSupportActionBar().setTitle(mExpandableListTitle.get(groupPosition).toString());
mSelectedItemView.setText(mExpandableListTitle.get(groupPosition).toString());
}
});
mExpandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
getSupportActionBar().setTitle(R.string.film_genres);
mSelectedItemView.setText(R.string.selected_item);
}
});
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
String selectedItem = ((List) (mExpandableListData.get(mExpandableListTitle.get(groupPosition))))
.get(childPosition).toString();
getSupportActionBar().setTitle(selectedItem);
mSelectedItemView.setText(mExpandableListTitle.get(groupPosition).toString() + " -> " + selectedItem);
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(R.string.film_genres);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#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) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am using a navigation drawer that fetches the album list from picasa web api. I have been trying to implement that same list as the tab items. Can someone please help me with implementing it?
This is the Navigation Drawer item class to show the albums in the navigation drawer.
public class NavDrawerItem {
private String albumId, albumTitle;
// boolean flag to check for recent album
private boolean isRecentAlbum = false;
public NavDrawerItem() {
}
public NavDrawerItem(String albumId, String albumTitle) {
this.albumId = albumId;
this.albumTitle = albumTitle;
}
public NavDrawerItem(String albumId, String albumTitle,
boolean isRecentAlbum) {
this.albumTitle = albumTitle;
this.isRecentAlbum = isRecentAlbum;
}
public String getAlbumId() {
return albumId;
}
public void setAlbumId(String albumId) {
this.albumId = albumId;
}
public String getTitle() {
return this.albumTitle;
}
public void setTitle(String title) {
this.albumTitle = title;
}
public boolean isRecentAlbum() {
return isRecentAlbum;
}
public void setRecentAlbum(boolean isRecentAlbum) {
this.isRecentAlbum = isRecentAlbum;
}
}
Nav drawer list adapter
package com.techsprint.wallpaperpro.helper;
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;
import com.techsprint.wallpaperpro.NavDrawerItem;
import com.techsprint.wallpaperpro.R;
import java.util.ArrayList;
/**
* Created by Mahe on 6/18/2015.
*/
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);
}
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
txtTitle.setText(navDrawerItems.get(position).getTitle());
return convertView;
}
}
The activity main layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="true">
<!-- 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="#dimen/list_view_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/list_background"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="#dimen/list_view_divider_height"
android:listSelector="#drawable/list_selector" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
Drawer item layout
<?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="#dimen/drawer_list_item_layout_height"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="#dimen/drawer_list_item_layout_height"
android:background="#drawable/list_selector">
<ImageView
android:id="#+id/navimage_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_subject_black_24dp" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/navimage_list"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingLeft="#dimen/drawer_list_item_padding"
android:paddingRight="#dimen/drawer_list_item_padding"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#color/list_item_title" />
</RelativeLayout>
</LinearLayout>
And my main activity
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// Navigation drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private List<Category> albumsList;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
private Toolbar toolbar;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// Getting the albums from shared preferences
albumsList = AppController.getInstance().getPrefManger().getCategories();
// Insert "Recently Added" in navigation drawer first position
Category recentAlbum = new Category(null,
getString(R.string.nav_drawer_recently_added));
albumsList.add(0, recentAlbum);
// Loop through albums in add them to navigation drawer adapter
for (Category a : albumsList) {
navDrawerItems.add(new NavDrawerItem(a.getId(), a.getTitle()));
}
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);
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(
android.R.color.transparent)));*/
getSupportActionBar().setDisplayShowHomeEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().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);
}
}
String deviceName = android.os.Build.MODEL;
String deviceMan = android.os.Build.MANUFACTURER;
String HARDWARE = Build.HARDWARE;
String TYPE = Build.TYPE;
String board = Build.BOARD;
/**
* Navigation drawer 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.menu_main, menu);
return true;
}
/**
* On menu item selected
*/
#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:
// Selected settings menu item
// launch Settings activity
Intent intent = new Intent(MainActivity.this,
SettingsActivity.class);
startActivity(intent);
return true;
case R.id.googleplus:
Intent intent1 = new Intent(MainActivity.this, GooglePlusActivity.class);
startActivity(intent1);
return true;
case R.id.feedback:
final Intent _Intent = new Intent(android.content.Intent.ACTION_SEND);
_Intent.setType("text/html");
_Intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{getString(R.string.mail_feedback_email)});
_Intent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.mail_feedback_subject));
_Intent.putExtra(android.content.Intent.EXTRA_TEXT, "Please Leave Your Valuable Feedback Above This Line" + "\n" + deviceMan + " " + deviceName + "," + " " + HARDWARE + "," + " " + board + "," + " " + TYPE);
startActivity(Intent.createChooser(_Intent, getString(R.string.title_send_feedback)));
return true;
case R.id.followus:
Intent intent2 = new Intent(MainActivity.this, FollowUsActivity.class);
startActivity(intent2);
return true;
case R.id.test:
Intent intent3 = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent3);
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:
// Recently added item selected
// don't pass album id to grid fragment
fragment = GridFragment.newInstance(null);
break;
default:
// selected wallpaper category
// send album id to grid fragment to list all the wallpapers
String albumId = albumsList.get(position).getId();
fragment = GridFragment.newInstance(albumId);
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(albumsList.get(position).getTitle());
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e(TAG, "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);
}
}
The application is a wallpaper app which fetches data from the picasa web api. The app uses the volley library.
Every time I open my Activity from Navigation Drawer, a blank screen appears. I am trying to open a fragment from my Navigation:
public class MainActivity extends ActionBarActivity {
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() {
String[] osArray = {"Math", "Physics", "Chemistry"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position) {
case 0:
Intent a = new Intent(MainActivity.this, MathActivity.class);
startActivity(a);
break;
case 1:
Intent b = new Intent(MainActivity.this, PhysicsActivity.class);
startActivity(b);
break;
case 2:
Intent c = new Intent(MainActivity.this, ChemistryActivity.class );
startActivity(c);
break;
default:
}
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#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) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
To open Activity like this:
public class MathActivity extends Activity{
protected void onCreate(Bundle bundle) {
setContentView(R.layout.math_fragment_activity);
super.onCreate(bundle);
}
}
Every time I do so, a blank screen appears. Why is this happening and can anyone help me solve this problem?
UPDATE:
Here is my layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listViewAnimals"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:dividerHeight="0.1dp"
android:divider="#0000CC"/> </RelativeLayout>
Try switching your setContentiew to be after the super.onCreate call.
I am having some problem with navigation drawer in Android. So these are the codes with me:
public class NavigationDrawer extends FragmentActivity {
private String[] drawerListViewItems;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private ActionBarDrawerToggle actionBarDrawerToggle;
protected DrawerLayout fullLayout;
protected FrameLayout actContent;
#Override
public void setContentView(final int layoutResID) {
fullLayout = (DrawerLayout) getLayoutInflater().inflate(
R.layout.navigation_drawer, null); // Your base layout here
actContent = (FrameLayout) fullLayout.findViewById(R.id.act_content);
getLayoutInflater().inflate(layoutResID, actContent, true);
super.setContentView(fullLayout);
drawerListViewItems = getResources().getStringArray(R.array.items);
drawerListView = (ListView) findViewById(R.id.left_drawer);
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,
drawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
drawerListView.bringToFront();
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position,
long id) {
switch (position) {
}
drawerLayout.closeDrawer(drawerListView);
}
}
}
And my xml 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" >
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:divider="#CCCCCC"
android:dividerHeight="0.5dp"
android:paddingLeft="16dp"
android:paddingRight="16dp" />
<FrameLayout
android:id="#+id/act_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
And the string file where I declare the words for navigation drawer item:
<string-array name="items">
<item>Dashboard</item>
<item>Account</item>
<item>Setting</item>
<item>Recurring</item>
<item>Budget</item>
</string-array>
But with these code, the navigation drawer level is only one. What I am trying to do is there will be still sub item under Dashboard, Setting and Budget.
I wonder how to modify it so that the navigation drawer could take in one more level of items.
Thanks in advance.
EDIT
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
// private ListView mDrawerList;
private ExpandableListView mDrawerList;
private LinearLayout navDrawerView;
CustomExpandAdapter customAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mAnalyzeEventSelection;
private int selectedPosition;
List<SampleTO> listParent;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
navDrawerView = (LinearLayout) findViewById(R.id.navDrawerView);
mAnalyzeEventSelection = getResources().getStringArray(R.array.analyzeEvent_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ExpandableListView) findViewById(R.id.nav_left_drawer);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
listParent = new ArrayList<SampleTO>();
listDataChild = new HashMap<String, List<String>>();
// Navigation Drawer of Flight starts
listParent.add(new SampleTO(getString(R.string.createEventDrawer), R.drawable.sun));
listParent.add(new SampleTO(getString(R.string.analyzeEventDrawer), R.drawable.solar_system));
listParent.add(new SampleTO(getString(R.string.qrCodeDrawer), R.drawable.moon));
listDataChild.put(getString(R.string.createEventDrawer), new ArrayList<String>());
listDataChild.put(getString(R.string.qrCodeDrawer), new ArrayList<String>());
listDataChild.put(getString(R.string.analyzeEventDrawer), Arrays.asList(mAnalyzeEventSelection));
customAdapter = new CustomExpandAdapter(this, listParent, listDataChild);
// setting list adapter
mDrawerList.setAdapter(customAdapter);
mDrawerList.setChoiceMode(ExpandableListView.CHOICE_MODE_SINGLE);
// 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,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
) {
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
protected void onResume() {
super.onResume();
mDrawerList.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
int index = parent.getFlatListPosition(ExpandableListView.getPackedPositionForGroup(groupPosition));
parent.setItemChecked(index, true);
String parentTitle = ((SampleTO) customAdapter.getGroup(groupPosition)).getTitle();
if (parentTitle.equals(getString(R.string.createEventDrawer))){
Toast.makeText(
MainActivity.this,
"Create Event",
Toast.LENGTH_LONG).show();
setTitle(mAnalyzeEventSelection[selectedPosition]);
}
else if (parentTitle != getString(R.string.analyzeEventDrawer)) {
mDrawerLayout.closeDrawer(navDrawerView);
}
return false;
}
});
mDrawerList.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
int index = parent.getFlatListPosition(ExpandableListView.getPackedPositionForChild(groupPosition, childPosition));
parent.setItemChecked(index, true);
selectItem(childPosition);
return false;
}
});
}
#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(navDrawerView);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
private void selectItem(int position) {
selectedPosition = position;
mDrawerLayout.closeDrawer(navDrawerView);
switch(selectedPosition){
case 0:
Toast.makeText(
MainActivity.this,
"Event Pop",
Toast.LENGTH_LONG).show();
break;
case 1:
Toast.makeText(
MainActivity.this,
"Buffer",
Toast.LENGTH_LONG).show();
break;
}
setTitle(mAnalyzeEventSelection[selectedPosition]);
}
#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 my string file:
<resources>
<string name="app_name">Navigation Drawer Example</string>
<string name="createEventDrawer">Create Event</string>
<string name="analyzeEventDrawer">Analyze Event</string>
<string-array name="analyzeEvent_array">
<item>Past Event Population</item>
<item>Buffer</item>
</string-array>
<string name="qrCodeDrawer">QR Code Scan</string>
<string name="drawer_open">Open navigation drawer</string>
<string name="drawer_close">Close navigation drawer</string>
<string name="action_websearch">Web search</string>
<string name="app_not_available">Sorry, there\'s no web browser available</string>
<string name="_11">11</string>
Steps:
Change ListView to Expandablelistview.
Add subitems for the group items required.
Example :Custom Navigation Drawer