Action bar Icon menu issue on Fragment - android

well just when I solved an issue another one is comming right there, and I don't know if I'm violating any rule of this forum posting everything I got an issue, I hope not, but here I go again, I'm trying to add an Icon menu to the Action bar within my fragment, on my parent activity I don't know have action bar menu, so I don't trying to replace the menu on my fragment, because I just use a DrawerLayout to drawer a list menu and it's all, but in some specific Fragments I want to show some action bar icon menu, I've search in the forum before posting but I didn't find something than can help me, because I'm not sure what is going on, I did the two stepts to show and action bar menu on fragments read on others post, I even tried using the default menu.xml created by android studio, in two differents fragment, but for some reason the menu is not being showing on fragments Action bar, I'm not sure if I have to do something on my parent Activity first, but here are my both code Activity and Fragmen
Parent Activity code which is declared the DrawerLayout menu list
import java.util.ArrayList
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private String[] titulos;
private DrawerLayout NavDrawerLayout;
private ListView NavList;
private ArrayList<Item_objct> NavItms;
private TypedArray NavIcons;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
Fragment ventas;
NavigationAdapter NavAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__main);
NavDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavList = (ListView) findViewById(R.id.lista);
View header = getLayoutInflater().inflate(R.layout.header, null);
NavList.addHeaderView(header);
NavIcons = getResources().obtainTypedArray(R.array.navigation_iconos);
titulos = getResources().getStringArray(R.array.nav_options);
NavItms = new ArrayList<Item_objct>();
NavItms.add(new Item_objct(titulos[0], NavIcons.getResourceId(0, -1)));
NavItms.add(new Item_objct(titulos[1], NavIcons.getResourceId(1, -1)));
NavItms.add(new Item_objct(titulos[2], NavIcons.getResourceId(2, -1)));
NavItms.add(new Item_objct(titulos[3], NavIcons.getResourceId(3, -1)));
NavItms.add(new Item_objct(titulos[4], NavIcons.getResourceId(4, -1)));
NavItms.add(new Item_objct(titulos[5], NavIcons.getResourceId(5, -1)));
NavAdapter= new NavigationAdapter(this,NavItms);
NavList.setAdapter(NavAdapter);
mTitle = mDrawerTitle = getTitle();
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
NavDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* Icono de navegacion*/
R.string.app_name, /* "open drawer" description */
R.string.hello_world /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
Log.e("Cerrado completo", "!!");
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
Log.e("Apertura completa", "!!");
}
};
NavDrawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
NavList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
MostrarFragment(position);
}
});
ventas = new VentasFragment();
}
private void MostrarFragment(int position) {
Fragment fragment = null;
switch (position) {
case 0:
//fragment = new HomeFragment();
break;
case 1:
fragment = ventas;
break;
case 4:
fragment = new customerFragment();
break;
default:
//si no esta la opcion mostrara un toast y nos mandara a Home
Toast.makeText(getApplicationContext(),"Opcion "+titulos[position-1]+"no disponible!", Toast.LENGTH_SHORT).show();
// fragment = new HomeFragment();
position=1;
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
NavList.setItemChecked(position, true);
NavList.setSelection(position);
if(position > 0)
setTitle(titulos[position-1]);
else
setTitle("Balance General");
NavDrawerLayout.closeDrawer(NavList);
} else {
Log.e("Error ", "MostrarFragment"+position);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
Log.e("mDrawerToggle pushed", "x");
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
}
Fragment Code where I want to implement the action bar menu
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.ToggleButton;
public class customerFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public static customerFragment newInstance(String param1, String param2) {
customerFragment fragment = new customerFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public customerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_customer, container, false);
// Inflate the layout for this fragment
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
//mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.main, menu);
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
As you see on Fragment Code, I call setHasOptionMenu(true); whithin onCreat() in the last line, and I inflate my menu.xml whithin onCreateOptionMenu(), but I doesn't showing anything anyways, I'm not pretty sure about what is going on, why It doesn't work anyways.
Thank you so much beforehand, and sorry if the issue is quickly obvious, I'm beginner yet and I don't understand a lot of things of Methods Overriding and Callings.

What if you try to add items programmatically instead of inflater.inflate(R.menu.main, menu), like this:
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.add(0, R.id.your_id, 0,
getResources().getString(R.string.your_string))
.setIcon(R.drawable.your_icon)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
That's working for me.

Related

Errors in Navigation Drawer Activity

I'm trying to create a navigation drawer for Android. I've followed these pages (this and this) but now I'm stuck.
Here's my code, based on the planet navigation drawer:
package com.example.side_navigation_from_scratch;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private String mDrawerTitle;
private String mainTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
mainTitle = mDrawerTitle = (String) getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mainTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mainTitle = (String) title;
getActionBar().setTitle(mainTitle);
}
/**
* 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);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
TextView planetName = (TextView) rootView.findViewById(R.id.text);
getActivity().setTitle(planet);
return rootView;
}
}
}
I get different errors depending on the changes I make.
Like it is right now, I get
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
ActionBarActivity is deprecated so I'm not going to use it but if I change Activity to AppCompatActivity, I get
java.lang.IllegalArgumentException: AppCompat does not support the current theme features
What am I doing wrong? Which is better to use: Activity, ActionBarActivity or AppCompatActivity? Thanks in advance
Thanks to Raghunandan I managed to fix this: I changed the Activity to AppCompatActivity and replaced getActionBar for getSupportActionBar. I don't have any more NPE

Android: Starting a navigation drawer from an activity

There are lots of question which are similar to mine but I couldn't find any solution in those answers.
My program first shows a splash screen than comes to a log-in screen. After the user logs in I want to call the navigation drawer because my main screen and profile screen are in the navigation drawer as a fragment. So basically iI am trying to call a fragment which is a part of navigation drawer, from an activity.
Here is how I try to call the fragment;
private void loguserIn(User returnedUser){
userLocalStore.storeUserData(returnedUser);
userLocalStore.setUserLoggedIn(true);
Intent intent = new Intent(this,userprofile.class);
startActivity(intent);
}
But when i call this method it force closes.
Here is the userprofile fragment;
package com.okanyakit.watchme;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by okan on 4/23/2015.
*/
public class userprofile extends android.support.v4.app.Fragment implements View.OnClickListener{
View rootview;
Button logoutbutton;
EditText regusername, regpassword, regemail, regphonenumber, regbloodtype, regbirthday, regaddress;
UserLocalStore userLocalStore;
Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.userprofile_layout,container,false);
regusername = (EditText)rootview.findViewById(R.id.regusername);
regpassword = (EditText)rootview.findViewById(R.id.regpassword);
regemail = (EditText)rootview.findViewById(R.id.regemail);
regphonenumber = (EditText)rootview.findViewById(R.id.regphonenumber);
regbloodtype = (EditText)rootview.findViewById(R.id.regbloodtype);
regbirthday = (EditText)rootview.findViewById(R.id.regbirthday);
regaddress = (EditText)rootview.findViewById(R.id.regaddress);
logoutbutton = (Button)rootview.findViewById(R.id.regbutton);
logoutbutton.setOnClickListener(this);
userLocalStore = new UserLocalStore(this);
return rootview;
}
#Override
public void onStart() {
super.onStart();
if (authenticate()== true)
{
displayUserDetails();
}
else{
Intent intent = new Intent(getActivity(),loginscreen.class);
startActivity(intent);
}
}
private void displayUserDetails()
{
User user = userLocalStore.getLoggedInUser();
regusername.setText(user.username);
regemail.setText(user.email);
regphonenumber.setText(user.phonenumber);
regbloodtype.setText(user.bloodtype);
regaddress.setText(user.address);
}
private boolean authenticate()
{
return userLocalStore.getuserloogedin();
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.logoutbutton:
userLocalStore.clearUserData();
userLocalStore.setUserLoggedIn(false);
break;
}
}
}
Here is the slide menu ;
package com.okanyakit.watchme;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class slidemenu extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slidemenu);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objfragment = null;
switch (position) {
case 0:
objfragment = new mainscreen();
break;
case 1:
objfragment = new userprofile();
break;
case 2:
objfragment = new usermessage();
break;
case 3:
objfragment = new alarmsettings();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objfragment)
.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;
case 4:
mTitle = getString(R.string.title_section4);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.slidemenu, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given 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_slidemenu, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((slidemenu) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
Andr here is the navigationdrawer class
package com.okanyakit.watchme;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
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);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
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_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
getString(R.string.title_section4),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).commit();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
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);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
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 ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
I don't know what is the main cause of this so tried to put everything that is involved in here.
I think this should work for you.
DrawerLayout mLayout = (DrawerLayout) mNavigationDrawerFragment.findViewById(R.id.drawer_layout);
mLayout.openDrawer(mLayout);
You cannot call a fragment with Intents. An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity.
You can call your fragment with
ExampleFragment fragment = (ExampleFragment)getFragmentManager.getfindFragmentById(R.id.example_fragment);
To put the fragment in your activity, use this method in your oncreate of your activity:
if (savedInstance == null)
{
getFragmentManger().beginTransaction().Add(R.id.container, new ExampleFragment()).commit();
}
where R.id.container is the ID in your activity layoutfile of the placeholder in which you want to place your fragments.

