I have an error I am having trouble reproducing. I think it comes about when the app is being used then the user switches aps and of goes to the homescreen for awhile then comes back to my app. The full error is:
android.view.InflateException: Couldn't resolve menu item onClick handler
goToSearch in class android.view.ContextThemeWrapper
at android.view.MenuInflater$InflatedOnMenuItemClickListener
.<init>(MenuInflater.java:202)
at android.view.MenuInflater$MenuState.setItem(MenuInflater.java:402)
at android.view.MenuInflater$MenuState.addItem(MenuInflater.java:436)
at android.view.MenuInflater.parseMenu(MenuInflater.java:173)
at android.view.MenuInflater.inflate(MenuInflater.java:95)
at com.beerportfolio.beerportfoliopro.MainDrawer2.onCreateOptionsMenu(MainDrawer2.java:172)
at android.app.Activity.onCreatePanelMenu(Activity.java:2513)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:224)
at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:415)
at com.android.internal.policy.impl.PhoneWindow.invalidatePanelMenu(PhoneWindow.java:770)
at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:3179)
at android.os.Handler.handleCallback(Handler.java:608)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:5060)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(NativeStart.java)
Caused by: java.lang.NoSuchMethodException:
goToSearch [interface android.view.MenuItem]
at java.lang.Class.getConstructorOrMethod(Class.java:460)
at java.lang.Class.getMethod(Class.java:915)
at android.view.MenuInflater$InflatedOnMenuItemClickListener.<init>(MenuInflater.java:200)
at android.view.MenuInflater$MenuState.setItem(MenuInflater.java:402)
at android.view.MenuInflater$MenuState.addItem(MenuInflater.java:436)
at android.view.MenuInflater.parseMenu(MenuInflater.java:173)
at android.view.MenuInflater.inflate(MenuInflater.java:95)
at com.beerportfolio.beerportfoliopro.MainDrawer2.onCreateOptionsMenu(MainDrawer2.java:172)
at android.app.Activity.onCreatePanelMenu(Activity.java:2513)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:224)
at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:415)
at com.android.internal.policy.impl.PhoneWindow.invalidatePanelMenu(PhoneWindow.java:770)
at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:3179)
at android.os.Handler.handleCallback(Handler.java:608)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:5060)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(NativeStart.java)
My main drawer2 class looks like this:
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);
Crashlytics.start(this);
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);
}
}
public void setActionBarTitle(String title) {
getActionBar().setTitle(title);
}
#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);
if (mCurrentNavItem == null) {
}
else{
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);
}
}
//test to keep item not selected
int toClear=mDrawerList.getCheckedItemPosition();
if (toClear >= 0) {
mDrawerList.setItemChecked(toClear, 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();
}
public void scanBarcode(MenuItem item) {
//open scanner
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
public void onActivityResult(int requestCode,
int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator
.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
//todo: set scan content into setting,
//load new fragment which calls async task below. New
//todo: fragment will have same ui as search. :-)
Fragment Fragment_one;
FragmentManager man= this.getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new BarcodeFrag(scanContent);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
//tran.commit();
tran.commitAllowingStateLoss();
}
else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
Lastly my menu xml looks like this:
<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="always|collapseActionView"
android:onClick="goToSearch" />
<item android:id="#+id/action_scan"
android:icon="#drawable/barcode"
android:onClick="scanBarcode"
android:showAsAction="ifRoom|collapseActionView"/>
</menu>
I cannot for the life of me figure out where this error is coming from.
I would recommend using the onOptionsItemSelected mechanism if possible instead of manually wiring the click methods.
Take a look at the documentation:
Android Developer Guide:Menus
You might have found a platform bug. Does it still happen if you set your activity theme to Theme.Holo or Theme.Holo.Light? Specifically, try it with something that isn't based on Theme.Holo.Light.DarkActionBar.
If this fixes your original problem please report this at http://b.android.com.
You have wrong method signature.
This is yours
public void goToSearch(MenuItem item){
}
This is how it should be
public void goToSearch(View v){
}
please see
http://developer.android.com/reference/android/R.attr.html#onClick
for reference
Related
i try create app on fragment, but i have some error:
FATAL EXCEPTION: main Process: pl.pionas.zabawa, PID: 3074
java.lang.NullPointerException
at pl.pionas.zabawa.Fragments.HomeFragment.initializeListViewPromo(HomeFragment.java:77)
at pl.pionas.zabawa.Fragments.HomeFragment.OnTaskCompletedArticlesPromo(HomeFragment.java:71)
at pl.pionas.zabawa.AsyncTasks.ArticlesPromoAsyncTask$1.onResponse(ArticlesPromoAsyncTask.java:70)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
This error is when i change class fragment (example go to LoginFragment.class) and orientation.
My MainMenuActivity.class:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
private Fragment fragment = null;
private Boolean restore = false;
private String mTitle;
FragmentManager fragmentManager;
private Boolean action = false;
String tag = null;
private int prev;
private ArrayList<MenuFragment> mapMenu = new ArrayList<MenuFragment>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
if (savedInstanceState != null) {
fragment = fragmentManager.getFragment(savedInstanceState, "currentFragment");
restore = savedInstanceState.getBoolean("restore");
mTitle = savedInstanceState.getString("mTitle");
mapMenu = savedInstanceState.getParcelableArrayList("mapMenu");
tag = fragment.getTag();
} else {
fragment = new HomeFragment();
mapMenu.add(new MenuFragment(getString(R.string.app_name), 0));
restore = false;
mTitle = getString(R.string.app_name);
tag = mTitle;
}
if (fragment != null) {
fragmentManager.beginTransaction().replace(R.id.flContent, fragment, tag).addToBackStack(tag).commit();
if (restore) {
fragmentManager.findFragmentByTag(tag);
} else {
fragmentManager.beginTransaction().replace(R.id.flContent, fragment, tag).addToBackStack(tag).commit();
}
}
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(mTitle);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
View headerLayout = nvDrawer.inflateHeaderView(R.layout.nav_header);
// We can now look up items within the header if needed
ImageView ivHeaderPhoto = (ImageView) headerLayout.findViewById(R.id.imageView);
Drawable myDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.logo, null);
ivHeaderPhoto.setImageDrawable(myDrawable);
// Setup drawer view
setupDrawerContent(nvDrawer);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
// `onPostCreate` called when activity start-up is complete after `onStart()`
// NOTE! Make sure to override the method with only a single `Bundle` argument
#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 toggles
drawerToggle.onConfigurationChanged(newConfig);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
int menuId = menuItem.getItemId();
if (prev == menuId) {
mDrawer.closeDrawers();
return;
}
prev = menuId;
createNewFragment(menuId, true);
}
private void createNewFragment(int menuId, boolean add) { // Create a new fragment and specify the fragment to show based on nav item clicked
Class fragmentClass;
action = true;
int position = 0;
switch (menuId) {
case R.id.nav_login:
fragmentClass = LoginFragment.class;
mTitle = getString(R.string.menu_login);
position = 1;
break;
case R.id.nav_articles:
fragmentClass = CategoryFragment.class;
mTitle = getString(R.string.menu_articles);
position = 2;
break;
default:
fragmentClass = HomeFragment.class;
mTitle = APP_NAME;
break;
}
if (add) {
mapMenu.add(new MenuFragment(mTitle, menuId));
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
tag = mTitle;
if (action) {
// Insert the fragment by replacing any existing fragment
fragmentManager.beginTransaction().replace(R.id.flContent, fragment, tag).addToBackStack(tag).commit();
// Highlight the selected item has been done by NavigationView
nvDrawer.getMenu().getItem(position).setChecked(true);
}
// Set action bar title
getSupportActionBar().setTitle(mTitle);
// Close the navigation drawer
mDrawer.closeDrawers();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("restore", true);
outState.putParcelableArrayList("mapMenu", mapMenu);
outState.putString("mTitle", getSupportActionBar().getTitle().toString());
getSupportFragmentManager().putFragment(outState, "currentFragment", fragment);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
int i = mapMenu.size();
if (i > 1) {
mapMenu.remove(i - 1);
MenuFragment menuFragment = mapMenu.get((i - 2));
tag = menuFragment.getTitle();
createNewFragment(menuFragment.getMenuPosition(), false);
} else {
MainActivity.this.finish();
}
}
} }
My HomeFragment.class:
public class HomeFragment extends Fragment implements OnTaskCompletedArticlesLastAdded {
private ListView listViewLastAdded;
private ArrayList<Article> articleLastAddedList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArticlesLastAddedAsyncTask articlesLastAddedAsyncTask = new ArticlesLastAddedAsyncTask(getContext(), this);
articlesLastAddedAsyncTask.execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
listViewLastAdded = (ListView) rootView.findViewById(R.id.listViewLastAdded);
return rootView;
}
#Override
public void OnTaskCompletedArticlesLastAdded(ArrayList<Article> articleList) {
articleLastAddedList = articleList;
initializeListLastAdded();
}
private void initializeListLastAdded() {
ArticlesListAdapter adapter = new ArticlesListAdapter(getContext(), articleLastAddedList);
listViewLastAdded.setAdapter(adapter);
}
}
What i do wrong?
Thanks for help.
If you don't want Android to restart the activity when screen is rotated (this destroys your fragment and causes NULLPointer exception) you can add
android:configChanges="orientation|screenSize"
inside the activity tag in your Androidmanifest.xml
I'm writing an app for school and everything works fine when I run the app in the emulator.
The problem is when I connect my phone through usb and run the app on the phone.
Whenever I do something which requires the mListener (in any fragment in the whole app), I get a nullpointerexception on my mListener.
I have searched but have not found a solution or similar problem.
I have the problem in all of my fragments, but I will just show 1 fragment here:
Code of a fragment:
public class QuizFragment extends Fragment {
private OnFragmentQuizInteractionListener mListener;
List<Vraag> quesList;
int qid=0;
Vraag currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
Button butNext;
TextView txtResult;
Button btnToonAntwoord;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("Quiz");
final View view = inflater.inflate(R.layout.quiz_layout, container, false);
//btnStart = (Button) getActivity().findViewById(R.id.btnStart);
//btnStart.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// mListener.initQuiz();
// }
//});
//reset the score to 0
mListener.resetScore();
qid=0;
QuizDbHelper db=new QuizDbHelper(view.getContext());
quesList=db.getAllQuestions();
currentQ=quesList.get(qid);
txtQuestion=(TextView) view.findViewById(R.id.textView1);
rda=(RadioButton)view.findViewById(R.id.radio0);
rdb=(RadioButton)view.findViewById(R.id.radio1);
rdc=(RadioButton)view.findViewById(R.id.radio2);
//zet de radiobuttons klaar om geklikt te worden.
rda.setEnabled(true);
rdb.setEnabled(true);
rdc.setEnabled(true);
butNext=(Button)view.findViewById(R.id.btnNext);
btnToonAntwoord=(Button)view.findViewById(R.id.btnToonAntwoord);
txtResult = (TextView) view.findViewById(R.id.resultTextview);
setQuestionView(view);
setOnClickListeners(view);
return view;
}
private void setOnClickListeners(View v){
final View thisView = v;
butNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(qid<8){
//zet de radiobuttons klaar om geklikt te worden.
rda.setEnabled(true);
rdb.setEnabled(true);
rdc.setEnabled(true);
//zet het resultaat terug op niets
txtResult.setText("");
//Wanneer het goed is, voeg 1 bij de score bij
RadioGroup grp = (RadioGroup) thisView.findViewById(R.id.radioGroup1);
RadioButton answer = (RadioButton) thisView.findViewById(grp.getCheckedRadioButtonId());
if (currentQ.getANSWER().equals(checkChecked(answer.getId()))) {
mListener.incrementScore();
}
currentQ=quesList.get(qid);
setQuestionView(thisView);
}else{
//ga naar het eindscherm met het resultaat.
mListener.navigeerEindscore();
}
}
});
btnToonAntwoord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp = (RadioGroup) thisView.findViewById(R.id.radioGroup1);
RadioButton answer = (RadioButton) thisView.findViewById(grp.getCheckedRadioButtonId());
//toon de juiste boodschap aan de hand van het antwoord die gegeven is.
if (currentQ.getANSWER().equals(checkChecked(answer.getId()))) {
txtResult.setText(currentQ.getGoedeFeedback());
}else{
txtResult.setText(currentQ.getSlechteFeedback());
}
//zet de radiobuttons klaar om geklikt te worden.
rda.setEnabled(false);
rdb.setEnabled(false);
rdc.setEnabled(false);
}
});
}
private String checkChecked(int id) {
if(id == R.id.radio0){
return "A";
}else if(id == R.id.radio1){
return "B";
}else{
return "C";
}
}
private void setQuestionView(View v)
{
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
qid++;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentQuizInteractionListener) {
mListener = (OnFragmentQuizInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnResultFragmentInteractionListener");
}
}
public interface OnFragmentQuizInteractionListener {
void incrementScore();
void resetScore();
void navigeerEindscore();
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
mainActivity:
{
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,DashboardFragment.OnFragmentLoginInteractionListener,LoginFragment.OnFragmentLoginInteractionListener, RegistratieFragment.OnFragmentRegistratieInteractionListener,QuizFragment.OnFragmentQuizInteractionListener, ResultFragment.OnResultFragmentInteractionListener{
private FragmentManager fragmentManager;
public int quizScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_main);
quizScore = 0;
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(this);
String themeName = pref.getString("Theme1", "Blauw");
//toolbar ophalen
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Log.i("huidige preferences", themeName);
//toolbar instellen
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
/**if (themeName.equals("Blauw")) {
setTheme(R.style.AppTheme_blauw);
Log.i("MyActivity", "in blauw");
} else if (themeName.equals("Groen")) {
this.setTheme(R.style.AppTheme_groen);
Log.i("MyActivity", "in groen");
} else if (themeName.equals("Roze")) {
this.setTheme(R.style.AppTheme_roze);
Log.i("MyActivity", "in roze");
}**/
fragmentManager = getFragmentManager();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
fragmentManager.beginTransaction().replace(R.id.content_frame, new DashboardFragment()).commit();
}
//backknop werkt hoe hij moet werken
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
int count = getFragmentManager().getBackStackEntryCount();
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (count == 0) {
super.onBackPressed();
//additional code
} else {
getFragmentManager().popBackStack();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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.
switch (item.getItemId()) {
case R.id.action_settings:
fragmentManager.beginTransaction().replace(R.id.content_frame, new InstellingenFragment()).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
//region dashboard
public void MijnProfielClicked() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new MijnProfielFragment())
.addToBackStack("MijnProfiel")
.commit();
}
public void AlarmClicked() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new PilAlarmFragment())
.addToBackStack("Pilalarm")
.commit();
}
public void KalenderClicked() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new MenstruatieFragment())
.addToBackStack("Kalender")
.commit();
}
//endregion
//Navigatiemethodes LOGIN
public void Login() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new DashboardFragment())
.addToBackStack("Login")
.commit();
}
//Navigatiemethodes REGISTREREN
public void Registreer() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new DashboardFragment())
.addToBackStack("Registreer")
.commit();
}
public void Annuleren() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new LoginFragment())
.addToBackStack("Registreer")
.commit();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch (item.getItemId()) {
case R.id.nav_dashboard_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new DashboardFragment()).addToBackStack("dashboard").commit();
break;
case R.id.nav_mijnprofiel_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new MijnProfielFragment()).addToBackStack("mijnprofiel").commit();
break;
case R.id.nav_categorieen_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new CategorieenFragment()).addToBackStack("categorieen").commit();
break;
case R.id.nav_pilalarm_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new PilAlarmFragment()).addToBackStack("pilalarm").commit();
break;
case R.id.nav_menstruatie_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new MenstruatieFragment()).addToBackStack("menstruatie").commit();
break;
case R.id.nav_quiz_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new QuizFragment()).addToBackStack("quiz").commit();
break;
case R.id.nav_instellingen_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new InstellingenFragment()).addToBackStack("instellingen").commit();
break;
case R.id.nav_partners_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new PartnersFragment()).addToBackStack("partners").commit();
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//region Partner onclick listeners
public void onVivesPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.vives.be/");
}
public void onSensoaPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.sensoa.be/");
}
public void onUgentPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.ugent.be/");
}
public void onUCCVPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.ucvvgent.be/nl/");
}
public void onOnePartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.one.be//");
}
private void goToUrl(String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
//endregion
//region quizfragment
#Override
public void incrementScore() {
quizScore++;
}
#Override
public void resetScore() {
quizScore = 0;
}
#Override
public void navigeerEindscore() {
fragmentManager.beginTransaction().replace(R.id.content_frame, new ResultFragment()).commit();
}
#Override
public int getScore() {
return quizScore;
}
//endregion
The error I'm getting (doesn't matter what fragment, it's always nullpointerexception on the mlistener)
java.lang.NullPointerException: Attempt to invoke interface method 'void be.vives.pwo_kinderwens.Quiz.QuizFragment$OnFragmentQuizInteractionListener.resetScore()' on a null object reference
at be.vives.pwo_kinderwens.Quiz.QuizFragment.onCreateView(QuizFragment.java:55)
at android.app.Fragment.performCreateView(Fragment.java:2053)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:894)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.app.BackStackRecord.run(BackStackRecord.java:834)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:447)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
The problem is that your mListener is not implemented.
I would try the following:
I would add a method to QuizFragment like :
public void setFragmentQuizInteractionListener(OnFragmentQuizInteractionListener mListener)
{
this.mListener = mListener;
}
And then
case R.id.nav_quiz_layout:
QuizFragment quizFragment = new QuizFragment();
quizFragment.setFragmentQuizInteractionListener(this);
fragmentManager.beginTransaction().replace(R.id.content_frame, quizFragment ).addToBackStack("quiz").commit();
break;
And drop the onAttach() method.
Probably not the nicest way but worth a try.
You need to override
public void onAttach (Activity activity)
instead of
public void onAttach (Context context)
The latter was included in API level 23, so previous versions of Android will not call it.
See onAttach (Activity activity)
Use onAttach method in Fragment. Check Fragment Lifecycle
Context context;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}
I have implemented the material design navigation drawer. However when selecting a new activity the navigation drawer doesn't close smoothly. (I have tried various solutions and suggestions here on SO, but nothing actually helps me)
So I am hoping someone has found a solution to this?
Here is my MainActivity.class:
public class MainActivity extends ActionBarActivity
implements NavigationDrawerCallbacks {
private NavigationDrawerFragment mNavigationDrawerFragment;
private Toolbar mToolbar;
private boolean doubleBackToExitPressedOnce;
private ProgressDialog pd = null;
private Object data = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.fragment_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
// populate the navigation drawer
mNavigationDrawerFragment.setUserData("WELCOME", "", BitmapFactory.decodeResource(getResources(), R.drawable.ic_avatar));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FragmentHome();
break;
case 1:
fragment = new FragmentSecondActivity();
break;
case 2:
fragment = new FragmentThirdActivity();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).commit();
}
}
#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.main, menu);
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);
}
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please press BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}
NavigationDrawerFragment:
public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks {
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 mActionBarDrawerToggle;
private DrawerLayout mDrawerLayout;
private RecyclerView mDrawerList;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
#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;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavigationItem> navigationItems = getMenu();
NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition);
return view;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public ActionBarDrawerToggle getActionBarDrawerToggle() {
return mActionBarDrawerToggle;
}
public DrawerLayout getDrawerLayout() {
return mDrawerLayout;
}
#Override
public void onNavigationDrawerItemSelected(int position) {
selectItem(position);
}
public List<NavigationItem> getMenu() {
List<NavigationItem> items = new ArrayList<NavigationItem>();
items.add(new NavigationItem("Home", getResources().getDrawable(R.drawable.ic_home)));
items.add(new NavigationItem("Second Activity", getResources().getDrawable(R.drawable.ic_icon)));
items.add(new NavigationItem("Third Activity", getResources().getDrawable(R.drawable.ic_icon)));
return items;
}
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.myPrimaryDarkColor));
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#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);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mActionBarDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
}
public void openDrawer() {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
public void closeDrawer() {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
#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.
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
public void setUserData(String user, String email, Bitmap avatar) {
ImageView avatarContainer = (ImageView) mFragmentContainerView.findViewById(R.id.imgAvatar);
((TextView) mFragmentContainerView.findViewById(R.id.txtUserEmail)).setText(email);
((TextView) mFragmentContainerView.findViewById(R.id.txtUsername)).setText(user);
avatarContainer.setImageDrawable(new RoundImage(avatar));
}
public View getGoogleDrawer() {
return mFragmentContainerView.findViewById(R.id.googleDrawer);
}
public static class RoundImage extends Drawable {
private final Bitmap mBitmap;
private final Paint mPaint;
private final RectF mRectF;
private final int mBitmapWidth;
private final int mBitmapHeight;
public RoundImage(Bitmap bitmap) {
mBitmap = bitmap;
mRectF = new RectF();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint.setShader(shader);
mBitmapWidth = mBitmap.getWidth();
mBitmapHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
canvas.drawOval(mRectF, mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRectF.set(bounds);
}
#Override
public void setAlpha(int alpha) {
if (mPaint.getAlpha() != alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
}
#Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
#Override
public int getIntrinsicWidth() {
return mBitmapWidth;
}
#Override
public int getIntrinsicHeight() {
return mBitmapHeight;
}
public void setAntiAlias(boolean aa) {
mPaint.setAntiAlias(aa);
invalidateSelf();
}
#Override
public void setFilterBitmap(boolean filter) {
mPaint.setFilterBitmap(filter);
invalidateSelf();
}
#Override
public void setDither(boolean dither) {
mPaint.setDither(dither);
invalidateSelf();
}
public Bitmap getBitmap() {
return mBitmap;
}
}
}
What can I do to make closing the navigation drawer close smoothly? At the moment it closes halfway then stops for a second then closes and the new activity is shown.
add the below method before calling another class on navigation drawer item click i.e. in onnavigationdrawerselected method
mNavigationDrawerFragment.closeDrawers();
This will close the navigation drawer..
close your drawer first.
after 200ms, open your new activity
USE A THREAD TO CLOSE THE DRAWER THAT CAN IMPROVE SOME CASES
new Handler().post(new Runnable() {
#Override
public void run() {
drawerLayout.closeDrawers();
}
});
I've implemented ActionBarDrawerToggle for NavigationDrawer and also used ActionBar.
How can I handle both click events because both require onOptionsItemSelected(MenuItem item) method?
Is there any other way around?
public class A1 extends AppCompatActivity implements OnItemClickListener {
String[] menu;
DrawerLayout dLayout;
ListView dList;
ArrayAdapter < String > adapter;
ActionBarDrawerToggle drawListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a1);
menu = new String[] {
"Home", "Android", "Windows", "Linux", "Raspberry Pi", "WordPress", "Videos", "Contact Us"
};
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
dList = (ListView) findViewById(R.id.left_drawer);
adapter = new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1, menu);
dList.setAdapter(adapter);
dList.setOnItemClickListener(this);
dList.setSelector(android.R.color.holo_blue_dark);
drawListener = new ActionBarDrawerToggle(this, dLayout, R.drawable.ic_draw, R.string.dopen) {
#Override
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Menu");
}
#Override
public void onDrawerClosed(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerClosed(drawerView);
}
};
dLayout.setDrawerListener(drawListener);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public boolean onCreateOptionsMenu(Menu menu) //for actionbar
{
getMenuInflater().inflate(R.menu.actionbar, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.copy:
return showToast("Copy");
default:
return false;
}
// if(drawListener.onOptionsItemSelected(item))
// {
// return true;
// }
// return super.onOptionsItemSelected(item);
}
public boolean showToast(String message) {
Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show();
return true;
}
#Override
public void onConfigurationChanged(android.content.res.Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawListener.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawListener.syncState();
}
#Override
public void onItemClick(AdapterView <? > arg0, View v, int position, long id) {
selectitem(position);
dLayout.closeDrawers();
Bundle args = new Bundle();
args.putString("Menu", menu[position]);
Fragment detail = new DetailFragment();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, detail).commit();
}
public void selectitem(int position) {
dList.setItemChecked(position, true);
setTitle(menu[position]);
}
public void setTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
I see you're using the latest AppCompat and stuff. Then why complicate the drawer?
Please go through this. You can make a drawer VERY quickly and easily, handle its open and close quite neatly. You don't even need the ActionBarDrawerToggle.
Cheers.
I am currently trying to implement the new NavigationDrawer as per the Google IO 2013 guidelines. I am using ActionbarSherlock. The code is working well. The only issue is that I am not able to toggle the "up" caret next to my app icon when the navigation drawer is pulled out. I am pasting my entire code below. Kindly help.
public class MainActivity extends SherlockFragmentActivity {
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.drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
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();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu();
}
};
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
new Thread(new Runnable() {
#Override
public void run() {
prefs = getPreferences(MODE_PRIVATE);
opened = prefs.getBoolean(OPENED_KEY, false);
if(opened == false)
{
mDrawerLayout.openDrawer(mDrawerList);
}
}
}).start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(getMenuItem(item))) {
return true;
}
switch (item.getItemId()) {
case R.id.action_websearch:
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getSupportActionBar().getTitle());
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);
}
}
private android.view.MenuItem getMenuItem(final MenuItem item) {
return new android.view.MenuItem() {
#Override
public int getItemId() {
return item.getItemId();
}
public boolean isEnabled() {
return true;
}
#Override
public boolean collapseActionView() {
return false;
}
#Override
public boolean expandActionView() {
return false;
}
#Override
public ActionProvider getActionProvider() {
return null;
}
#Override
public View getActionView() {
return null;
}
#Override
public char getAlphabeticShortcut() {
return 0;
}
#Override
public int getGroupId() {
return 0;
}
#Override
public Drawable getIcon() {
return null;
}
#Override
public Intent getIntent() {
return null;
}
#Override
public ContextMenuInfo getMenuInfo() {
return null;
}
#Override
public char getNumericShortcut() {
return 0;
}
#Override
public int getOrder() {
return 0;
}
#Override
public SubMenu getSubMenu() {
return null;
}
#Override
public CharSequence getTitle() {
return null;
}
#Override
public CharSequence getTitleCondensed() {
return null;
}
#Override
public boolean hasSubMenu() {
return false;
}
#Override
public boolean isActionViewExpanded() {
return false;
}
#Override
public boolean isCheckable() {
return false;
}
#Override
public boolean isChecked() {
return false;
}
#Override
public boolean isVisible() {
return false;
}
#Override
public android.view.MenuItem setActionProvider(ActionProvider actionProvider) {
return null;
}
#Override
public android.view.MenuItem setActionView(View view) {
return null;
}
#Override
public android.view.MenuItem setActionView(int resId) {
return null;
}
#Override
public android.view.MenuItem setAlphabeticShortcut(char alphaChar) {
return null;
}
#Override
public android.view.MenuItem setCheckable(boolean checkable) {
return null;
}
#Override
public android.view.MenuItem setChecked(boolean checked) {
return null;
}
#Override
public android.view.MenuItem setEnabled(boolean enabled) {
return null;
}
#Override
public android.view.MenuItem setIcon(Drawable icon) {
return null;
}
#Override
public android.view.MenuItem setIcon(int iconRes) {
return null;
}
#Override
public android.view.MenuItem setIntent(Intent intent) {
return null;
}
#Override
public android.view.MenuItem setNumericShortcut(char numericChar) {
return null;
}
#Override
public android.view.MenuItem setOnActionExpandListener(OnActionExpandListener listener) {
return null;
}
#Override
public android.view.MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) {
return null;
}
#Override
public android.view.MenuItem setShortcut(char numericChar, char alphaChar) {
return null;
}
#Override
public void setShowAsAction(int actionEnum) {
}
#Override
public android.view.MenuItem setShowAsActionFlags(int actionEnum) {
return null;
}
#Override
public android.view.MenuItem setTitle(CharSequence title) {
return null;
}
#Override
public android.view.MenuItem setTitle(int title) {
return null;
}
#Override
public android.view.MenuItem setTitleCondensed(CharSequence title) {
return null;
}
#Override
public android.view.MenuItem setVisible(boolean visible) {
return null;
}
};
}
/* 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 SherlockFragment {
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];
// change int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()), "drawable", getActivity().getPackageName());
int imageId = getResources().getIdentifier("tempmap", "drawable", getActivity().getPackageName());
// change ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
// change getActivity().setTitle(planet);
getActivity().setTitle("MapView");
return rootView;
}
}
}
If you don't need the 3 lines to move (like in gmail app), you could just add:
<item name="homeAsUpIndicator">#drawable/ic_drawer</item>
<item name="android:homeAsUpIndicator">#drawable/ic_drawer</item>
in your activity's theme. I prefer this to using yet another library in my app.
ic_drawer can be downloaded from here:
http://developer.android.com/training/implementing-navigation/nav-drawer.html
try to call syncState on the toggle drawer like this:
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
//your ActionBarDrawerToggle is below
mDrawerToggle.syncState();
}
or just right after you instantiate it.
I had the same problem and did some research on that topic. It does not seem to be easy to get the caret working correctly on older SDKs. Long story short, there's a guy who has a running example implementation that's based on reflection:
https://github.com/nicolasjafelle/SherlockNavigationDrawer
I tested it and it works perfectly for me, even on Android 2.x !
I have the caret removed in 4.x devices, but not for 2.x devices. The repository is here if you need it:
https://github.com/bcrider/NavigationDrawerSherlocked
It's simply the sample that Google supplied that I modified using ActionBarSherlock as you have done as well. I fixed an issue with a method (onOptionsItemSelected) in the sample that originally prevented the tapped icon from doing anything after ActionBarSherlock was integrated into the app.
Hope this helps!