I created an app with Navigation Drawer
in BaseActivity
. Everything works ok except the change of title in the Action Bar
. the title changes for a second but when opening the new activity is shown the original title.
我在BaseActivity中创建了一个带有Navigation Drawer的应用程序。除了Action Bar中的标题更改外,一切正常。标题会更改一秒,但在打开新活动时会显示原始标题。
What can be the error? thanks
可能是什么错误?谢谢
BaseActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PerfilAdapter.iniciarBaseDatos(this);
perfilObj = PerfilAdapter.selectPerfil(1);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
cargarActionBar();
cargarDrawerLayout(savedInstanceState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.menuOpcSonidos:
...
return true;
case R.id.menuOpcCambiarColor:
...
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.menuOpcSonidos)
.setTitle(getResources().getString(R.string.sonidoOnOff) + " " + perfilObj.getSonidos());
return super.onPrepareOptionsMenu(menu);
}
private void cargarActionBar() {
ActionBar actionBar = getActionBar();
int[] colores2 = Modulo.cargarColoresDrawerlayout(perfilObj.getColor());
actionBar.setBackgroundDrawable(new GradientDrawable(Orientation.BOTTOM_TOP, colores2));
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
int titleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
TextView textoTitulo = (TextView)findViewById(titleId);
textoTitulo.setTextColor(getResources().getColor(R.color.blanco));
textoTitulo.setTypeface(null, Typeface.BOLD);
textoTitulo.setTextSize(19);
textoTitulo.setShadowLayer(5, 0, 0, getResources().getColor(R.color.negro));
}
private void cargarDrawerLayout(Bundle b) {
mTitle = mDrawerTitle = getTitle();
textosMenuLateral = getResources().getStringArray(R.array.nav_drawer_items);
iconosMenuLateral1 = getResources()
.obtainTypedArray(R.array.iconos_menu_lateral1);
iconosMenuLateral2 = getResources()
.obtainTypedArray(R.array.iconos_menu_lateral2);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenuMain);
int[] colores = {0, 0xFFFFFFFF, 0};
mDrawerList.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colores));
mDrawerList.setDividerHeight(4);
navDrawerItems1 = new ArrayList<DrawerItem>();
navDrawerItems1.add(new DrawerItem(textosMenuLateral[0], iconosMenuLateral1.getResourceId(0, -1)));
navDrawerItems1.add(new DrawerItem(textosMenuLateral[1], iconosMenuLateral1.getResourceId(1, -1)));
navDrawerItems1.add(new DrawerItem(textosMenuLateral[2], iconosMenuLateral1.getResourceId(2, -1)));
navDrawerItems1.add(new DrawerItem(textosMenuLateral[3], iconosMenuLateral1.getResourceId(3, -1)));
navDrawerItems1.add(new DrawerItem(textosMenuLateral[4], iconosMenuLateral1.getResourceId(4, -1)));
navDrawerItems2 = new ArrayList<DrawerItem>();
navDrawerItems2.add(new DrawerItem(textosMenuLateral[0], iconosMenuLateral2.getResourceId(0, -1)));
navDrawerItems2.add(new DrawerItem(textosMenuLateral[1], iconosMenuLateral2.getResourceId(1, -1)));
navDrawerItems2.add(new DrawerItem(textosMenuLateral[2], iconosMenuLateral2.getResourceId(2, -1)));
navDrawerItems2.add(new DrawerItem(textosMenuLateral[3], iconosMenuLateral2.getResourceId(3, -1)));
navDrawerItems2.add(new DrawerItem(textosMenuLateral[4], iconosMenuLateral2.getResourceId(4, -1)));
iconosMenuLateral1.recycle();
iconosMenuLateral2.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
adapter = new DrawerListAdapter(getApplicationContext(),
navDrawerItems1,
navDrawerItems2,
perfilObj.getColor(),
pos);
mDrawerList.setAdapter(adapter);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.drawable.icono_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 (b == null) {
opcionesPanelLateral(0);
}
}
private class SlideMenuClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView textView = (TextView) view.findViewById(R.id.title);
textView.setTypeface(null, Typeface.BOLD);
opcionesPanelLateral(position);
}
}
private void opcionesPanelLateral(int position) {
Intent i;
switch (position) {
case 0:
pos = 0;
break;
case 1:
i = new Intent(this, ActivitySecond.class);
mDrawerLayout.closeDrawer(mDrawerList);
startActivity(i);
pos = 1;
break;
case 2:
i = new Intent(this, ActivityThird.class);
mDrawerLayout.closeDrawer(mDrawerList);
startActivity(i);
pos = 2;
break;
case 3:
i = new Intent(this, ActivityFourth.class);
mDrawerLayout.closeDrawer(mDrawerList);
startActivity(i);
pos = 3;
break;
case 4:
break;
default:
break;
}
mDrawerList.setItemChecked(pos, true);
mDrawerList.setSelection(pos);
setTitle(textosMenuLateral[pos]);
mDrawerLayout.closeDrawer(mDrawerList);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
cargarActionBar();
cargarDrawerLayout(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void onBackPressed() {
mDrawerLayout.closeDrawer(mDrawerList);
}
I think that error is the use the Activities... but I don't know as fix
我认为错误是使用活动...但我不知道修复
1 个解决方案
#1
1
Android Studio allows to add a navigation drawer to the app through File | New | Activity. This "ready-made" navigation drawer comes with everything you need: properties, methods, events, etc.
Android Studio允许通过File |将导航抽屉添加到应用程序新的|活动。这个“现成的”导航抽屉带有您需要的一切:属性,方法,事件等。
Next steps to change titles for different fragments are intended to use with the ready-made navigation drawer of Android Studio, but they might be helpful to anyothers:
更改不同片段的标题的后续步骤旨在与Android Studio的现成导航抽屉一起使用,但它们可能对任何人都有帮助:
-
The navigation drawer has several files : one activity, and one or more fragments. Open the java activity file of your navigation drawer (what you call "Base Activity").
导航抽屉有几个文件:一个活动和一个或多个片段。打开导航抽屉的java活动文件(您称之为“基本活动”)。
-
Find method onCreate.
查找onCreate方法。
-
In this method, add the line mTitle = "???", where "???" is the title of the first fragment that will me shown as soon as the navigation drawer screen appears.
在这个方法中,添加行mTitle =“???”,其中“???”是导航抽屉屏幕出现后我将显示的第一个片段的标题。
-
Now find method onNavigationDrawerItemSelected. CHARLIE, I'm not sure, but I believe you have it under the name opcionesPanelLateral.
现在找到onNavigationDrawerItemSelected的方法。查理,我不确定,但我相信你的名字是opcionesPanelLateral。
-
In this method you have a switch. This switch opens the appropiate fragment depending on the selected option. To set the title for each fragment, go to each case in the switch an add the line mTitle = "My title"; before frg = new my_frag();. This way, when the fragment opens it will show the appropiate title.
在这种方法中你有一个开关。此开关根据所选选项打开适当的片段。要设置每个片段的标题,请转到开关中的每个案例,添加行mTitle =“我的标题”;在frg = new my_frag();之前。这样,当片段打开时,它将显示适当的标题。
-
Find method restoreActionBar. CHARLIE, I don't see it in your code nor any equivalent method. Add it. Inside of it, add the line actionBar.setTitle( mTitle);, and here is where the title is actually set (maybe that's why your title disappears). Call this method inside onCreateOptionsMenu (after inflate).
查找方法restoreActionBar。查理,我在你的代码中没有看到它,也没有任何等效的方法。添加它。在其中,添加行actionBar.setTitle(mTitle);,这里是标题实际设置的地方(也许这就是你的标题消失的原因)。在onCreateOptionsMenu中调用此方法(在inflate之后)。
That's it. I'm using hard-coded strings, if you follow Android rules, use strings.xml.
而已。我正在使用硬编码字符串,如果您遵循Android规则,请使用strings.xml。
Now a real life example from and app I'm working on right now. Next is the raw code of my "BaseActivity" of the ready-made navigation drawer (some things are in spanish because I'm costarrican):
现在是我正在努力的现实生活中的一个例子。接下来是现成导航抽屉的“BaseActivity”的原始代码(有些东西是西班牙语,因为我是costarrican):
package my_package;
//------------------------------------------------------------------------------
import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
//------------------------------------------------------------------------------
public class menu_act extends ActionBarActivity
implements drawer_frg.NavigationDrawerCallbacks {
//------------------------------------------------------------------------------
// Fragment managing the behaviors, interactions and presentation of the navigation drawer.
private drawer_frg 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.menu_lay );
mNavigationDrawerFragment = (drawer_frg) getSupportFragmentManager().findFragmentById(
R.id.navigation_drawer );
mTitle = "Perfil"; // getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp( R.id.navigation_drawer,( DrawerLayout )
findViewById( R.id.drawer_layout ) );
// BARRA DE TÍTULO ANARANJADA.
//ActionBar actionBar = getSupportActionBar();
//actionBar.setBackgroundDrawable( new ColorDrawable( getResources().getColor( R.color.col_nar ) ) );
}
//------------------------------------------------------------------------------
@Override
public void onNavigationDrawerItemSelected ( int position ) {
Fragment frg;
// getSupportActionBar().setDisplayOptions( ActionBar.DISPLAY_SHOW_CUSTOM );
switch ( position )
{ case 0 : //getSupportActionBar().setCustomView( R.layout.perfil_tit );
mTitle = "Perfil";
frg = new perfil_frg();
break;
case 1 : // getSupportActionBar().setCustomView( R.layout.contactos_tit );
mTitle = "Contactos";
frg = new contactos_frg();
break;
default : frg = PlaceholderFragment.newInstance( position + 1 );
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace( R.id.container,frg ).commit();
}
//------------------------------------------------------------------------------
public void onSectionAttached ( int number ) {
switch (number) {
case 1 : mTitle = getString( R.string.mnu_opc_per ); break;
case 2 : mTitle = getString( R.string.mnu_opc_con ); break;
case 3 : mTitle = getString( R.string.mnu_opc_sal ); 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.menu_act,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;
*/
//mDrawerToggle.syncState();
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.menu_frg, container, false);
return rootView;
}
//------------------------------------------------------------------------------
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((menu_act) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NUMBER));
}
//==============================================================================
}
//------------------------------------------------------------------------------
}
#1
1
Android Studio allows to add a navigation drawer to the app through File | New | Activity. This "ready-made" navigation drawer comes with everything you need: properties, methods, events, etc.
Android Studio允许通过File |将导航抽屉添加到应用程序新的|活动。这个“现成的”导航抽屉带有您需要的一切:属性,方法,事件等。
Next steps to change titles for different fragments are intended to use with the ready-made navigation drawer of Android Studio, but they might be helpful to anyothers:
更改不同片段的标题的后续步骤旨在与Android Studio的现成导航抽屉一起使用,但它们可能对任何人都有帮助:
-
The navigation drawer has several files : one activity, and one or more fragments. Open the java activity file of your navigation drawer (what you call "Base Activity").
导航抽屉有几个文件:一个活动和一个或多个片段。打开导航抽屉的java活动文件(您称之为“基本活动”)。
-
Find method onCreate.
查找onCreate方法。
-
In this method, add the line mTitle = "???", where "???" is the title of the first fragment that will me shown as soon as the navigation drawer screen appears.
在这个方法中,添加行mTitle =“???”,其中“???”是导航抽屉屏幕出现后我将显示的第一个片段的标题。
-
Now find method onNavigationDrawerItemSelected. CHARLIE, I'm not sure, but I believe you have it under the name opcionesPanelLateral.
现在找到onNavigationDrawerItemSelected的方法。查理,我不确定,但我相信你的名字是opcionesPanelLateral。
-
In this method you have a switch. This switch opens the appropiate fragment depending on the selected option. To set the title for each fragment, go to each case in the switch an add the line mTitle = "My title"; before frg = new my_frag();. This way, when the fragment opens it will show the appropiate title.
在这种方法中你有一个开关。此开关根据所选选项打开适当的片段。要设置每个片段的标题,请转到开关中的每个案例,添加行mTitle =“我的标题”;在frg = new my_frag();之前。这样,当片段打开时,它将显示适当的标题。
-
Find method restoreActionBar. CHARLIE, I don't see it in your code nor any equivalent method. Add it. Inside of it, add the line actionBar.setTitle( mTitle);, and here is where the title is actually set (maybe that's why your title disappears). Call this method inside onCreateOptionsMenu (after inflate).
查找方法restoreActionBar。查理,我在你的代码中没有看到它,也没有任何等效的方法。添加它。在其中,添加行actionBar.setTitle(mTitle);,这里是标题实际设置的地方(也许这就是你的标题消失的原因)。在onCreateOptionsMenu中调用此方法(在inflate之后)。
That's it. I'm using hard-coded strings, if you follow Android rules, use strings.xml.
而已。我正在使用硬编码字符串,如果您遵循Android规则,请使用strings.xml。
Now a real life example from and app I'm working on right now. Next is the raw code of my "BaseActivity" of the ready-made navigation drawer (some things are in spanish because I'm costarrican):
现在是我正在努力的现实生活中的一个例子。接下来是现成导航抽屉的“BaseActivity”的原始代码(有些东西是西班牙语,因为我是costarrican):
package my_package;
//------------------------------------------------------------------------------
import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
//------------------------------------------------------------------------------
public class menu_act extends ActionBarActivity
implements drawer_frg.NavigationDrawerCallbacks {
//------------------------------------------------------------------------------
// Fragment managing the behaviors, interactions and presentation of the navigation drawer.
private drawer_frg 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.menu_lay );
mNavigationDrawerFragment = (drawer_frg) getSupportFragmentManager().findFragmentById(
R.id.navigation_drawer );
mTitle = "Perfil"; // getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp( R.id.navigation_drawer,( DrawerLayout )
findViewById( R.id.drawer_layout ) );
// BARRA DE TÍTULO ANARANJADA.
//ActionBar actionBar = getSupportActionBar();
//actionBar.setBackgroundDrawable( new ColorDrawable( getResources().getColor( R.color.col_nar ) ) );
}
//------------------------------------------------------------------------------
@Override
public void onNavigationDrawerItemSelected ( int position ) {
Fragment frg;
// getSupportActionBar().setDisplayOptions( ActionBar.DISPLAY_SHOW_CUSTOM );
switch ( position )
{ case 0 : //getSupportActionBar().setCustomView( R.layout.perfil_tit );
mTitle = "Perfil";
frg = new perfil_frg();
break;
case 1 : // getSupportActionBar().setCustomView( R.layout.contactos_tit );
mTitle = "Contactos";
frg = new contactos_frg();
break;
default : frg = PlaceholderFragment.newInstance( position + 1 );
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace( R.id.container,frg ).commit();
}
//------------------------------------------------------------------------------
public void onSectionAttached ( int number ) {
switch (number) {
case 1 : mTitle = getString( R.string.mnu_opc_per ); break;
case 2 : mTitle = getString( R.string.mnu_opc_con ); break;
case 3 : mTitle = getString( R.string.mnu_opc_sal ); 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.menu_act,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;
*/
//mDrawerToggle.syncState();
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.menu_frg, container, false);
return rootView;
}
//------------------------------------------------------------------------------
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((menu_act) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NUMBER));
}
//==============================================================================
}
//------------------------------------------------------------------------------
}