[英]how to change the Title in Navigation Drawer
I would like that the title in the menu will change by the fragment name that was click.我希望菜单中的标题会因单击的片段名称而改变。 for the code below what i get is that, the actual title in each fragment is "Home" and its does not change.
对于下面的代码,我得到的是,每个片段中的实际标题是“Home”并且它不会改变。 but i found that when i click on an item in the menu the title changing for a second and return back to the "Home" title.
但我发现当我点击菜单中的一个项目时,标题会改变一秒钟并返回“主页”标题。 i implemented the ondrawer but still i don't know what could cause that.
我实施了抽屉,但我仍然不知道是什么原因造成的。
my code:我的代码:
package com.example.matant.gpsportclient;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.matant.gpsportclient.Controllers.Fragments.CreateEventFragmentController;
import com.example.matant.gpsportclient.Controllers.DBcontroller;
import com.example.matant.gpsportclient.Controllers.Fragments.GoogleMapFragmentController;
import com.example.matant.gpsportclient.Controllers.Fragments.ManageEventFragmentController;
import com.example.matant.gpsportclient.Controllers.Fragments.ProfileFragmentController;
import com.example.matant.gpsportclient.InterfacesAndConstants.AsyncResponse;
import com.example.matant.gpsportclient.InterfacesAndConstants.Constants;
import com.example.matant.gpsportclient.Utilities.DrawerItem;
import com.example.matant.gpsportclient.Utilities.DrawerItemCustomAdapter;
import com.example.matant.gpsportclient.Utilities.SessionManager;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainScreen extends AppCompatActivity implements AsyncResponse {
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DBcontroller dbController;
private ProgressDialog progress = null;
private SessionManager sm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
return;
}
mNavigationDrawerItemTitles= getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
sm = SessionManager.getInstance(this);
mTitle = mDrawerTitle = "Home";
DrawerItem [] drawerItems = new DrawerItem[Constants.MENU_SIZE];
drawerItems[0] = new DrawerItem(R.drawable.home,"Home");
drawerItems[1] = new DrawerItem(R.drawable.profile,"Profile");
drawerItems[2] = new DrawerItem(R.drawable.search,"Search Events");
drawerItems[3] = new DrawerItem(R.drawable.create,"Create Event");
drawerItems[4] = new DrawerItem(R.drawable.manage,"Manage Event");
drawerItems[5] = new DrawerItem(R.drawable.attending,"Attending List");
drawerItems[6] = new DrawerItem(R.drawable.recent_search_24,"Recent Searches");
drawerItems[7] = new DrawerItem(R.drawable.logout,"Log Out");
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_menu, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
getSupportActionBar().setTitle(mNavigationDrawerItemTitles[0]);
if (savedInstanceState == null) {
// on first time display view for first nav item
selectItem(0);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public void handleResponse(String resStr) {
try
{
if((this.progress!= null )&& this.progress.isShowing())
{
this.progress.dismiss();
}
}catch (final IllegalArgumentException e){
Log.d("Dialog error",e.getMessage());
}catch (final Exception e){
Log.d("Dialog error",e.getMessage());
}
finally {
this.progress = null;
}
Log.d("handleResponse", resStr);
if(resStr!=null)
{
try {
JSONObject jsonObj = new JSONObject(resStr);
String flg = jsonObj.getString(Constants.TAG_FLG);
switch (flg) {
case "user logged out":
{
sm.logoutUser();
break;
}
case "query failed": {
Toast.makeText(getApplicationContext(),"Error Connection",Toast.LENGTH_LONG).show();
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public void sendDataToDBController() {
String user = sm.getUserDetails().get(Constants.TAG_EMAIL);
BasicNameValuePair tagReq = new BasicNameValuePair("tag","logout");
BasicNameValuePair userNameParam = new BasicNameValuePair("username",user);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(tagReq);
nameValuePairList.add(userNameParam);
dbController = new DBcontroller(this,this);
dbController.execute(nameValuePairList);
}
@Override
public void preProcess() {
this.progress = ProgressDialog.show(this, "Log Out",
"Logging out...", true,false);
}
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) {
Fragment fragment = null;
switch (position) {
case 0: //Home
fragment = new GoogleMapFragmentController();
break;
case 1: //Profile
fragment = new ProfileFragmentController();
break;
case 2: //Search Events
//fragment = new SearchEventFragmentController();
break;
case 3: //Create Events
fragment = new CreateEventFragmentController();
break;
case 4: //Manage Events
fragment = new ManageEventFragmentController();
break;
case 5: //Attending List
//fragment = new AttendingListFragmentController();
break;
case 6: //Recent Searches
//fragment = new RecentSearchesFragmentController();
break;
case 7: { //Log Out
logout();
finish(); //destroy the main activity
}
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
getSupportActionBar().setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().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);
}
public void logout()
{
sendDataToDBController();
}
/*@Override
protected void onDestroy() {
super.onDestroy();
logout();
}*/
}
Set it for all your fragment.为所有片段设置它。 This should do the work!!
这应该做的工作!
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.id.your_fragment_layout, container,
false);
getActivity().setTitle("<your title>");
return rootView;
}
try this:尝试这个:
@Override
public void onResume() {
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Your Title");
}
Ok i found the problem, your answer was good and i really change the title each time from the fragment but in addition i need to disable this line:好的,我发现了问题,您的回答很好,我每次都从片段中更改标题,但另外我需要禁用此行:
getSupportActionBar().setTitle(mDrawerTitle);
from the onDrawerOpened and onDrawerClosed从 onDrawerOpened 和 onDrawerClosed
Do not set the title to ActionBar, set the title to Activity, you can do so from the activity or fragment.不要将title设置为ActionBar,将title设置为Activity,可以从activity或者fragment中进行。 For Activity:
对于活动:
setTitle("New Title");
or for Fragment:或片段:
getActivity().setTitle("New Title");
add this in your fragment将此添加到您的片段中
getActivity().setTitle("title");
add remove this below line from Drawer activity添加从抽屉活动中删除以下行
getActivity().setTitle("title");
Try this one it worked for me试试这个对我有用
place a Textview inside the toolbar of app_bar activity
在 app_bar 活动的工具栏内放置一个 Textview
Inside the oncreateView of a fragment put this code
在片段的 oncreateView 里面放这个代码
TextView heading;
heading=(TextView)getActivity().findViewById(R.id.Id_title);
heading.setText("your text");
By using this you can Name each fragments with your own text通过使用它,您可以用自己的文本命名每个片段
在 onCreateView() 中编写以下代码:
activity!!.setTitle("Your Text")
If your purpose is "Changing toolbar title according to the fragment name" i tip to see if the "navigation graph" of the "navigation drawer" you set all stuff correctly: every fragment should have something like this:如果您的目的是“根据片段名称更改工具栏标题”,我提示您查看“导航抽屉”的“导航图”是否正确设置了所有内容:每个片段都应具有以下内容:
<fragment
android:id="@+id/nav_ID_OF_FRAGMENT"
android:name="rubik_cube.navigation.ui.NAME_OF_Fragment"
android:label="@string/TOOLBAR_TITLE_HERE"
tools:layout="@layout/fragment_LAYOUT_GO_HERE" />
and in the resources the fragment desired title string, in the res/layout the layout of the fragment, in the code a class that handle the fragment stuff在资源中,片段所需的标题字符串,在 res/layout 中片段的布局,在代码中处理片段内容的类
and toolbar works perfectly!和工具栏完美地工作!
if u want to change toolbar name dinamically according to other stuff like idk pressing a button, select from menu u need to change it programmatically instead with:如果您想根据 idk 按下按钮等其他内容动态更改工具栏名称,请从菜单中选择您需要以编程方式更改它,而不是:
ActionBar toolbar = requireActivity().getSupportActionBar();
if(toolbar != null) toolbar.setTitle("your title");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.