This question already has answers here:
getActionBar() returns null
(25 answers)
Closed 8 years ago.
I want to get instance of action bar but getting the value null and because of that my whole program is not running.
My code where I have included this method is:
When my code jumps to line where action bar is needed it gives me null pointer exception
HomeTab.java:
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
public class HomeTab extends Activity implements OnItemClickListener{
MyCustomAdapter myCustomAdapter;
Context context=HomeTab.this;
//ImageView menuimage;
String optionName[]=new String[] {"Alerts","Events","Newsletters","News","Parent Info","Logins","Parent Teacher Interviews","Flexi School LunchOrder","Contact US","Kool Content"};
//int image[]=new int[] {R.drawable.alert_small_icon,R.drawable.events,R.drawable.newsletter,R.drawable.newsletter,R.drawable.arrow_24,R.drawable.arrow_24,R.drawable.arrow_24,R.drawable.arrow_24,R.drawable.arrow_24,R.drawable.arrow_24};
int imageArrow[]=new int[]{R.drawable.right_arrow};
ArrayList<ListModel> mylist=new ArrayList<ListModel>();
// test for sliding drawer
/*
String[] menu;
DrawerLayout dLayout;
ListView dList;
ArrayAdapter<String> adapter;*/
/*
* code from leftslide
*
*/
private DrawerLayout mDrawerLayout;
public ListView DrawerList;
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;
LayoutInflater inflater=null;
// code upto left slide
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_layout);
//menuimage=(ImageView)findViewById(R.id.menuimage);
//new code below
/*menuimage=(ImageView)findViewById(R.id.menuimage);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,menu);
menu = new String[]{"Home","Android","Windows","Linux","Raspberry Pi","WordPress","Videos","Contact Us"};
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
dList = (ListView) findViewById(R.id.left_drawer);*/
//new above
ListView listview=(ListView)findViewById(R.id.listView1);
getDatainList();
listview.setAdapter(new MyCustomAdapter(context, mylist));
listview.setBackgroundColor(Color.WHITE);
listview.setOnItemClickListener(this);
inflater=(LayoutInflater)HomeTab.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi=inflater.inflate(com.example.testlist.R.layout.sliding_activity_main, null);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(com.example.testlist.R.array.nav_drawer_items);
//nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(com.example.testlist.R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) vi.findViewById(R.id.drawer_layout);
DrawerList = (ListView) vi.findViewById(R.id.left_draw);
DrawerList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// displayView(position);
Toast.makeText(getApplicationContext(), "hi", 300).show();
}
});
navDrawerItems = new ArrayList<com.ctpl.skoolbag.leftslide.NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new com.ctpl.skoolbag.leftslide.NavDrawerItem(navMenuTitles[0],navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new com.ctpl.skoolbag.leftslide.NavDrawerItem(navMenuTitles[1],navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new com.ctpl.skoolbag.leftslide.NavDrawerItem(navMenuTitles[2],navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new com.ctpl.skoolbag.leftslide.NavDrawerItem(navMenuTitles[3],navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems.add(new com.ctpl.skoolbag.leftslide.NavDrawerItem(navMenuTitles[4],navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new com.ctpl.skoolbag.leftslide.NavDrawerItem(navMenuTitles[5],navMenuIcons.getResourceId(5, -1)));
navDrawerItems.add(new com.ctpl.skoolbag.leftslide.NavDrawerItem(navMenuTitles[6],navMenuIcons.getResourceId(6, -1)));
navDrawerItems.add(new com.ctpl.skoolbag.leftslide.NavDrawerItem(navMenuTitles[7],navMenuIcons.getResourceId(7, -1)));
// Recycle the typed array
navMenuIcons.recycle();
// setting the nav drawer list adapter
adapter = new com.ctpl.skoolbag.leftslide.NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
DrawerList.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.cat, //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);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.left_slide, 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(DrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#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);
}
private void getDatainList()
{
for(int i=0;i<10;i++)
{
ListModel li=new ListModel();
li.setOptionName(optionName[i]);
// li.setImage(image[i]);
li.setImageArrow(R.drawable.arrow);
mylist.add(li);
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
{
switch (position) {
case 0:
Intent call_AlertWebService=new Intent(getApplicationContext(),AlertActivityFromService.class);
startActivity(call_AlertWebService);
break;
case 1:
Intent i=new Intent(getApplicationContext(),EventsFromWebService.class);
startActivity(i);
break;
case 2:
Intent in=new Intent(getApplicationContext(),NewslettersActivityFromService.class);
startActivity(in);
break;
case 3:
Intent inn=new Intent(getApplicationContext(),NewsFromService.class);
startActivity(inn);
break;
default:
break;
}
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
android.app.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) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(com.example.testlist.R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
DrawerList.setItemChecked(position, true);
DrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(DrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
}
once check your minSdkVersion.
change to
<uses-sdk android:minSdkVersion="11" />
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
When I run the program I get NullPointerException on the line albumlist.add(0, recentAlbum). I have checked other classes which is good and I even initialized the list But i cant figure out where I went wrong.
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 = new ArrayList<NavDrawerItem>();
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
// Getting the albums from shared preferences
albumsList = AppController.getInstance().getPrefManager().getCategory();
// Insert "Recently Added" in navigation drawer first position
Category recentAlbum = new Category(null,
getString(R.string.nav_drawer_recently_added));
albumsList.clear();
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
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setIcon(
new ColorDrawable(getResources().getColor(
android.R.color.transparent)));
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.side_nav_bar, R.string.app_name, R.string.app_name) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Navigation drawer menu item click listener
*/
private class SlideMenuClickListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_scrolling, 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;
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 home fragment
fragment = GridFragment.newInstance(null);
break;
default:
// selected wallpaper category
// send album id to home fragment to list all the wallpapers
String albumId = albumsList.get(position).getId();
fragment = GridFragment.newInstance(albumId);
break;
}
if (fragment != null) {
android.app.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;
getSupportActionBar().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);
} }
Here is the Stack trace
Process: com.thedreamlight.thewallyapp, PID: 4645
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thedreamlight.thewallyapp/com.thedreamlight.thewallyapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2479)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2541)
at android.app.ActivityThread.access$1000(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1436)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5628)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
at com.thedreamlight.thewallyapp.MainActivity.onCreate(MainActivity.java:61)
at android.app.Activity.performCreate(Activity.java:6001)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2432)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2541)
at android.app.ActivityThread.access$1000(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1436)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5628)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
Initialize albumList array list like this:
private List<Category> albumsList = new ArrayList<>();
Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
In a nutshell, you are trying to use a null variable,which will through NullPointerException.
private List<Category> albumsList; that you declare was not initiated yet, so you need to initialize it as follows:
private List<Category> albumsList = new ArrayList<>();
Back press is not working from fragment to fragment.(my application contains navigation drawer and Tab view.) My Main Activity code is given below.i have added the back press method please help me....
public class Main Activity extends Activity {
ImageView image;
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;
ExpandableListView expListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Runtime.getRuntime().maxMemory();
// 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>();
// 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)));
// 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)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6],
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// mDrawerLayout.setBackgroundDrawable(new ColorDrawable(R.drawable.border));
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
ActionBar actionBar = getActionBar();
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
actionBar.setCustomView(R.layout.custom_view);
// actionBar.setCustomView(R.layout.custom_view1);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.show();
addListenerOnButton();
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.draw,//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;
}
/**
* 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 FirstFragment();
break;
case 1:
fragment = new HomeFragment();
break;
case 2:
fragment = new FindPeopleFragment();
break;
case 3:
fragment = new PhotosFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new CommunityFragment();
break;
default:
break;
}
**Edited Code:**
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.addToBackStack(null);
ft.replace(R.id.frame_container, fragment);
// Add this transaction to the back stack, so when the user presses back,// it rollbacks.
ft.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);
}
private void addListenerOnButton() {
// TODO Auto-generated method stub
image = (ImageView) findViewById(R.id.actionBarLogo);
image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Fragment fd2 = new MovieActivity();
android.app.FragmentTransaction ft2 =
getFragmentManager().beginTransaction();
ft2.replace(R.id.frame_container, fd2);
ft2.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft2.addToBackStack(null);
ft2.commit();
}
});
}
#Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
}
else {
getFragmentManager().popBackStack();
}
}
#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);
}
}
Inside your activity which handles all the fragments , use
#Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
}
else {
getSupportFragmentManager().popBackStack();
}
}
When the fragment backstack entry count is 0 , it means all the fragments are popped out of the backstack. So you just execute the super.onBackPressed() then. However when the stack is not empty , when you press back button you need to pop the top most fragment from the backstack so that proper back navigation happens.
Note : use getFragmentManager().getBackStackEntryCount() instead of getSupportFragmentManager().getBackStackEntryCount() if you are importing android.app.Fragment.
Edit
Now that you have changed your onBackPressed() code , next thing to do is change this in your code.
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.frame_container, fragment);
// Add this transaction to the back stack, so when the user presses back,// it rollbacks.
ft.addToBackStack("Give a Tag for the fragment here");
ft.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");
}
Basically what we are doing here is adding a particular fragment to the fragment backstack while replacing it so that while onBackPressed() of activity is executed count variable will store the number of fragments present in the fragment backstack , and proper back navigation occurs then.
Actually, this is my main problem. I've got a NavigationDrawer and I was changing lot of things about it; because I've added a TabHostFragment inside of it. The problem is when I'm in one Fragment, I've an ActionBar icon that goes to another Fragment. At the time to do this, it works perfect; but when I go to another Fragment, it still on the back of the new Fragment. I tried to put a BackGround color of each Fragment and it isn't visible.
The problem is that the transaction is OK; but when I'm in the other Fragment, when I press in a BlankSpace (For example) and on the old Fragment has a button here with a Toast, it's still showing this Toast on the new Fragment.
Here are a little examples of what happens maybe with images, you can understand better my question:
This main problem comes when I go trough this Fragment (I call it on MainActivity) that has no sense; because I want to call it when I'm on a specific Fragment; but it's in the only part that I can call this Fragment...
This is the MainActivity, where I call this FragmentTransaction:
case R.id.newOffer:
android.app.FragmentManager fm = getFragmentManager();
android.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, new TipusNouProducte());
ft.commit();
return true;
And by the way, I leave here the code from my NavigationDrawer for you that always when I'm going through a Fragment, it says "Error on creating Fragment":
private void displayView(int position) {
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
Fragment fragment = null;
switch (position) {
case 0:
fragment = new TabHostFragment();
break;
case 1:
fragment = new LocalizacionFragment();
break;
case 2:
fragment = new ListaProductosFragment();
break;
case 3:
fragment = new ConfiguracionFragment(this);
break;
case 4:
fragment = new AyudaSugerenciasFragment();
break;
case 5:
fragment = new AyudaSugerencias();
break;
case 6:
finish();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
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");
}
}
If you need more code that you think can cause this problem, feel free to ask me; then I'll update ASAP.
TabHostFragment.xml
<android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
MainActivity code looks like:
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// saber si esta abierto
public boolean mDrawerOpened;
// nav drawer title
private CharSequence mDrawerTitle;
private FragmentTabHost mTabHost;
// used to store app title
private CharSequence mTitle;
//para ponerlo visible
public MenuItem mi;
// 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[1], navMenuIcons.getResourceId(1, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
//AyudaSugerencias
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -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().setBackgroundDrawable(new ColorDrawable(0xff1d97dd));
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(
Html.fromHtml("<font color='ffffff'>"
+ mTitle + "</font>"));
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
mDrawerOpened = false;
syncState();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(
Html.fromHtml("<font color='ffffff'>"
+ mDrawerTitle + "</font>"));
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
mDrawerOpened = true;
syncState();
}
};
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) {
Fragment fragment = null;
// 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;
case R.id.ofertasRefresh:
return true;
case R.id.menu_search:
return true;
case R.id.newOffer:
android.app.FragmentManager fm = getFragmentManager();
android.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, new TipusNouProducte());
ft.commit();
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);
if (mDrawerOpened) {
menu.removeItem(R.id.ofertasRefresh);
menu.removeItem(R.id.menu_search);
menu.removeItem(R.id.newOffer);
}
if (!mDrawerOpened) {
menu.add(Menu.NONE, R.id.ofertasRefresh, Menu.NONE, mTitle);
}
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
*/
private void displayView(int position) {
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
Fragment fragment = null;
switch (position) {
case 0:
fragment = new TabHostFragment();
break;
case 1:
fragment = new LocalizacionFragment();
break;
case 2:
fragment = new ListaProductosFragment();
break;
case 3:
fragment = new ConfiguracionFragment(this);
break;
case 4:
fragment = new AyudaSugerenciasFragment();
break;
case 5:
fragment = new AyudaSugerencias();
break;
case 6:
finish();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
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);
}
}
TabHostFragment looks like:
public class TabHostFragment extends Fragment {
// Declaring our tabs and the corresponding fragments.
public TabHostFragment(){
}
private FragmentTabHost mTabHost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab_host_test2, container, false);
mTabHost = (FragmentTabHost)rootView.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("Mis ofertas").setIndicator("Mis ofertas"),
MisOfertasFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Mis recomendaciones").setIndicator("Mis recomendaciones"),
RecomendacionesFragment.class, null);
return rootView;
}
}
I'm not certain that this is the cause of your problem, but one thing that's definitely wrong is the use of the native FragmentManager instead of the one from the support library.
In your code, replace
case R.id.newOffer:
android.app.FragmentManager fm = getFragmentManager();
android.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, new TipusNouProducte());
ft.commit();
return true;
with
case R.id.newOffer:
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, new TipusNouProducte());
ft.commit();
return true;
You have used the support library's FragmentManager at other places in your code, so you should continue to use that everywhere.
Also, TipusNouProducte should extend android.support.v4.app.Fragment and NOT
android.app.Fragment.
I will update this answer if I find more issues.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've just finished up a four month project on android and I want to port to IOS I found the J2OBJC project but im having troube converting the class. so I guess im asking how to do I convert a class like my main activity this to work in IOS and how do I put in in Xcode. If I've completely misunderstood how J2OBJC works can you please show me an effective way to convert my project, Thanks.
public class MainActivity extends FragmentActivity {
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), true, "22"));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1), true, "+10"));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
getActionBar().setDisplayHomeAsUpEnabled(true);
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
// enabling action bar app icon and behaving it as toggle button
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();
}
};
}
/**
* 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 HomeMediaFragment();
break;
case 2:
fragment = new SectionFragment();
break;
case 3:
fragment = new HomeSectionFragment();
break;
case 4:
fragment = new WhatsHotFragment();
break;
case 5:
fragment = new AuthorFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fm = getSupportFragmentManager();
fm.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 toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
All j2objc does is convert the syntax from Java to Objective-C. You're still going to have to know and understand UIKit and the associated iOS frameworks. The short answer is, you've got a 2-3 month or more project ahead of you as you rewrite all of the user interface code, even if you can salvage the model and data handling code using j2objc.
How do I add buttons, switches, seekbars etc. to an android app drawer?
I know how to add text to the listview but I'm finding the above very difficult. I have my current app drawer below. What changes would you suggest to accomplish the above.
Code:
MainActivity
public class MainActivity extends Activity {
// Within which the entire activity is enclosed
DrawerLayout mDrawerLayout;
// ListView represents Navigation Drawer
ListView mDrawerList;
// ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
ActionBarDrawerToggle mDrawerToggle;
// Title of the action bar
String mTitle="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = (String) getTitle();
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle( this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close){
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("Select a river");
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(),
R.layout.drawer_list_item ,
getResources().getStringArray(R.array.rivers)
);
// Setting the adapter on mDrawerList
mDrawerList.setAdapter(adapter);
// Enabling Home button
getActionBar().setHomeButtonEnabled(true);
// Enabling Up navigation
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
// Getting an array of rivers
String[] rivers = getResources().getStringArray(R.array.rivers);
//Currently selected river
mTitle = rivers[position];
// Creating a fragment object
RiverFragment rFragment = new RiverFragment();
// Creating a Bundle object
Bundle data = new Bundle();
// Setting the index of the currently selected item of mDrawerList
data.putInt("position", position);
// Setting the position to the fragment
rFragment.setArguments(data);
// Getting reference to the FragmentManager
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, rFragment);
// Committing the transaction
ft.commit();
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
});
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
/** Handling the touch event of app icon */
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Activity_Layout
<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">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="#+id/drawer_list"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
You can use this library for your drawer library
or if you want this drawer then put one linearlayout and then put you views inside that.
SlidingMenu menu = new SlidingMenu(this);
menu.setMode(SlidingMenu.LEFT);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
menu.setMenu(R.layout.side_panel);
Now in the side panel layout put your views in side that now for view side panel use this:
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home:
if (menu != null) {
menu.toggle();
}
break;
}
return true;
}
for initializing side panel data use this:
menu.findViewById(R.id.your_view_id).setOnClickListener(this);
and override onclick event and handle that you want.
for further information see the example in the github.