gpt4 book ai didi

Android - 在运行时更改自定义标题 View

转载 作者:IT老高 更新时间:2023-10-28 22:20:49 27 4
gpt4 key购买 nike

我在我的应用程序中为每个 Activity 使用自定义标题 View 。在其中一项 Activity 中,基于按钮单击,我需要更改自定义标题 View 。现在每次我调用 setFeatureInt 时都可以正常工作。

但如果我尝试更新自定义标题中的任何项目(例如更改按钮的文本或标题上的 TextView ),则不会进行更新。

通过代码调试显示 TextView 和按钮实例不为空,我还可以看到自定义标题栏。但是 TextView 或按钮上的文本没有更新。有没有其他人遇到过这个问题?我该如何解决?

谢谢。

编辑

这是我尝试过的。即使调用 postInvalidate 也不会更新。

    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.text_title);

TextView databar = (TextView) findViewById(R.id.title_text);
databar.setText("Some Text");
databar.postInvalidate();

Button leftButton = (Button) findViewById(R.id.left_btn);
leftButton.setOnClickListener(mLeftListener);
leftButton.setText("Left Btn");
leftButton.postInvalidate();

Button rightBtn = (Button) findViewById(R.id.right_btn);
rightBtn.setOnClickListener(mRightListener);
rightBtn.postInvalidate();

最佳答案

问题是唯一的Window实现( PhoneWindow )使用 LayoutInflater在其 setFeatureInt 方法中并用 inflate 实例化新布局和 attachToRoot=true。因此,当您调用 setFeatureInt 时,新布局不会替换,而是附加 到内部标题容器,从而在彼此之上绘制。

您可以通过使用以下辅助方法而不是 setFeatureInt 来解决此问题。在设置新的自定义标题功能之前,助手会简单地从内部标题容器中删除所有 View :


private void setCustomTitleFeatureInt(int value) {
try {
// retrieve value for com.android.internal.R.id.title_container(=0x1020149)
int titleContainerId = (Integer) Class.forName(
"com.android.internal.R$id").getField("title_container").get(null);

// remove all views from titleContainer
((ViewGroup) getWindow().findViewById(titleContainerId)).removeAllViews();

// add new custom title view
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, value);

} catch(Exception ex) {
// whatever you want to do here..
}
}

我不确定当前的 setFeatureInt 行为是否是有意的,但它肯定没有以一种或另一种方式记录,这就是为什么我将把它带到 android 开发者那里;)

编辑

正如评论中所指出的,上述解决方法并不理想。无需依赖 com.android.internal.R.id.title_container 常量,您只需在设置新标题时隐藏旧的自定义标题。

假设您有两个自定义标题布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/custom_title_1" ...

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/custom_title_2" ...

如果您想将 custom_title_1 替换为 custom_title_2,您可以隐藏前者并使用 setFeatureInt 添加后者:

findViewById(R.id.custom_title_1).setVisibility(View.GONE);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_2);

关于Android - 在运行时更改自定义标题 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/820398/

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