I have two fragments MainFragment and First_Fragment. First fragment contains a video view but whenever I try to rotate, nav drawer always goes back to its main fragment. How could I save or restore my fragment state ? so it would stop going back to its main fragment.
Here's my code for the MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
VideoView videoView;
NavigationView navigationView = null;
Toolbar toolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainFragment first = new MainFragment();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, first);
fragmentTransaction.commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
MainFragment first = new MainFragment();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, first);
fragmentTransaction.commit();
} else if (id == R.id.nav_gallery) {
First_Fragment first = new First_Fragment();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, first);
fragmentTransaction.commit();
} else if (id == R.id.nav_slideshow) {
}
When you're not handling the activity change like orientation, keyboard, etc. it will automatically recreates the activity. Therefore you're fragment does not save your previous instance. To solve that, I only encounter two solution.
The first one is already mentioned by Zeeshan that handle your orientation change by following this step:
Handle the orientation change in your AndroidManifest
<activity
android:name="com.example.Activity"
android:label="Activity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:windowSoftInputMode="stateHidden|adjustResize"
android:theme="#style/Theme.AppCompat.Light" />
Handle the event in the onConfiguration Change method
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
The second one is to save the fragment state. Refer here https://stackoverflow.com/a/17135346/5870896
You can do setRetainInstance(true) in your fragments, but a BottomNavigationBar will work incorrectly. In this case you can use some boolean flag in activity and save/restore it with Bundle like this:
In onCreate:
if (savedInstanceState != null) {
isMapFragmentVisible = savedInstanceState.getBoolean("isMainVisible");
} else {
navigator.navigateToFragment(fragmentLocation);
}
In onSavedInstanceState:
outState.putBoolean("isMainVisible", isMapFragmentVisible);
In onNavigationSelectedListener:
case R.id.bottom_navigation_map:
if (isMapFragmentVisible) {
break;
} else {
navigator.navigateToFragment(fragmentMap);
isMapFragmentVisible = true;
}
return true;
case R.id.bottom_navigation_location:
if (!isMapFragmentVisible) {
break;
} else {
navigator.navigateToFragment(fragmentLocation);
isMapFragmentVisible = false;
}
return true;
For me it works perfect. Are there any more elegant ways?
Activity recreates when you rotate the device. you need to mention in your manifest that you will handle the orientation change in your code so that system don't do it like this:
<activity name="MainActivity" android:configChanges="keyboardHidden|orientation|screenSize"/>
and then handle the event
#Override
public void onConfigurationChanged(Configuration newConfig) {
}
in your activity
Write this in manifests.xml
android:configChanges="orientation"
like this:-
<activity
android:name=".fragmentLayouts.MainActivity"
android:configChanges="orientation" />
Add this to your java code:-
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
drawerListener.onConfigurationChanged(newConfig);
}
Related
I am really new to android and I am really frustrated with it. I want to switch between fragments in drawer menu. However, the screen stays the same. In the drawer it says that I am on a particular fragment but I see no change. I set a different background to differentiate between them.
I believe that fragment manager is deprecated based on what people are saying but I don't know how to change it with. Also the thin is I don't know which tutorials are out of date because I have very little knowledge about android development.
Fragment code:
public class ToolsFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tools, container,false);
}
}
Main activity code:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new CharacterFragment());
navigationView.setCheckedItem(R.id.nav_characters);
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
} else{
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_characters:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new CharacterFragment());
break;
case R.id.nav_episodes:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new EpisodesFragment());
break;
case R.id.nav_tools:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new EpisodesFragment());
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
You forgot to call commit()
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new CharacterFragment()).commit();
In my app I have problem like this. Note that I'm working with fragments and I have drawer too.
That's the method in my MainActivity for drawer open/close.
public void drawerInit() {
toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer);
view = findViewById(R.id.mainView);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
float moveFactor = (drawerView.getWidth() * slideOffset);
view.setTranslationX(moveFactor);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
drawer.addDrawerListener(toggle);
toggle.syncState();
}
Example I have 3 fragments (F1, F2, F3). F1 is my main fragment where I can open and close the drawer. When I'm opening F2 or F3 fragments, I need to change the drawer icon to back arrow. I'm doing this part successfully, but the problem is when I'm clicking on this back arrow, that opens the navigation drawer instead of going back. So how can I fix this part?
Here the part, where I'm changing the icon to back arrow in fragment.
((AppCompatActivity) getActivity()).getSupportActionBar().show();
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity) getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
Add in your Activity
public void crateMenuButton(){
toggle.setDrawerIndicatorEnabled(true);
if(toolbarDrawable == null) {
toolbarDrawable = toolbar.getNavigationIcon();
}
toolbar.setNavigationIcon(toolbarDrawable);
invalidateOptionsMenu();
toggle.syncState();
}
public void createBackButton() {
toggle.setDrawerIndicatorEnabled(false);
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if the drawerToggle is disabled, fall off to the home button action
if (!toggle.isDrawerIndicatorEnabled()) {
// pop fragment here
FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack();
}
} else {
if (drawerLayout.isDrawerOpen(navigationView)) {
drawerLayout.closeDrawer(navigationView);
} else {
drawerLayout.openDrawer(navigationView);
}
}
}
});
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_white));
}
Download Back Arrow
Then call from your fragment as your need
((YourActivity) getActivity()).createBackButton();
OR
((YourActivity) getActivity()).crateMenuButton();
So i've encountered a small problem today. I was making a bottom navigation view in my app, and after clicking buttons, it replaces the fragment on the screen (and it works perfectly!).
But just after launching the app, and without clicking any button, there is no fragment on the screen.
I've realized that the fragments are shown only after clicking a button, and I'd like to have a default fragment (kalkulatorFragment).
I've been trying my best to somehow set it up, but no success...
public class Main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
kalkulatorFragment kalkulator_fragment = new kalkulatorFragment();
wzoryFragment wzory_fragment = new wzoryFragment();
definicjeFragment definicje_fragment = new definicjeFragment();
switch (item.getItemId()) {
case R.id.kalkulator:
ft.replace(android.R.id.content, kalkulator_fragment);
ft.commit();
return true;
case R.id.wzory:
ft.replace(android.R.id.content, wzory_fragment);
ft.commit();
return true;
case R.id.definicje:
ft.replace(android.R.id.content, definicje_fragment);
ft.commit();
return true;
}
return false;
}
Ok i just figured it out.
I moved the ft.replace to the onCreate() method, so the kalkulatorFragment is going to be shown just after creating an Activity.
public class Main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kalkulatorFragment kalkulator_fragment = new kalkulatorFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(android.R.id.content, kalkulator_fragment);
ft.commit();
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
You need to use this code OUTSIDE of OnCreate Method:
navigation.setSelectedItemId(R.id.IdOFYourItemFromBottomNavigationMenuItems);
I don't know why, but it wont work inside OnCreate method. You can declare and initialize it inside OnCreate method, just can't set the default item in there.
In my case I am using it inside OnCreateOptionsMenu.
MainActivity class:
/* all necessary imports */
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
/* Other variable initialized here... */
FragOne fo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fo.setTextViewText("This is added from Activity");
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragOne(), "My Tracker");
adapter.addFragment(new FragTwo(), "Team Tracker");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Fragment class:
/* all necessary imports */
public class FragOne extends Fragment {
TextView tvCName;
public FragOne() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_frag_one, container, false);
return view;
//return inflater.inflate(R.layout.fragment_frag_one, container, false);
}
#Override
public void onViewCreated(View view , Bundle savedInstanceState) {
tvCName = (TextView) view.findViewById(R.id.tvctq);
}
public void setTextViewText(String value){
tvCName.setText(value);
}
}
Fragment XML Layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mytip.FragOne">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvctq" />
</FrameLayout>
I am trying to access the TextView inside the Fragment from MainActivity like this:
FragOne fo;
fo.setTextViewText("This is added from Activity");
I keep getting a NullPointerExceptionError. I looked at all the articles to see how to access, however none of them helped me.
Can someone please let me know what am I doing wrong and how to fix it?
I also plan on adding other Views inside my Fragment that I would need to access in the future.
Because fo hasn't been initialized in the following code snippet:
FragOne fo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fo.setTextViewText("This is added from Activity");
...
}
fo.setTextViewText() reasonably throws NPE.
You have to pay attention to the Activity lifecycle - you seem to be setting everything up correctly, but making a few mistakes accessing the correct instance of the fragment at the time it's actually ready. Things you should do
Get proper instance of the fragment from your ViewPager, like #ginomempin suggested;
Only try to set your text no earlier then your activities onStart method has been called - I usually do it onResume method (you can override it if you haven't already). Doing it in onResume method in the activity makes sure your Fragment has already gone through it's lifecycle up till onResume as well, and data will refresh if it has been brought to the background previously.
Here's a lifecycle diagram for your reference:
You need to use your Fragment factory method when creating your Fragment in your activity. Please see below:
**
Back Stack
**
The transaction in which fragments are modified can be placed on an internal back-stack of the owning activity. When the user presses back in the activity, any transactions on the back stack are popped off before the activity itself is finished.
For example, consider this simple fragment that is instantiated with an integer argument and displays that in a TextView in its UI:
public static class CountingFragment extends Fragment {
int mNum;
/**
* Create a new instance of CountingFragment, providing "num"
* as an argument.
*/
static CountingFragment newInstance(int num) {
CountingFragment f = new CountingFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
/**
* When creating, retrieve this instance's number from its arguments.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
/**
* The Fragment's UI is just a simple text view showing its
* instance number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText("Fragment #" + mNum);
tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
return v;
}
}
A function that creates a new instance of the fragment, replacing whatever current fragment instance is being shown and pushing that change on to the back stack could be written as:
void addFragmentToStack() {
mStackLevel++;
// Instantiate a new fragment.
Fragment newFragment = CountingFragment.newInstance(mStackLevel);
// Add the fragment to the activity, pushing this transaction
// on to the back stack.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, newFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
After each call to this function, a new entry is on the stack, and pressing back will pop it to return the user to whatever previous state the activity UI was in.
Source: https://developer.android.com/reference/android/app/Fragment.html
You need to get the same instance of FragOne from the viewpager.
First, you can only access the FragOne instance after the ViewPager is setup.
Then, try this:
fo = adapter.getItem(0)
Note:
Since you already have fragments, it would be better to let the fragment itself handle the UI-related actions (such as setting the textview) rather than from the Activity.
My problem is that when you open the app is not shown the overflow menu in the actionbar.
If you see en the MainActivity class I have a onOptionsItemSelected for the navigationdrawer, so when I create on the bottom a onCreatedOptionMenu with their respective onOptionsItemSelected fails.
and I dont know how to fix it.
This is what I want
Image
But nothing appears in the actionbar when I open application
This is my menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/Theme.Sherlock">
<item
android:id="#+id/more"
android:icon="#drawable/ic_action_overflow"
android:title="#string/more"
android:showAsAction="always"/>
<menu >
<item
android:id="#+id/contacto"
android:title="#string/contacto"
android:showAsAction="always|withText"/>
<item
android:id="#+id/recomenda"
android:title="#string/recomenda"
android:showAsAction="always|withText"/>
<item
android:id="#+id/salir"
android:title="#string/salir"
android:showAsAction="always|withText"/>
</menu>
MainActivity.java:
public class MainActivity extends SherlockFragmentActivity {
// Declare Variables
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String[] title;
Fragment fragment0 = new Fragment0();
//20 more
private CharSequence mDrawerTitle;
private CharSequence mTitle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from drawer_main.xml
setContentView(R.layout.drawer_main);
// Get the Title
mTitle = mDrawerTitle = "¿Qué buscás?";
// Generate title
title = new String[] { " ASD ", "CORTE LÁSER", "CORTE METALES",
"CORTE POR CHORRO DE AGUA", "CURSOS", "EQUIPOS DE VIDEO", "FICHAS TÉCNICAS",
"FOTÓGRAFOS", "GRÁFICAS", "IMPRESIÓN 3D", "LIBRERÍAS Y PAPELERAS", "MAQUETAS Y PROTOTIPOS",
"MODELADO 3D", "MODELOS", "PLÁSTICOS", "ROUTER", "SUBLIMACIÓN", "TELGOPOR", "TERMOFORMADO",
"TORNERO MADERA", "TORNERO METALES", "VINILOS" };
// Locate DrawerLayout in drawer_main.xml
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Locate ListView in drawer_main.xml
mDrawerList = (ListView) findViewById(R.id.listview_drawer);
// Set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Pass string arrays to MenuListAdapter
mMenuAdapter = new MenuListAdapter(MainActivity.this, title);
// Set the MenuListAdapter to the ListView
mDrawerList.setAdapter(mMenuAdapter);
// Capture listview menu item click
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(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) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
// Set the title on the action when drawer open
getSupportActionBar().setTitle(mDrawerTitle);
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
// ListView click listener 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) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
case 0:
ft.replace(R.id.content_frame, fragment0);
ft.addToBackStack(null);
break;
case 1:
ft.replace(R.id.content_frame, fragment1);
ft.addToBackStack(null);
break;
// and 19 more cases
}
ft.commit();
mDrawerList.setItemChecked(position, true);
// Get the title followed by the position
setTitle(title[position]);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
public boolean onCreatedOptionMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.menu1, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
And the Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
//...
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.Sherlock.Light.ForceOverflow" >
<meta-data
//...
</application>
Please if you need some more information to answer, ask me
(I have not yet allowed to post images to show you my app)
Sorry if I made a mistake when posting, also for my English, I notice that I am beginner coding.
EDIT:
I think that solves the fact that the menu does not appear on the actionbar with this code and deleting the menu.xml:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu subMenu = menu.addSubMenu("Más");
subMenu.add("Volver");
subMenu.add("Contacto");
subMenu.add("Salir");
subMenu.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return true;
}
And added this in the onOptionsItemSelected already have in the MainActivity.java:
if (item.getTitle().toString().equalsIgnoreCase("Publicá!")) {
Intent in = new Intent(getApplicationContext(),Publica.class);
startActivity(in);
Toast.makeText(this, "Publicá tu Negocio/Local/Emprendimiento", Toast.LENGTH_LONG).show();
} if (item.getTitle().toString().equalsIgnoreCase("Contacto")) {
Intent in = new Intent(getApplicationContext(),Contacto.class);
startActivity(in);
Toast.makeText(this, "Contactate y reportanos ...", Toast.LENGTH_LONG).show();
}
if (item.getTitle().toString().equalsIgnoreCase("Salir")) {
Intent i = new Intent(); i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i); android.os.Process.killProcess(android.os.Process.myPid());
Toast.makeText(this, "<-- Busca lo que necesitas", Toast.LENGTH_LONG).show();
}
Now i Have something like This
But not know to generate the menu on the actionbar be an icon instead of text like "Type".
That is my problem now.
This is what you need to do with the item tags
android:showAsAction=["ifRoom" | "never" | "withText" | "always" | "collapseActionView"]
always will always show you menus, never will let your menu item to come in the overflow mode..
set
android:showAsAction="never"
look here for more description.