为了账号安全,请及时绑定邮箱和手机立即绑定

从片段设置自定义ActionBar标题

从片段设置自定义ActionBar标题

一只甜甜圈 2019-12-25 14:33:59
在我的Main中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);这完美。但是,一旦我打开other 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>
查看完整描述

3 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

你在做什么是对的。Fragments没有访问ActionBarAPI的权限,因此您必须致电getActivity。除非您Fragment是静态内部类,否则您应该WeakReference为父级创建一个并调用Activity。getActionBar从那里。


要ActionBar在使用自定义布局时为您设置标题,您Fragment需要致电getActivity().setTitle(YOUR_TITLE)。


你打电话的原因setTitle是因为你打电话getTitle为你的标题ActionBar。getTitle返回该标题Activity。


如果你不想让通话getTitle,那么你就需要创建一个公共方法,设置你的文字TextView中Activity承载Fragment。


在您的活动中:


public void setActionBarTitle(String title){

    YOUR_CUSTOM_ACTION_BAR_TITLE.setText(title);

}

在您的片段中:


((MainFragmentActivity) getActivity()).setActionBarTitle(YOUR_TITLE);

文件:


Activity.getTitle


Activity.setTitle


另外,您无需调用this.whatever提供的代码,只需提示。


查看完整回答
反对 回复 2019-12-25
  • 3 回答
  • 0 关注
  • 560 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信