Header ImageView in Navigation Drawer - Android Eclipse - java

I have created a Navigation Drawer and then I want to put an image header without having it to be part of the item resources. I have created a header image but it was clickable and the id of it was the id of the first item. And the header image become a big header in my whole app which can be seen in every page. How can I fix this.
This is the main activity
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// Boolean keepPlaying = true;
// MediaPlayer mp;
Item btnplay;
MediaPlayer mp;
private boolean isPaused=false;
private int length;
// 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);
mp = new MediaPlayer();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
isPlaying = false;
isPaused = false;
}
});
play(null);//you are calling play by launching
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
// Search
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// History
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Linux Distro
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Dos Vs Linux
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// Linux Commands
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
// Bash Commands
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
// Terminal
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));
// About US
navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons.getResourceId(8, -1)));
// Help
navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuIcons.getResourceId(9, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
//Header of the listview, go to header.xml to customize
View header = getLayoutInflater().inflate(R.layout.header_navi, null);
//addHeaderView is to add custom content into first row
mDrawerList.addHeaderView(header);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(false);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer_invisible, //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(1);
}
}
/**
* 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);
}
}
//inflate items in actionbar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//Background sounds
boolean isPlaying = false;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
mDrawerToggle.onOptionsItemSelected(item);
if (item.getItemId() == R.id.btnplay) //whatever you named in xml
{
invalidateOptionsMenu();
}
return super.onOptionsItemSelected(item);
}
public void play(MenuItem menuItem) {
if (!isPlaying && !isPaused) {
mp = new MediaPlayer();
/* Toast.makeText(getApplicationContext(), "play started",
Toast.LENGTH_SHORT).show();
*/
try {
AssetFileDescriptor afd = getAssets().openFd("bgmusic_mainactivity.ogg");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
afd.getLength());
mp.prepare();
mp.start();// play sound
mp.setLooping(true);
} catch (Exception e) {
e.printStackTrace();
}
isPlaying = true;
} else if (isPlaying) {
/* Toast.makeText(getApplicationContext(), "play paused",
Toast.LENGTH_SHORT).show();
*/
mp.pause();
isPlaying = false;
isPaused = true;
length = mp.getCurrentPosition();
menuItem.setIcon(R.drawable.ic_action_volume_muted);
// and for resuming the player from the position where it stopped
// lately is done by:
} else if (isPaused) {
mp.seekTo(length);
mp.start();
isPlaying = true;
isPaused = false;
menuItem.setIcon(R.drawable.ic_action_volume_on);
}
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(isPlaying){
menu.getItem(0).setIcon(R.drawable.ic_action_volume_on);
}
else{
menu.getItem(0).setIcon(R.drawable.ic_action_volume_muted);
}
return super.onPrepareOptionsMenu(menu);
}
/**
* Displaying 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 CommandList();
break;
case 1:
fragment = new Home();
break;
case 2:
fragment = new History();
break;
case 3:
fragment = new LinuxDistro();
break;
case 4:
fragment = new DosLinux();
break;
case 5:
fragment = new LinuxCommands();
break;
case 6:
fragment = new BashCommands();
break;
case 7:
fragment = new Terminal();
break;
case 8:
fragment = new AboutUs();
break;
case 9:
fragment = new Help();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment!");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
// exit dialog
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you really want to close the app?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Tux To Go Alert!")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mp.stop();
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
header_navi.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/img_header"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:scaleType="fitXY"
android:src="#drawable/header" />
</RelativeLayout>
activity_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/header"
>
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>

There is A simple way to add a image or Header in the Navigation :
you can add any View or image view in the "DrawerLayout" just put your list-view in a "LinearLayout" and add a Image view and the list view in that Layout. It will show the Image View or any other view which you added in the "DrawerLayout" .
As Example :
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/header"
>
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<LinearLayout
android:id="#+id/header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/img_header"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:scaleType="fitXY"
android:src="#drawable/header" />
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>

Just put your <ListView> and <ImageView> in a <RelativeLayout> and add this to <ListView>
android:layout_below="your image id"
Replace your image id with image id.

Related

Navigation Menu Fragment not being able to initialize its layout's components

I've created a navigation menu fragment for my application so that i can use it across all of my activities. However, when i run the app the menu does not work neither when i click on the hamburger icon nor when i pull from left to right. So i decided to use the debugger and i found out that none of my fragment's layout components get initialized within the fragment's class. Can you help me figure out why this happens and how to fix it? Here is my fragment.java class and my fragment_layout.xml file:
Fragment.java:
public class NavMenuFragment extends Fragment {
// NavMenu member vars
private DrawerLayout mDrawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle mToggle; // Button for toggling the side menu
// Keeps the position of the previously selected menu item(0 : Home)
int position = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_nav_menu,null);
mDrawerLayout = view.findViewById(R.id.drawerLayout);
navigationView = view.findViewById(R.id.nav_view);
mToggle = new ActionBarDrawerToggle(getActivity(),mDrawerLayout,R.string.drawer_open,R.string.drawer_closed); // Instantiating our button
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Sets the default selected menu item, to the Home item
navigationView.getMenu().findItem(R.id.nav_home).setChecked(true);
// Used to help on check and uncheck menu items when the user clicks on them
final List<MenuItem> items = new ArrayList<>();
Menu menu;
menu = navigationView.getMenu();
// Fill the list with all the menu items
for(int i=0; i<menu.size();i++) {
items.add(menu.getItem(i));
}
Toast.makeText(getActivity(), "size:" + items.size(), Toast.LENGTH_SHORT).show();
// When an item inside the NavView gets clicked, then handle the event...
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
mDrawerLayout.closeDrawer(Gravity.START);
break;
case R.id.nav_UserBoxGLB:
break;
case R.id.nav_UserBoxJP:
break;
case R.id.nav_settings:
break;
case R.id.nav_feedback:
break;
case R.id.nav_contact_us:
break;
case R.id.nav_donate:
// Open the website's URL in a browser window
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://www.google.com"));
startActivity(intent);
break;
case R.id.nav_about:
break;
default:
return onNavigationItemSelected(item);
}
items.get(position).setChecked(false);
item.setChecked(true);
mDrawerLayout.closeDrawers();
return false;
}
});
mDrawerLayout.addDrawerListener(mToggle);
// Set the hamburger icon's color
mToggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.NavActionBarTextColor));
mToggle.syncState();
}
// When an item from the Action Bar gets tapped, then...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return mToggle.onOptionsItemSelected(item) || onOptionsItemSelected(item);
}
}
Fragment_layout.xml:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_gravity="left"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
android:id="#+id/drawerLayout">
<!-- The actual side menu Nav View -->
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/navigation_header"
app:menu="#menu/navigation_menu"
android:id="#+id/nav_view">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
You are doing it wrong
If you want to use same navigation drawer for all fragment then
You can make a navigation drawer in your main activity and open fragment from that navigation drawer.
Here is the tutorial

Fragment duplicates when I go to another Fragment

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.

FragmentTabHost - No tab known for tag null

Few days ago I implemented TabHostFramgent in a Fragment with a NavigationDrawer, and I faced with a problem that is the following error :
java.lang.IllegalStateException: No tab known for tag null
The thing is that all works perfectly since my first item list of my NavigationDrawer is my TabHostFragment, so it works perfect, but the problem is when I go in example to the second item and then I want to go back to the first item, every time that I try so it crashes.
I was searching everywhere, here in SO, code.google.com, etc... and I still don't get the proper answer.
My tab_host_test_2.xmllooks like :
<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>
My activity_main.xml where I've got my NavigationDrawer looks like :
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
</android.support.v4.widget.DrawerLayout>
My TabHostFragment.java:
public class TabHostFragment extends Fragment {
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);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
mTabHost = (FragmentTabHost)view.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"),
MisOfertasFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),
RecomendacionesFragment.class, null);
}
}
My ActivityMain.java:
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[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)));
//AyudaSugerencias
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
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:
getFragmentManager().beginTransaction().replace(R.id.frame_container, new TipusNouProducte()).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 RecomendacionesFragment();
break;
case 2:
fragment = new LocalizacionFragment();
break;
case 3:
fragment = new ListaProductosFragment();
break;
case 4:
fragment = new ConfiguracionFragment();
break;
case 5:
fragment = new AyudaSugerenciasFragment();
break;
case 6:
fragment = new AyudaSugerencias();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit(); /// here says that replace android.app.Fragment in FragmentTransaction cannot be applied...
// 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);
}
}
The full LogCat error is :
03-04 16:53:05.708 2232-2232/info.androidhive.slidingmenu E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: info.androidhive.slidingmenu, PID: 2232
java.lang.IllegalStateException: No tab known for tag null
at android.support.v4.app.FragmentTabHost.doTabChanged(FragmentTabHost.java:330)
at android.support.v4.app.FragmentTabHost.onAttachedToWindow(FragmentTabHost.java:280)
at android.view.View.dispatchAttachedToWindow(View.java:13406)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2707)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2714)
at android.view.ViewGroup.addViewInner(ViewGroup.java:3919)
at android.view.ViewGroup.addView(ViewGroup.java:3733)
at android.view.ViewGroup.addView(ViewGroup.java:3678)
at android.view.ViewGroup.addView(ViewGroup.java:3654)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:958)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:454)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
EDIT
The answer of #Y.S., was kinda different about what I was asking for, but it could be a solution, but it didn't worked fine at all, and the NavigationDrawer is under the TabHostFragment, etc... I don't want to change anything of my layout.
As the error suggests
Java : illegal state exception : no tab known for tag null
you tried to initialise TabHost but TabHost was null.
Try the code that I have used to initialise the TabHost and it works fine. Keep you code in onCreateView(). This problem occurs when you try to setup your FragmentTabHost in onViewCreated(), which is called too late. Try to set it up in onCreateView(), and add at least one tab before returning the view Object.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Create FragmentTabHost
mTabHost = new FragmentTabHost(getActivity());
// Locate fragment1.xml to create FragmentTabHost
mTabHost.setup(getActivity(), getChildFragmentManager(), R.layout.fragment1);
mTabHost.addTab(mTabHost.newTabSpec("groups").setIndicator("",getResources().getDrawable(R.drawable.tab_group_icon)),FragmentTab1.class, null);
mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("",getResources().getDrawable(R.drawable.tab_user_icon)),FragmentTab2.class, null);
MainActivity.fabButton.setVisibility(View.VISIBLE);
return mTabHost;
}
change Layout to:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
<android.support.v4.app.FragmentTabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
</android.support.v4.app.FragmentTabHost>
</LinearLayout>
Hope it helps.
There is another way to display tabs which can be used here.
Define TabHostFragment like this:
public class TabHostFragment extends Fragment implements ActionBar.TabListener{
public TabHostFragment(){
}
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab_host_test2, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getChildFragmentManager());
final ActionBar actionBar = ((FragmentActivity)getActivity()).getSupportActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment f = null;
switch (i) {
case 0:
f = new MisOfertasFragment();
break;
case 1:
f = new RecomendacionesFragment();
break;
}
return f;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return getFragmentTitle(position);
}
private String getFragmentTitle(int position){
if(position == 0)
return "Tab 1";
else if(position == 1)
return "Tab 2";
else
return "";
}
}
}
Define tab_host_test2.xml like this:
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Rest of the code remains the same.
Try this. This should work.
EDIT:
Add this to the displayView() method:
if(position != 0)
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
specify in .xml file where you are using this TabHostFragment(complete path like com.my.TabHostFragment). like
<com.my.TabHostFragment
android:id="#+id/fragmentId"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>

ActionBarSherlock menu ForceOverflow not showing

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.

How do I add buttons, switches etc. to an android app drawer?

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.

Categories