Action Button Not Showing Drawable in Action Bar - android

I am trying to get an action button to appear in my action bar, however I am only able to get the action overflow to show up instead of the drawable. Here is what I see.
Here is my menu_friends.xml source:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:binder="http://schemas.android.com/apk/res-auto" >
<!-- action_friends should appear as action button -->
<item android:id="#+id/action_friends"
android:icon="#drawable/ic_account_plus_grey600_24dp"
android:title="#string/menu_edit_friends_label"
binder:showAsAction="always" />
</menu>
Here is the fragment where I am inflating the menu:
public class FriendsFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_friends, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.menu_friends, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_friends:
navigateToEditFriends();
}
return super.onOptionsItemSelected(item);
}
private void navigateToEditFriends() {
Intent myIntent = new Intent(FriendsFragment.this.getActivity(), EditFriendsActivity.class);
startActivity(myIntent);
}
}
Here is my MainActivity code:
public class MainActivity extends FragmentActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mDrawerItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mDrawerItems = getResources().getStringArray(R.array.drawer_titles);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the menu_main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// Add items to the ListView
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mDrawerItems));
// Set the OnItemClickListener so something happens when a
// user clicks on an item.
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle the NavigationDrawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
/* // Set the default content area to item 0
// when the app opens for the first time
if(savedInstanceState == null) {
}*/
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
private class DrawerItemClickListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
navigateTo(position);
}
}
private void navigateTo(int position) {
switch(position) {
case 0:
navigateToSettings();
break;
case 1:
userLogout();
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return (position ==0)? "Inbox" : "Friends";
}
#Override
public int getCount() {
return 2;
}
#Override
public Fragment getItem(int position) {
return (position ==0)? new InboxFragment() : new FriendsFragment();
}
}
private void userLogout() {
ParseFacebookUtils.getSession().closeAndClearTokenInformation();
ParseUser.logOut();
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
private void navigateToSettings() {
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
}
}
Any help on this would be greatly appreciated!
-R

Put the setHasOptionsMenu() in your Fragments onCreate methode and not in onCreateView() methode. That should do the trick.

Related

Update an TextView in NavigationDrawer after input from user in previous activity

There is some information that I want to display in the NavigationDrawer. This information is entered by the user in a previous activity. I use an intent to send the information to the Main Activity for the Drawer.
MainActivity (After user entered details)
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
String info = intent.getStringExtra("info");
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
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.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.nav_item_dashboard);
break;
......
}
I have a specific layout for the navigation drawer and it contains a textview which I want to update with the String test. This is the fragment code and the xml for it.
FragmentDrawer Class
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
navItem.setIcon(icons.getResourceId(i,-1));
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
icons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
TextView userID = (TextView) layout.findViewById(R.id.nav_title_user);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
FramgentDrawer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white">
<RelativeLayout
android:id="#+id/nav_header_container"
android:layout_width="match_parent"
android:layout_height="140dp"
android:layout_alignParentTop="true"
android:background="#color/colorPrimary">
......
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceInverse"
android:text="#string/welcome_user"
android:id="#+id/nav_title_user"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"/>
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_below="#id/nav_header_container" />
I have managed to update the list in the drawer with Icons, Labels and a Header. I have done so by using a RecyclerViewAdapter.
The problem that I am having is that these details were from the resources (strings.xml).
How can I update a textview on a NavigationFragment when it has been created? How can I send a value to the fragment so that it will be used during OnCreateView of the fragment?
I was looking too much into it. The solution was quite simple...Even though it took me 3 hrs to figure this out :/
In the NavigationFragment, I created a method to update a textview with a string. In the MainActivity where I get the information from the intent, I just called the method like this:
drawerFragment.setUserTextView(info);
This is why taking breaks are important... ^^

Android Navigation Drawer can't click on one item