Cannot resolve symbol in main activity java class

I cannot find out what the problem is here! I am following this tutorial for building a navigation drawer with fragments and I cannot find a way to fix the "cannot resolve symbol error". The error is on "drawer_nav_item". I have looked for unused classes and other times that it is used and cannot find it! Please Help! I can provide more code upon request
This is my activity_main.xml
package com.nhscoding.safe2tell;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import com.nhscoding.safe2tell.AboutClass;
import com.nhscoding.safe2tell.FragmentNavigationDrawer;
import com.nhscoding.safe2tell.LearnClass;
import com.nhscoding.safe2tell.R;
import com.nhscoding.safe2tell.SettingsClass;
import com.nhscoding.safe2tell.StoriesClass;
import com.nhscoding.safe2tell.SubmitClass;
public class MainActivity extends FragmentActivity {
private FragmentNavigationDrawer dlDrawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find our drawer view
dlDrawer = (FragmentNavigationDrawer) findViewById(R.id.drawer_layout);
// Setup drawer view
dlDrawer.setupDrawerConfiguration((ListView) findViewById(R.id.lvDrawer),
R.layout.drawer_nav_item, R.id.flContent);
// Add nav items
dlDrawer.addNavItem("Submit", "Submit Class", SubmitClass.class);
dlDrawer.addNavItem("Second", "Second Fragment", StoriesClass.class);
dlDrawer.addNavItem("Third", "Third Fragment", LearnClass.class);
dlDrawer.addNavItem("Fouth", "Fourth Fragment", AboutClass.class);
dlDrawer.addNavItem("Fifth", "Fifth Fragment", SettingsClass.class);
// Select default
if (savedInstanceState == null) {
dlDrawer.selectDrawerItem(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
if (dlDrawer.isDrawerOpen()) {
// Uncomment to hide menu items
// menu.findItem(R.id.mi_test).setVisible(false);
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Uncomment to inflate menu items to Action Bar
// inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (dlDrawer.getDrawerToggle().onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
dlDrawer.getDrawerToggle().syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
dlDrawer.getDrawerToggle().onConfigurationChanged(newConfig);
}
}
Here is my Navigation Drawer Class
package com.nhscoding.safe2tell;
import java.util.ArrayList;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.nhscoding.safe2tell.R;
public class FragmentNavigationDrawer extends DrawerLayout {
private ActionBarDrawerToggle drawerToggle;
private ListView lvDrawer;
private ArrayAdapter<String> drawerAdapter;
private ArrayList<FragmentNavItem> drawerNavItems;
private int drawerContainerRes;
public FragmentNavigationDrawer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public FragmentNavigationDrawer(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FragmentNavigationDrawer(Context context) {
super(context);
}
// setupDrawerConfiguration((ListView) findViewById(R.id.lvDrawer), R.layout.drawer_list_item, R.id.flContent);
public void setupDrawerConfiguration(ListView drawerListView, int drawerItemRes, int drawerContainerRes) {
// Setup navigation items array
drawerNavItems = new ArrayList<FragmentNavigationDrawer.FragmentNavItem>();
// Set the adapter for the list view
drawerAdapter = new ArrayAdapter<String>(getActivity(), drawerItemRes,
new ArrayList<String>());
this.drawerContainerRes = drawerContainerRes;
// Setup drawer list view and related adapter
lvDrawer = drawerListView;
lvDrawer.setAdapter(drawerAdapter);
// Setup item listener
lvDrawer.setOnItemClickListener(new FragmentDrawerItemListener());
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
drawerToggle = setupDrawerToggle();
setDrawerListener(drawerToggle);
// set a custom shadow that overlays the main content when the drawer
setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// Setup action buttons
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
// addNavItem("First", "First Fragment", FirstFragment.class)
public void addNavItem(String navTitle, String windowTitle, Class<? extends Fragment> fragmentClass) {
drawerAdapter.add(navTitle);
drawerNavItems.add(new FragmentNavItem(windowTitle, fragmentClass));
}
/** Swaps fragments in the main content view */
public void selectDrawerItem(int position) {
// Create a new fragment and specify the planet to show based on
// position
FragmentNavItem navItem = drawerNavItems.get(position);
Fragment fragment = null;
try {
fragment = navItem.getFragmentClass().newInstance();
Bundle args = navItem.getFragmentArgs();
if (args != null) {
fragment.setArguments(args);
}
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().replace(drawerContainerRes, fragment).commit();
// Highlight the selected item, update the title, and close the drawer
lvDrawer.setItemChecked(position, true);
setTitle(navItem.getTitle());
closeDrawer(lvDrawer);
}
public ActionBarDrawerToggle getDrawerToggle() {
return drawerToggle;
}
private FragmentActivity getActivity() {
return (FragmentActivity) getContext();
}
private ActionBar getSupportActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
private void setTitle(CharSequence title) {
getSupportActionBar().setTitle(title);
}
private class FragmentDrawerItemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectDrawerItem(position);
}
}
private class FragmentNavItem {
private Class<? extends Fragment> fragmentClass;
private String title;
private Bundle fragmentArgs;
public FragmentNavItem(String title, Class<? extends Fragment> fragmentClass) {
this(title, fragmentClass, null);
}
public FragmentNavItem(String title, Class<? extends Fragment> fragmentClass, Bundle args) {
this.fragmentClass = fragmentClass;
this.fragmentArgs = args;
this.title = title;
}
public Class<? extends Fragment> getFragmentClass() {
return fragmentClass;
}
public String getTitle() {
return title;
}
public Bundle getFragmentArgs() {
return fragmentArgs;
}
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(getActivity(), /* host Activity */
this, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
// setTitle(getCurrentTitle());
// call onPrepareOptionsMenu()
getActivity().supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
// setTitle("Navigate");
// call onPrepareOptionsMenu()
getActivity().supportInvalidateOptionsMenu();
}
};
}
public boolean isDrawerOpen() {
return isDrawerOpen(lvDrawer);
}
}
The issue is that you have not defined your layout: drawer_nav_item
#Override
public void onCreate(Bundle sIS){
super(sIS);
setContentView(R.layout.activity_main);
// Find our drawer view
dlDrawer = (FragmentNavigationDrawer) findViewById(R.id.drawer_layout);
// Setup drawer view
dlDrawer.setupDrawerConfiguration((ListView)findViewById(R.id.lvDrawer),
R.layout.drawer_nav_item, /* <- this layout has not been defined
in your layouts folder */
R.id.flContent);
...
}

Navigation Drawer Application crashes on API 10

Hi I am creating a sample navigation drawer app using ActionBarActivity . My problem is my application is running fine in Android 4.0+ but crashes on Android 2.3.3 even after adding the appropriate support libraries. Thanks in advance.
Error I am getting is [IMG]http://i57.tinypic.com/919kro.jpg[/IMG]
package com.example.navigationdrawerdemo;
import java.util.Locale;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
// actionBar = ((ActionBarActivity)getActivity()).getSupportActionBar();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getSupportActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.fragmentimage)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
Problem: my compiler was not showing that these android:attr/* are not supported in API level 10. I found a solution.
To support lower versions, instead of removing the following three parameters,
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:background="?android:attr/activatedBackgroundIndicator"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
You can actually replace them with equivalent values/resources.
The equivalent values can be obtained from https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/themes.xml
Now,
a) android:textAppearance="#android:style/TextAppearance.Medium"
b) Download a selector from https://github.com/habzy/Test0011_DialerPad/blob/master/res/drawable/list_item_activated_background.xml
In the above project browse the resources in hdpi,mdpi etc and get files named list_activated_holo.9.png
Finally
android:background="#drawable/activated_background_holo_dark"
c) From the equivalent values obtained , we know that listPreferredItemHeightSmall is 48dip
android:minHeight="48dip"

Altering what will appear on different fragments (Navigation Drawer)

I'm back on again. My last attempt at the Navigation Drawer failed, so I have started it with fragments (going much better this time). Anyways, I have got to the point where the fragments are loading etc, but I have no idea where it edits what appears in each fragment.
I was assuming there was a separate thing for each fragment, but I can't find it, if you guys can help that would be great.
So basically, my question is, how to tell the different fragments what to display? I have a feeling it is in the onCreateView method but I'm not sure..
Here's my code:
package com.example.android.navigationdrawerexample;
import java.util.Locale;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private DrawerLayout DrawerLayout;
private ListView DrawerList;
private ActionBarDrawerToggle DrawerToggle;
private CharSequence DrawerTitle;
private CharSequence Title;
private String[] pageArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Title = DrawerTitle = getTitle();
pageArray = getResources().getStringArray(R.array.pageArray);
DrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
DrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
DrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
DrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, pageArray));
DrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
DrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
DrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace standard image in action bar */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(Title);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(DrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
DrawerLayout.setDrawerListener(DrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = DrawerLayout.isDrawerOpen(DrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (DrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PageFragment();
Bundle args = new Bundle();
args.putInt(PageFragment.ARG_PAGE_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
DrawerList.setItemChecked(position, true);
setTitle(pageArray[position]);
DrawerLayout.closeDrawer(DrawerList);
}
#Override
public void setTitle(CharSequence title) {
Title = title;
getActionBar().setTitle(Title);
}
/**
* 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.
DrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
DrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PageFragment extends Fragment {
public static final String ARG_PAGE_NUMBER = "page_number";
public PageFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int pgNum = getArguments().getInt(ARG_PAGE_NUMBER);
String planet = getResources().getStringArray(R.array.pageArray)[pgNum];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
If you can help me out, that would be great :)
Look in your selectItem method, which is called whenever a tab is selected.
It currently creates a new PageFragment instance:
Fragment fragment = new PageFragment();
And then passes the ID of the selected item as an argument:
Bundle args = new Bundle();
args.putInt(PageFragment.ARG_PAGE_NUMBER, position);
fragment.setArguments(args);
That is to say, no matter which item is selected, PageFragment is instantiated, just with different arguments.
In PageFragment's onCreateView method, this argument is retrieved and used to determine which planet to display:
int pgNum = getArguments().getInt(ARG_PAGE_NUMBER);
String planet = getResources().getStringArray(R.array.pageArray)[pgNum];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
So, that is 'where it edits what appears in each fragment'.
If you want to display a different fragment for each item in the drawer (probably a fairly common use case) then I would use a switch statement:
private void selectItem(int position) {
Fragment fragment;
// Select a different fragment based on which tab has been selected
switch (position) {
case 0:
fragment = new TopDrawerItemFragment();
break;
case 1:
fragment = new SecondDrawerItemFragment();
break;
}
// Replace the fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mTabTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
TopDrawerItemFragment and SecondDrawerItemFragment could be inner classes (like PageFragment) or separate Java class files.
You're selectItem method is setting up your fragment views. The lines
Fragment fragment = new PageFragment();
Bundle args = new Bundle();
args.putInt(PageFragment.ARG_PAGE_NUMBER, position);
fragment.setArguments(args);
are creating the new fragment and setting its data where as the next 2 lines in the method
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
are changing the app's view to that of the fragment's (basically displaying that fragment). As for the fragment's view, the fragment'w own onCreateView method issetting up its view. Hopefully that helps

Categories

Resources