在我的主 FragmentActivity
中,我设置了我的自定义 ActionBar
标题,如下所示:
LayoutInflater inflator = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.custom_titlebar, null);
TextView tv = (TextView) v.findViewById(R.id.title);
Typeface tf = Typeface.createFromAsset(this.getAssets(),
"fonts/capsuula.ttf");
tv.setTypeface(tf);
tv.setText(this.getTitle());
actionBar.setCustomView(v);
这很完美。但是,一旦我打开其他 Fragments
,我希望更改标题。我不确定如何访问 Main Activity
来执行此操作?过去,我是这样做的:
((MainFragmentActivity) getActivity()).getSupportActionBar().setTitle(
catTitle);
有人可以建议正确的方法吗?
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent" >
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:ellipsize="end"
android:maxLines="1"
android:text=""
android:textColor="#fff"
android:textSize="25sp" />
</RelativeLayout>
最佳答案
你所做的是正确的。 Fragments
无法访问 ActionBar
API,因此您必须调用 getActivity
。除非您的 Fragment
是静态内部类,在这种情况下,您应该为父级创建一个 WeakReference
并从那里调用 Activity.getActionBar
。
要为您的 ActionBar
设置标题,在使用自定义布局时,您需要在 Fragment
中调用 getActivity().setTitle(YOUR_TITLE )
.
之所以调用setTitle
是因为你调用getTitle
作为ActionBar
的标题。 getTitle
返回该 Activity
的标题。
如果您不想调用 getTitle
,那么您需要创建一个公共(public)方法,在 中设置
。 TextView
的文本承载 Fragment
的 Activity
在您的 Activity 中:
public void setActionBarTitle(String title){
YOUR_CUSTOM_ACTION_BAR_TITLE.setText(title);
}
在您的 fragment 中:
((MainFragmentActivity) getActivity()).setActionBarTitle(YOUR_TITLE);
文档:
另外,您不需要在您提供的代码中调用 this.whatever
,只是一个提示。
关于java - 从 Fragment 设置自定义 ActionBar 标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15560904/