I have a really interesting problem with my Navigator menu.
I have no idea why... But I can click on any item from my menu, I don't want to say I click and nothing happened. I really want to say I can't click on any item, all my menu it's like a big image.
I've try to make a new project witch already have Navigation Drawer Activity, of course it works.. but when I've try to copy that code and put on mine.. I have the same problem and vice versa, I've try to put my code into a new project with Navigation Drawer Activity, but again... I can't click on any item.
Here it's one image with my aplication.
Here it's my Main Activity:
public class MainActivity extends Activity implements NavigationDrawerFragment.NavigationDrawerCallbacks, AdapterView.OnItemClickListener {
ArrayList<Trail> arrayTrail;
ListView listViewTrails;
ArrayList<Wonder> arrayWonders1;
ArrayList<Wonder> arrayWonders2;
ArrayList<Wonder> arrayWonders3;
ArrayList<Wonder> arrayWonders4;
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
arrayWonders1 = new ArrayList<>();
arrayWonders2 = new ArrayList<>();
arrayWonders3 = new ArrayList<>();
arrayWonders4 = new ArrayList<>();
arrayWonders1.add(new Wonder("https://risehighershinebrighter.files.wordpress.com/2014/11/magic-of-blue-universe-images.jpg", "Ceva", "100"));
arrayWonders1.add(new Wonder("http://i765.photobucket.com/albums/xx291/just-meller/national%20geografic/Birds-national-geographic-6873734-1600-1200.jpg", "Ceva", "20"));
arrayWonders2.add(new Wonder("hhttp://www.freestockphotos.name/wallpaper-original/wallpapers/download-images-of-gentle-dogs-6866.jpg", "Ceva", "400"));
arrayWonders2.add(new Wonder("http://www.planwallpaper.com/static/images/desktop-year-of-the-tiger-images-wallpaper.jpg", "Ceva", "200"));
arrayWonders3.add(new Wonder("http://hdwallnpics.com/wp-content/gallery/hd-tiger-images/tigers-wallpapers-hd.jpg", "Ceva", "100"));
arrayWonders3.add(new Wonder("http://imgscenter.com/images/2014/09/13/6-autumn-nature-sandbox-images_2053316.jpg", "Ceva", "100"));
arrayWonders4.add(new Wonder("http://www.tollywooddaily.com/wp-content/uploads/2015/05/HORIZONTAL-BABY-HIGHRES-EMPTY.jpg", "Ceva", "100"));
arrayWonders4.add(new Wonder("http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg", "Ceva", "100"));
arrayTrail = new ArrayList<>();
Trail audi = new Trail("http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg", "Paris", "Popular Destination", "htrhetgftrwfrec", "Story", arrayWonders1);
Trail opel = new Trail("http://www.gettyimages.com/gi-resources/images/CreativeImages/Hero-527920799.jpg", "Romania", "Popular Destination", "fewfwefwefWgfeg", "Story", arrayWonders2);
Trail mercedes = new Trail("http://blog.jimdo.com/wp-content/uploads/2014/01/tree-247122.jpg", "Italia", "Popular Destination", "gtrhrthtrhrw", "Story", arrayWonders3);
Trail ferrari = new Trail("http://saturn.jpl.nasa.gov/multimedia/images/moons/images/PIA07759.jpg", "Roma", "Popular Destination", "dajfuisndfisndfs", "Story", arrayWonders4);
Trail fiesta = new Trail("http://www.quicksprout.com/images/foggygoldengatebridge.jpg", "Bucuresti", "Popular Destination", "regehgtrhrjhjy", "Story", arrayWonders1);
Trail porshe = new Trail("http://3.bp.blogspot.com/-rZmCIp0C-hQ/Tx6aCFeweoI/AAAAAAAAAnQ/WqIEVBTIzRk/s1600/Cool-Tiger-Wallpaper-1920x1080-HD.jpg", "Luxemburg", "Popular Destination", "Ffdsjifsdfmskodmf", "Story", arrayWonders2);
arrayTrail.add(audi);
arrayTrail.add(opel);
arrayTrail.add(mercedes);
arrayTrail.add(ferrari);
arrayTrail.add(fiesta);
arrayTrail.add(porshe);
listViewTrails = (ListView) findViewById(R.id.list_trails);
ListTailsAdapter adapter = new ListTailsAdapter(this, arrayTrail);
listViewTrails.setAdapter(adapter);
listViewTrails.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Trail selectedTrail = arrayTrail.get(position);
Intent intent = new Intent(this, TrailActivity.class);
intent.putExtra("trail", selectedTrail);
startActivity(intent);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, PlaceholderFragment.newInstance(position + 1)).commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.main_menu_search) {
ArrayList<Trail> trails = arrayTrail;
Intent intent = new Intent(this, SearchActivity.class);
intent.putExtra("trailsSearch", trails);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
And here it Navigation Drawer Fragment class:
public class NavigationDrawerFragment extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private NavigationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.categori_1),
getString(R.string.categori_2),
getString(R.string.categori_3),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(),
mDrawerLayout,
R.drawable.ic_drawer,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.main, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
public static interface NavigationDrawerCallbacks {
void onNavigationDrawerItemSelected(int position);
}
}
So if anyone of you guys have any idea... Please tell me, I really need to fix it as soon as possible and in this moment I don't have any idea how..
Thx for your help :)
this code work for me
public class MyDrawer extends AppCompatActivity {
ActionBarDrawerToggle toggle;
// other code
super.setContentView(fullLayout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout3);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
drawer.closeDrawers();
int itemId = menuItem.getItemId();
//Toast.makeText(getApplicationContext(), menuItem.getTitle().toString(),
// Toast.LENGTH_LONG).show();
int id = menuItem.getItemId();
if (id == R.id.nav_camara) {
update();
// Handle the camera action
} else if (id == R.id.nav_gallery) {
Intent intent = new Intent(getApplicationContext(), AndroidListViewCursorAdaptorActivity.class);
startActivity(intent);
// } else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
Intent intent = new Intent(getApplicationContext(), Manage.class);
startActivity(intent);
} else if (id == R.id.nav_about) {
Intent intent = new Intent(getApplicationContext(), About.class);
startActivity(intent);
}
else if (id == R.id.nav_cantect) {
Intent intent = new Intent(getApplicationContext(), AboutCantect.class);
startActivity(intent);
}
//navigationView.getMenu().findItem(R.id.drawer_5_reasons).setChecked(true);
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (toggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}

ActionBar is not showing Title in Android

I want to implement Left & Right Side Slider Menu so I have set Right Side Slider in NavigationDrawerSlider which already have Left Side Slider by Default.
I am using ActionBarSherLock for this to support Application from Api 8. Slider is working fine but issue is that ActionBar is not showing Title.
Please help me to solve this issue. One more thing, When I Click on ImageView, It also fires ActionBarDrawerToggle. So, how to prevent this also ?
My Code:
public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList_Left;
private ListView mDrawerList_Right;
private ActionBarDrawerToggle mDrawerToggle;
private ActionBar actionBar_Right;
private ArrayList<NavDrawerItem> navDrawerItems_Left;
private ArrayList<NavDrawerItem> navDrawerItems_Right;
private CharSequence mDrawerTitle_Left;
private CharSequence mTitle_Left;
private CharSequence mDrawerTitle_Right;
private CharSequence mTitle_Right;
private String[] mFragmentTitles_Left;
private String[] mFragmentTitles_Right;
private TypedArray navMenuIcons_Left;
private TypedArray navMenuIcons_Right;
private NavDrawerListAdapter adapter_Left;
private NavDrawerListAdapter adapter_Right;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle_Left = mDrawerTitle_Left = getTitle();
mFragmentTitles_Left = getResources().getStringArray(
R.array.nav_drawer_items);
mFragmentTitles_Right = getResources().getStringArray(
R.array.nav_drawer_items_right);
navMenuIcons_Left = getResources().obtainTypedArray(
R.array.nav_drawer_icons);
navMenuIcons_Right = getResources().obtainTypedArray(
R.array.nav_drawer_icons_right);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList_Left = (ListView) findViewById(R.id.list_left_slidermenu);
mDrawerList_Right = (ListView) findViewById(R.id.list_right_slidermenu);
actionBar_Right = getSupportActionBar();
actionBar_Right.setCustomView(R.layout.right_menu);
actionBar_Right.setDisplayShowTitleEnabled(true);
actionBar_Right.setDisplayShowCustomEnabled(true);
navDrawerItems_Left = new ArrayList<NavDrawerItem>();
navDrawerItems_Right = new ArrayList<NavDrawerItem>();
// Left Side Menus...
// Home...
navDrawerItems_Left.add(new NavDrawerItem(mFragmentTitles_Left[0],
navMenuIcons_Left.getResourceId(0, -1)));
navMenuIcons_Left.recycle();
// Right Side Menus...
// Edit Profile...
navDrawerItems_Right.add(new NavDrawerItem(mFragmentTitles_Right[0],
navMenuIcons_Right.getResourceId(0, -1)));
// Change Password...
navDrawerItems_Right.add(new NavDrawerItem(mFragmentTitles_Right[1],
navMenuIcons_Right.getResourceId(1, -1)));
navMenuIcons_Right.recycle();
mDrawerList_Left
.setOnItemClickListener(new DrawerItemClickListener_Left());
mDrawerList_Right
.setOnItemClickListener(new DrawerItemClickListener_Right());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
adapter_Left = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems_Left);
mDrawerList_Left.setAdapter(adapter_Left);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name);
adapter_Right = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems_Right);
mDrawerList_Right.setAdapter(adapter_Right);
ImageView imgRight = (ImageView) findViewById(R.id.imgRightMenu);
imgRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (mDrawerLayout.isDrawerOpen(mDrawerList_Right)) {
mDrawerLayout.closeDrawer(mDrawerList_Right);
setTitle(mTitle_Right);
} else {
mDrawerLayout.openDrawer(mDrawerList_Right);
mDrawerLayout.closeDrawer(mDrawerList_Left);
setTitle(mDrawerTitle_Right);
}
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem_Left(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawerList_Left)) {
mDrawerLayout.closeDrawer(mDrawerList_Left);
setTitle(mTitle_Left);
} else {
mDrawerLayout.openDrawer(mDrawerList_Left);
mDrawerLayout.closeDrawer(mDrawerList_Right);
setTitle(mDrawerTitle_Left);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener_Left implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
selectItem_Left(position);
}
}
private void selectItem_Left(int position) {
Fragment newFragment = new Home();
FragmentManager fm = getSupportFragmentManager();
switch (position) {
case 0:
newFragment = new Home();
break;
}
fm.beginTransaction().replace(R.id.frame_container, newFragment)
.commit();
mDrawerList_Left.setItemChecked(position, true);
setTitle(mFragmentTitles_Left[position]);
mDrawerLayout.closeDrawer(mDrawerList_Left);
}
private class DrawerItemClickListener_Right implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
selectItem_Right(position);
}
}
private void selectItem_Right(int position) {
Fragment newFragment = new EditProfile();
FragmentManager fm = getSupportFragmentManager();
switch (position) {
case 0:
newFragment = new EditProfile();
break;
case 1:
newFragment = new ChangePassword();
break;
}
fm.beginTransaction().replace(R.id.frame_container, newFragment)
.commit();
mDrawerList_Right.setItemChecked(position, true);
setTitle(mFragmentTitles_Right[position]);
mDrawerLayout.closeDrawer(mDrawerList_Right);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
I have figured out that It is not showing title because of
actionBar_Right = getSupportActionBar();
actionBar_Right.setCustomView(R.layout.right_menu);
actionBar_Right.setDisplayShowTitleEnabled(true);
actionBar_Right.setDisplayShowCustomEnabled(true);
What to do for this ?
For showing the title in the ActionBar setTitle must be overridden:
#Override
public void setTitle(CharSequence title)
{
this.title = title;
getSupportActionBar().setTitle(title);
}

android tabHost brakes listviews onArticleSelected

I have a Main Drawer activity which loads my fragments when a drawer item is selected. The fragment that is laoded contains a tabhost which hosts multiple fragments so you can switch to via tabs.
Before Tabs I had a fragment with a bunch of butons that when clicked, replaced the current fragment with a new fragment. The fragments all have listviews in them, and when you click an item replaced the current listview fragment with another fragment.
My problem is when I placed all my fragments into a tabhost the ArticleOnSelected no longer works, and force closes my app when ever an item is actually selected form the list view. Here is an example of one of the FC errors:
03-02 16:40:34.121 9066-9066/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalArgumentException: No view found for id 0x7f09008c (com.beerportfolio.beerportfoliopro:id/main) for fragment BreweryPage2{41ba3478 #2 id=0x7f09008c}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
I see the problem is with the view, and I think it can not access the main framelayout from the layout which holds all the fragments with the navigation drawer.
My MainDrawer2 class is what opens first and is where the drawer and fragments are loaded into. The code is:
public class MainDrawer2 extends FragmentActivity
{
private static final String EXTRA_NAV_ITEM = "extraNavItem";
private static final String STATE_CURRENT_NAV = "stateCurrentNav";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavDrawerListAdapter mDrawerAdapter;
private ListView mDrawerList;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private MainNavItem mCurrentNavItem;
public static Intent createLaunchFragmentIntent(Context context, MainNavItem navItem)
{
return new Intent(context, MainDrawer2.class)
.putExtra(EXTRA_NAV_ITEM, navItem.ordinal());
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer);
getActionBar().setDisplayHomeAsUpEnabled(true);
enableHomeButtonIfRequired();
mDrawerAdapter = new NavDrawerListAdapter(getApplicationContext());
mDrawerList.setAdapter(mDrawerAdapter);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayNavFragment((MainNavItem)parent.getItemAtPosition(position));
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(getIntent().hasExtra(EXTRA_NAV_ITEM)){
MainNavItem navItem = MainNavItem.values()
[getIntent().getIntExtra(EXTRA_NAV_ITEM,
MainNavItem.STATISTICS.ordinal())];
displayNavFragment(navItem);
}
else if(savedInstanceState != null){
mCurrentNavItem = MainNavItem.values()
[savedInstanceState.getInt(STATE_CURRENT_NAV)];
setCurrentNavItem(mCurrentNavItem);
}
else{
displayNavFragment(MainNavItem.STATISTICS);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void enableHomeButtonIfRequired()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
getActionBar().setHomeButtonEnabled(true);
}
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getActionBar().setTitle(mTitle);
}
#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
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
#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);
}
*/
private void displayNavFragment(MainNavItem navItem)
{
if(navItem == mCurrentNavItem){
return;
}
Fragment fragment = Fragment.instantiate(this,
navItem.getFragClass().getName());
if(fragment != null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, fragment)
.commit();
setCurrentNavItem(navItem);
}
}
private void setCurrentNavItem(MainNavItem navItem)
{
int position = navItem.ordinal();
// If navItem is in DrawerAdapter
if(position >= 0 && position < mDrawerAdapter.getCount()){
mDrawerList.setItemChecked(position, true);
}
else{
// navItem not in DrawerAdapter, de-select current item
if(mCurrentNavItem != null){
mDrawerList.setItemChecked(mCurrentNavItem.ordinal(), false);
}
}
mDrawerLayout.closeDrawer(mDrawerList);
setTitle(navItem.getTitleResId());
mCurrentNavItem = navItem;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToSearch(MenuItem item){
//go to search page
Fragment Fragment_one;
FragmentManager man= getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new Search();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
The default fragment which is loaded is the fragment which holds my tabhost and creates the tabs:
public class StatisticsTab extends Fragment {
private FragmentTabHost mTabHost;
//Mandatory Constructor
public StatisticsTab() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tabs,container, false);
mTabHost = (FragmentTabHost)rootView.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("Basic").setIndicator("Basic"),
StatisticsPage.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Brewery").setIndicator("Brewery"),
BreweryStatistics.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Style").setIndicator("Style"),
StyleStatistics.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Taste").setIndicator("Taste"),
TasteStatisticsPage.class, null);
return rootView;
}
}
If I click on an item in my tab and bring up the listview like this:
It gives me the FC I posted above. The code for this fragment is:
public class BreweryStatistics extends Fragment implements GetBreweryStatisticsJSON.OnArticleSelectedListener {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.brewery_statistics_layout, container, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
String url = "myURL";
//async task to get beer taste tag percents
GetBreweryStatisticsJSON task = new GetBreweryStatisticsJSON(getActivity());
task.setOnArticleSelectedListener(this);
task.execute(url);
// Inflate the layout for this fragment
return v;
}
#Override
public void onArticleSelected(String bID){
//code to execute on click
Fragment Fragment_one;
FragmentManager man= getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new BreweryPage2();
final Bundle bundle = new Bundle();
bundle.putString("breweryIDSent", bID);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
And when that onArticleSelected above is executed it does not load the new fragment. In theory what should happen the Fragment that holds the tabhost StatisticsTab should be replaced with the new Fragment in the OnArticleSelected

setIconified(false) force closes my app

Right now I have it not force closing but the keyboard pops up without the search box openning up, like in this picture:
My Search Fragment activity looks like:
public class Search extends Fragment implements SearchView.OnQueryTextListener, ReadJSONResult.OnArticleSelectedListener {
private ListView lv;
View v;
SearchView searchView;
private SearchView mSearchView;
private MenuItem mSearchMenuItem;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//set layout here
v = inflater.inflate(R.layout.activity_search, container, false);
setHasOptionsMenu(true);
getActivity().setTitle("Search");
//get user information
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//ActionBar actionBar = getActivity().getActionBar();
// Inflate the layout for this fragment
return v;
}
#Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
searchView = (SearchView) menu.findItem(R.id.menu_search2).getActionView();
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
}
public boolean onQueryTextSubmit (String query) {
//toast query
//make json variables to fill
// url to make request
String url = "myURL";
try {
query = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonUrl = url + query;
//todo: get json
ReadJSONResult task = new ReadJSONResult(getActivity());
task.setOnArticleSelectedListener(this);
task.execute(jsonUrl);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onArticleSelected(String b, String brewery){
//code to execute on click
Fragment Fragment_one;
FragmentManager man= getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new BeerPage();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", b);
bundle.putString("breweryIDSent", brewery);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
my android action bar menu xml is:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity" >
<item android:id="#+id/menu_search2"
android:actionViewClass="android.widget.SearchView"
android:title="Search"
android:icon="#android:drawable/ic_menu_search"
android:showAsAction="ifRoom|collapseActionView"
/>
</menu>
The activity this fragment is loaded into is:
public class MainDrawer2 extends FragmentActivity
{
private static final String EXTRA_NAV_ITEM = "extraNavItem";
private static final String STATE_CURRENT_NAV = "stateCurrentNav";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavDrawerListAdapter mDrawerAdapter;
private ListView mDrawerList;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private MainNavItem mCurrentNavItem;
public static Intent createLaunchFragmentIntent(Context context, MainNavItem navItem)
{
return new Intent(context, MainDrawer2.class)
.putExtra(EXTRA_NAV_ITEM, navItem.ordinal());
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer);
getActionBar().setDisplayHomeAsUpEnabled(true);
enableHomeButtonIfRequired();
mDrawerAdapter = new NavDrawerListAdapter(getApplicationContext());
mDrawerList.setAdapter(mDrawerAdapter);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayNavFragment((MainNavItem)parent.getItemAtPosition(position));
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(getIntent().hasExtra(EXTRA_NAV_ITEM)){
MainNavItem navItem = MainNavItem.values()
[getIntent().getIntExtra(EXTRA_NAV_ITEM,
MainNavItem.STATISTICS.ordinal())];
displayNavFragment(navItem);
}
else if(savedInstanceState != null){
mCurrentNavItem = MainNavItem.values()
[savedInstanceState.getInt(STATE_CURRENT_NAV)];
setCurrentNavItem(mCurrentNavItem);
}
else{
displayNavFragment(MainNavItem.STATISTICS);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void enableHomeButtonIfRequired()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
getActionBar().setHomeButtonEnabled(true);
}
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getActionBar().setTitle(mTitle);
}
#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
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
#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);
}
*/
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if(mDrawerToggle.onOptionsItemSelected(item)){
return true;
}
switch(item.getItemId()){
case R.id.menu_search2:
displayNavFragment(MainNavItem.SEARCH);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void displayNavFragment(MainNavItem navItem)
{
if(navItem == mCurrentNavItem){
return;
}
Fragment fragment = Fragment.instantiate(this,
navItem.getFragClass().getName());
if(fragment != null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, fragment)
.commit();
setCurrentNavItem(navItem);
}
}
private void setCurrentNavItem(MainNavItem navItem)
{
int position = navItem.ordinal();
// If navItem is in DrawerAdapter
if(position >= 0 && position < mDrawerAdapter.getCount()){
mDrawerList.setItemChecked(position, true);
}
else{
// navItem not in DrawerAdapter, de-select current item
if(mCurrentNavItem != null){
mDrawerList.setItemChecked(mCurrentNavItem.ordinal(), false);
}
}
mDrawerLayout.closeDrawer(mDrawerList);
setTitle(navItem.getTitleResId());
mCurrentNavItem = navItem;
}
}
looks like here
searchView.setIconified(false);
"searchView" has not been initialized properly yet, because before you create the field, but didn't assign any view for it:
SearchView searchView;
So in your onCreateView you should find your View by Id first before calling methods of searchView:
searchView = (SearchView) findViewById(R.id.the_view_id_here);

Categories

Resources