gpt4 book ai didi

android - 方向更改时工具栏 (SupportActionBar) 标题更改为应用程序名称

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:02:01 29 4
gpt4 key购买 nike

我的 Activity 中有这段代码:

protected void onCreate(Bundle savedInstanceState) {
...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
...
}

我正在从 onResume() 中的各种 fragment 更新 ActionBar 标题:

ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(title);
}

这工作正常,但方向更改后,标题再次更改为应用程序名称。我该如何克服这个问题?

编辑:经过更多调查后,我尝试了这个并发现了这种奇怪的行为:在 fragment 中设置标题的地方添加了这段代码:

final ActionBar actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
if (actionBar != null) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.d("SWAPNIL", "IN RUN BEFORE: " + actionBar.getTitle());
actionBar.setTitle(title);
Log.d("SWAPNIL", "IN RUN AFTER : " + actionBar.getTitle());
}
}, 3000);
}

这是日志:

10-13 10:27:04.526 3719-3719/com.example.xxxx D/SWAPNIL: onResumeHelp
10-13 10:27:07.528 3719-3719/com.example.xxxx D/SWAPNIL: IN RUN BEFORE: MY APP NAME
10-13 10:27:07.528 3719-3719/com.example.xxxx D/SWAPNIL: IN RUN AFTER : title
10-13 10:27:21.012 3719-3719/com.example.xxxx D/SWAPNIL: onResumeHelp
10-13 10:27:24.013 3719-3719/com.example.xxxx D/SWAPNIL: IN RUN BEFORE: title
10-13 10:27:24.013 3719-3719/com.example.xxxx D/SWAPNIL: IN RUN AFTER : title

它根据日志进行了更改,但未反射(reflect)在 UI 中。请帮助我!

最佳答案

好吧,在这个愚蠢的事情上花了 2 天时间后,我终于找到了解决方案(我会说是解决方法)。

这可能是一个嵌套的 Fragment 错误。

我有嵌套的 fragment 结构。正如我们所知,Fragment.getActivity() 返回父级 Activity。经过大量调试后,我观察到如果您在方向更改后调用 getActivity()(即使在 Fragment.onActivityCreated() 内部),它会返回旧的 Activity< 的引用 除了最上面的父 fragment ,它正确地返回新创建的 Activity

所以我编写了这个方法来从任何 Fragment 获取当前的 Activity:

/**
* When inside a nested fragment and Activity gets recreated due to reasons like orientation
* change, {@link android.support.v4.app.Fragment#getActivity()} returns old Activity but the top
* level parent fragment's {@link android.support.v4.app.Fragment#getActivity()} returns current,
* recreated Activity. Hence use this method in nested fragments instead of
* android.support.v4.app.Fragment#getActivity()
*
* @param fragment
* The current nested Fragment
*
* @return current Activity that fragment is hosted in
*/
public Activity getActivity(Fragment fragment) {
if (fragment == null) {
return null;
}
while (fragment.getParentFragment() != null) {
fragment = fragment.getParentFragment();
}
return fragment.getActivity();
}

关于android - 方向更改时工具栏 (SupportActionBar) 标题更改为应用程序名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33103079/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com