从 Fragment 设置自定义 ActionBar 标题 [英] Setting Custom ActionBar Title from Fragment

查看:75
本文介绍了从 Fragment 设置自定义 ActionBar 标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的主 FragmentActivity 中,我设置了我的自定义 ActionBar 标题,如下所示:

 LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);查看 v = inflator.inflate(R.layout.custom_titlebar, null);TextView tv = (TextView) v.findViewById(R.id.title);字体 tf = Typeface.createFromAsset(this.getAssets(),"字体/capsuula.ttf");tv.setTypeface(tf);tv.setText(this.getTitle());actionBar.setCustomView(v);

这很完美.但是,一旦我打开其他 Fragments,我想更改标题.我不确定如何访问 Main Activity 来执行此操作?过去,我是这样做的:

((MainFragmentActivity) getActivity()).getSupportActionBar().setTitle(catTitle);

有人可以建议正确的方法吗?

XML:

</RelativeLayout>

解决方案

===更新 2019 年 10 月 30 日====

由于我们有了 ViewModelLiveData 等新组件,我们可以通过使用 ViewModel 和 Live Data 以不同/更简单的方式从 Fragment 更新活动标题

活动

class MainActivity : AppCompatActivity() {private lateinit var viewModel: MainViewModel覆盖 fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.main_activity)如果(savedInstanceState == null){supportFragmentManager.beginTransaction().replace(R.id.container, MainFragment.newInstance()).commitNow()}viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)viewModel.title.observe(这个,观察者{supportActionBar?.title = it})} }

主片段

class MainFragment : Fragment() {伴生对象{有趣的 newInstance() = MainFragment()}private lateinit var viewModel: MainViewModel覆盖 fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,已保存的实例状态:捆绑?):查看{返回 inflater.inflate(R.layout.main_fragment,容器,假)}覆盖 fun onActivityCreated(savedInstanceState: Bundle?) {super.onActivityCreated(savedInstanceState)活动?.运行{viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)} ?: throw Throwable("无效活动")viewModel.updateActionBarTitle("来自片段的自定义标题")} }

和 MainModelView:

class MainViewModel : ViewModel() {private val _title = MutableLiveData()val 标题:LiveDataget() = _title有趣的 updateActionBarTitle(title: String) = _title.postValue(title) }

然后您可以使用 viewModel.updateActionBarTitle("Custom Title From Fragment")

从 Fragment 更新活动标题

===2015 年 4 月 10 日更新===

你应该使用监听器来更新你的操作栏标题

片段:

public class UpdateActionBarTitleFragment extends Fragment {私有 OnFragmentInteractionListener mListener;公共 UpdateActionBarTitleFragment() {}@覆盖public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);如果(getArguments()!= null){}}@覆盖公共视图 onCreateView(LayoutInflater inflater, ViewGroup 容器,捆绑savedInstanceState) {如果(mListener != null){mListener.onFragmentInteraction("自定义标题");}返回 inflater.inflate(R.layout.fragment_update_action_bar_title2,容器,假);}@覆盖public void onAttach(活动活动){super.onAttach(活动);尝试 {mListener = (OnFragmentInteractionListener) 活动;} catch (ClassCastException e) {抛出新的 ClassCastException(activity.toString()+ " 必须实现 OnFragmentInteractionListener");}}@覆盖公共无效 onDetach() {super.onDetach();mListener = null;}公共接口 OnFragmentInteractionListener {public void onFragmentInteraction(String title);}}

和活动:

public class UpdateActionBarTitleActivity 扩展 ActionBarActivity 实现 UpdateActionBarTitleFragment.OnFragmentInteractionListener {@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_update_action_bar_title);}@覆盖公共无效 onFragmentInteraction(字符串标题){getSupportActionBar().setTitle(title);}}

在此处阅读更多信息:https://developer.android.com/training/basics/fragments/communicating.html

In my Main FragmentActivity, I setup my custom ActionBar title like this:

    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);

This works perfect. However, once I open other Fragments, I want the title to change. I am not sure how to access the Main Activity to do this? In the past, I did this:

((MainFragmentActivity) getActivity()).getSupportActionBar().setTitle(
            catTitle);

Can someone advise on the proper method?

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>

解决方案

===Update October, 30, 2019===

Since we have new components such as ViewModel and LiveData, we can have a different/easier way to update Activity Title from Fragment by using ViewModel and Live Data

Activity

class MainActivity : AppCompatActivity() {
private lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.main_activity)
    if (savedInstanceState == null) {
        supportFragmentManager.beginTransaction()
            .replace(R.id.container, MainFragment.newInstance())
            .commitNow()
    }
    viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
    viewModel.title.observe(this, Observer {
        supportActionBar?.title = it
    })
} }

MainFragment

class MainFragment : Fragment() {
companion object {
    fun newInstance() = MainFragment()
}
private lateinit var viewModel: MainViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View {
    return inflater.inflate(R.layout.main_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    activity?.run {
        viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
    } ?: throw Throwable("invalid activity")
    viewModel.updateActionBarTitle("Custom Title From Fragment")
} }

And MainModelView:

class MainViewModel : ViewModel() {
private val _title = MutableLiveData<String>()
val title: LiveData<String>
get() = _title
fun updateActionBarTitle(title: String) = _title.postValue(title) }

And then you can update the Activity title from Fragment using viewModel.updateActionBarTitle("Custom Title From Fragment")

===Update April, 10, 2015===

You should use listener to update your action bar title

Fragment:

public class UpdateActionBarTitleFragment extends Fragment {
    private OnFragmentInteractionListener mListener;

    public UpdateActionBarTitleFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mListener != null) {
            mListener.onFragmentInteraction("Custom Title");
        }
        return inflater.inflate(R.layout.fragment_update_action_bar_title2, container, false);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(String title);
    }
}

And Activity:

public class UpdateActionBarTitleActivity extends ActionBarActivity implements UpdateActionBarTitleFragment.OnFragmentInteractionListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_action_bar_title);
    }

    @Override
    public void onFragmentInteraction(String title) {
        getSupportActionBar().setTitle(title);
    }
}

Read more here: https://developer.android.com/training/basics/fragments/communicating.html

这篇关于从 Fragment 设置自定义 ActionBar 标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