Im trying to use drawer toggle in an action bar with sherlock. This is my main activity:
import uk.co.senab.actionbarpulltorefresh.extras.actionbarsherlock.PullToRefreshAttacher;
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.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.mejorandroid.ejemplo3_clase3.fragments.MainFragment;
import com.mejorandroid.ejemplo3_clase3.fragments.TermsFragment;
public class MainActivity extends SherlockFragmentActivity
implements OnItemClickListener{
private ListView drawer_list;
private DrawerLayout drawer_layout;
private ActionBarDrawerToggle drawer_toggle;
private PullToRefreshAttacher pullToRefreshAttacher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pullToRefreshAttacher = PullToRefreshAttacher.get(this);
drawer_list = (ListView) findViewById(R.id.left_drawer);
drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
ArrayAdapter<String> drawer_adapter = new ArrayAdapter<String>(this,
R.layout.drawer_list_item, getResources().getStringArray(
R.array.array_drawer_options));
drawer_list.setAdapter(drawer_adapter);
drawer_list.setOnItemClickListener(this);
selectItem(0);
drawer_toggle = new ActionBarDrawerToggle(this, drawer_layout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close){
#Override
public void onDrawerClosed(View drawerView) {
supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
supportInvalidateOptionsMenu();
}
};
drawer_layout.setDrawerListener(drawer_toggle);
getSherlock().getActionBar().setDisplayHomeAsUpEnabled(true);
getSherlock().getActionBar().setHomeButtonEnabled(true);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawer_toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawer_toggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home || drawer_toggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
public PullToRefreshAttacher getAttacher() {
return pullToRefreshAttacher;
}
public void selectItem(int position){
Fragment f;
if(position==0){
f = new MainFragment();
}else{
f = new TermsFragment();
}
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.replace(R.id.main_content, f)
.commit();
drawer_list.setItemChecked(position, true);
setTitle(drawer_list.getItemAtPosition(position).toString());
drawer_layout.closeDrawer(drawer_list);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
selectItem(position);
}
}
In the method onOptionsItemSelected:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home || drawer_toggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
I get:
How can I fix this??
This is my main.xml:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
I had the same problem and this works for me:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (drawer_layout.isDrawerOpen(drawer_list)) {
drawer_layout.closeDrawer(drawer_list);
} else {
drawer_layout.openDrawer(drawer_list);
}
}
return super.onOptionsItemSelected(item);
}
I don't know if this problem is already fixed in the newest release of the Sherlock library / support library, but the workaround does a good job.
Related
How do i add items on navigation drawer from List<String> minerals = new ArrayList<String>();? is this possible?
navigation view
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/activity_navigation_drawer">
</android.support.design.widget.NavigationView>
main_acitivity.java
package xxxxxxxx;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class loginhome extends AppCompatActivity {
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginhome);
Toolbar topToolBar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(topToolBar);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() {
String[] osArray = { "Android", "iOS", "Windows", "OS X", "Linux" };
mAdapter = new ArrayAdapter<String>(this, R.layout.drawer_items,R.id.label ,osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(loginhome.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#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 onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_help) {
Toast.makeText(loginhome.this, "setting", Toast.LENGTH_LONG).show();
}
if(id == R.id.action_place){
Toast.makeText(loginhome.this, "Refresh App", Toast.LENGTH_LONG).show();
}
if(id == R.id.action_search){
Toast.makeText(loginhome.this, "Create Text", Toast.LENGTH_LONG).show();
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
drawer_items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="30sp"
android:background="#D3D3D3">
</TextView>
</LinearLayout>
My app basicly contains two activities, a main-activity and a settings-activity.
Settings-activity is launched by
Intent launchNewIntent = new Intent(MainActivity.this,SettingsActivity.class);
startActivityForResult(launchNewIntent, 0);
, which contains some fragments. I use the up navigation, which works perfectly in settings-activity between the fragments, but however I don't return to my main-activity when pressing the back button. The setDisplayHomeAsUpEnabled command is in my settings-activity, bc it didn't helped to solve my problem when I positioned it in my main-activity.
In my manifest I've declared main-activity as the parent activity for settings-activity.
So what do I have to do? - lot's of thanks!
My Mainactivity
package user.example;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent launchNewIntent = new Intent(MainActivity.this,SettingsActivity.class);
startActivityForResult(launchNewIntent, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
}
My SettingsActivity: (I've left out the fragments, but the same error is reproduced)
package user.example;
import android.support.v7.app.ActionBar;
public class SettingsActivity extends AppCompatPreferenceActivity {
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
AppCompatPreferenceActivity: (started by Settings.activity)
package user.example;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
public abstract class AppCompatPreferenceActivity extends PreferenceActivity {
private AppCompatDelegate mDelegate;
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
public void setSupportActionBar(#Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
#Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
#Override
public void setContentView(#LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
#Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
#Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
#Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
#Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
#Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
#Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
}
I figured out that I had to put this code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
into my AppCompatPreferenceActivity.java, now everything wokrs, thanks for all help so far!!! :)
I think you need to set the "main Activity" as the Parent Activity to "Settings Activity" in the Mainfest like that
<activity android:name=".SettingActivity"
android:parentActivityName=".MainActivity"></activity>
Edit
You neeed to add in the Setting Activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
I am making an application in Android for use with Cardboard.
At the moment I have implemented a menu that extends Activity in MainActivity and a code that activates the camera for a Cardboard (extending from CardboardActivity). My problem is when the menu selected the option in which launched this code. How I can throw a CardboardActivity within an Activity?
Sorry for my English. :(
This is the code:
package com.example.dbg.CamaraCV;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.google.vrtoolkit.cardboard.CardboardActivity;
public class MainActivity extends AppCompatActivity {
private Toolbar appbar;
private DrawerLayout drawerLayout;
private NavigationView navView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.dbg.CamaraCV.R.layout.activity_main);
appbar = (Toolbar)findViewById(com.example.dbg.CamaraCV.R.id.appbar);
setSupportActionBar(appbar);
getSupportActionBar().setHomeAsUpIndicator(com.example.dbg.CamaraCV.R.drawable.ic_nav_menu);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout = (DrawerLayout)findViewById(com.example.dbg.CamaraCV.R.id.drawer_layout);
/*
//Eventos del Drawer Layout
drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(View drawerView) {
}
#Override
public void onDrawerClosed(View drawerView) {
}
#Override
public void onDrawerStateChanged(int newState) {
}
});
*/
navView = (NavigationView)findViewById(com.example.dbg.CamaraCV.R.id.navview);
navView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
boolean fragmentTransaction = false;
Fragment fragment = null;
CardboardActivity CardboardActivity =null;
switch (menuItem.getItemId()) {
case com.example.dbg.CamaraCV.R.id.menu_seccion_0:
fragment = new Fragment0();
fragmentTransaction = true;
break;
case com.example.dbg.CamaraCV.R.id.menu_seccion_1:
startActivity(new Intent(MainActivity.this, CamaraCardBoard.class));
break;
case com.example.dbg.CamaraCV.R.id.menu_seccion_2:
fragment = new Fragment2();
fragmentTransaction = true;
break;
case com.example.dbg.CamaraCV.R.id.menu_seccion_3:
fragment = new Fragment3();
fragmentTransaction = true;
break;
}
if(fragmentTransaction) {
getSupportFragmentManager().beginTransaction()
.replace(com.example.dbg.CamaraCV.R.id.content_frame, fragment)
.commit();
menuItem.setChecked(true);
getSupportActionBar().setTitle(menuItem.getTitle());
}
drawerLayout.closeDrawers();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(com.example.dbg.CamaraCV.R.menu.menu_navview, 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 android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
I'm trying to create a navigation drawer. I have created it but the problem is that when i open the app the first time, the fragment is displayed in the content area but it is not highlighted in the navigation drawer.
This is code i'm using:
package com.hfad.evenit;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.hfad.evenit.Fragments.FourthFragment;
import com.hfad.evenit.Fragments.SecondFragment;
import com.hfad.evenit.Fragments.ThirdFragment;
import com.hfad.evenit.Fragments.TopFragment;
public class Home extends AppCompatActivity {
String []FragmentTitles;
ListView DrawerList;
DrawerLayout drawerLayout;
ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
FragmentTitles = getResources().getStringArray(R.array.fragment_titles);
DrawerList = (ListView) findViewById(R.id.drawer);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
DrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1, FragmentTitles));
DrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
selectItem(0);
DrawerList.setSelection(0);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open_drawer, R.string.close_drawer) {
#Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = drawerLayout.isDrawerOpen(DrawerList);
menu.findItem(R.id.action_share).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_home, 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.
if(drawerToggle.onOptionsItemSelected(item))
{
return true;
}
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void selectItem(int position)
{
Fragment fragment;
switch(position)
{
case 0:
fragment = new TopFragment();
break;
case 1:
fragment = new SecondFragment();
break;
case 2:
fragment = new ThirdFragment();
break;
case 3:
fragment = new FourthFragment();
break;
default:
fragment = new TopFragment();
}
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
setActionBarTitle(position);
drawerLayout.closeDrawer(DrawerList);
}
public void setActionBarTitle(int position)
{
String title;
title = FragmentTitles[position];
getSupportActionBar().setTitle(title);
}
}
The method you should use for changing the items state to "highlighted" or currently activated is setItemChecked(int position, boolean value). It's best to place it in your selectItem method so that the "highlighted" item changes once your SelectItem method is called.
You might also want to consider setting the listView's choice mode to CHOICE_MODE_SINGLE so that only one item can be in an active state at a given time.
drawerList.setChoiceMode(CHOICE_MODE_SINGLE);
Around here...
public void selectItem(int position) {
...
setActionBarTitle(position);
drawerLayout.closeDrawer(DrawerList);
}
Adding DrawerList.setItemChecked(position, true); may work.
public void selectItem(int position) {
...
setActionBarTitle(position);
DrawerList.setItemChecked(position, true); // <== add this line
drawerLayout.closeDrawer(DrawerList);
}
Actually I'm not using Navigation Drawer of the Android Studio's project template but using NavigationView (it is recommended for ease to use), recently. If my answer is invalid, please forget this.
I started writing an app for Android. I have a problem with the Animation of the NavigationDrawer icon at the top left. It works correctly when the application is launched for the first time but when I pick an item from the list in the NavgationDrawer its icon stays in the "open" state even though the `NavigationDrawer closes as it should.
Here is my MainActivity:
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.app.ActionBar;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.content.res.*;
public class MainActivity extends FragmentActivity {
ActionBarDrawerToggle icon;
final String[] listContent ={"Accueil","Fiche technique","Pilotes","Ecuries"};
final String[] fragments ={
"com.mycompany.f1holo.MainPageFragment",
"com.mycompany.f1holo.FirstFragment",
"com.mycompany.f1holo.SecondFragment",
"com.mycompany.f1holo.ThirdFragment"};
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayAdapter<String> ad = new ArrayAdapter<String>(getActionBar().getThemedContext(), android.R.layout.simple_list_item_1, listContent);
final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
final ListView list = (ListView) findViewById(R.id.drawer);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this,
drawer,
R.drawable.navdrawer,
R.string.open,
R.string.close);
drawer.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
list.setAdapter(ad);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, final int position, long id) {
drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
#Override
public void onDrawerClosed(View drawerView){
super.onDrawerClosed(drawerView);
FragmentTransaction transition = getSupportFragmentManager().beginTransaction();
transition.replace(R.id.mains, Fragment.instantiate(MainActivity.this, fragments[position]));
transition.commit();
}
});
drawer.closeDrawer(list);
}
});
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId())
{
case R.id.mainMenuAbout:
Toast.makeText(this, "F1 Holo", Toast.LENGTH_SHORT).show();
return true;
case R.id.mainMenuQuitter:
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
getMenuInflater().inflate(R.menu.main_about, menu);
return true;
}
}
And here is my FirstFragment:
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FirstFragment extends Fragment {
public static Fragment newInstance(Context context) {
FirstFragment frag = new FirstFragment();
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.first_fragment_layout, null);
return root;
}
}
I have found the solution and it is so obvious I could kick myself for not noticing before...
The problem is here:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, final int position, long id) {
drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
FragmentTransaction transition = getSupportFragmentManager().beginTransaction();
transition.replace(R.id.mains, Fragment.instantiate(MainActivity.this, fragments[position]));
transition.commit();
}
});
drawer.closeDrawer(list);
}
});
In this OnClickListener you are setting a new SimpleDrawerListener and therefore overriding this line:
drawer.setDrawerListener(actionBarDrawerToggle);
This disconnects the ActionBarDrawerToogle from the DrawerLayout and as a result stops the animations from playing... This is all you need:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, final int position, long id) {
FragmentTransaction transition = getSupportFragmentManager().beginTransaction();
transition.replace(R.id.mains, Fragment.instantiate(MainActivity.this, fragments[position]));
transition.commit();
drawer.closeDrawer(list);
}
});
Why would you want to do this anyway? It just causes a delay between the user picking the item and the content actually changing. If it is because of performance issues - maybe that the close animation of the NavigationDrawer is not playing correctly - then doing something like this might be appropriate but in any case if you decide to implement this do it like this:
First create global variable called drawerItemSelection:
private String drawerItemSelection = null;
And then implement your ItemClickListener like this:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, final int position, long id) {
drawerItemSelection = fragments[position];
drawer.closeDrawer(list);
}
});
And finally in your onCreate() method implement the ActionBarDrawerToogle like this:
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, R.drawable.navdrawer, R.string.open, R.string.close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if(drawerItemSelection != null) {
FragmentTransaction transition = getSupportFragmentManager().beginTransaction();
transition.replace(R.id.mains, Fragment.instantiate(MainActivity.this, drawerItemSelection));
transition.commit();
drawerItemSelection = null;
}
}
};
If you have any further questions feel free to ask!