我在我的应用程序中为每个活动使用自定义标题视图。在其中一个活动中,基于按钮点击,我需要更改自定义标题视图。现在,每当我调用setFeatureInt时,这都可以正常工作。

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

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

感谢。

修改

这是我尝试过的。即使在调用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 )使用 setFeatureInt 方法中查看/ LayoutInflater.html“rel =”noreferrer“> LayoutInflater 并使用 inflate attachToRoot = true 。因此,当您调用 setFeatureInt 时,新布局不会替换,而是附加到内部标题容器,从而相互叠加。

您可以使用以下帮助程序方法而不是 setFeatureInt 来解决此问题。在设置新的自定义标题功能之前,帮助程序只是从内部标题容器中删除所有视图:


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

修改

正如评论中所指出的,上述解决方法并不理想。您不必依赖 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);

其他提示

执行此操作的正确方法如下:

requestWindowFeature( Window.FEATURE_CUSTOM_TITLE );
setContentView( R.layout.my_layout );
getWindow().setFeatureInt( Window.FEATURE_CUSTOM_TITLE, R.layout.my_custom_title );
super.onCreate( savedInstanceState );

请注意,这些陈述的顺序非常重要。

如果您在任何其他语句之前调用super.onCreate(),您将获得一个空白标题栏,找到标题栏ID并从中删除所有视图的黑客将修复但不建议使用。

您是否在更新文本后调用invalidate或postInvalidate来重绘视图?如果它是一个自定义视图,你可以在绘图代码中放置一个断点以确保它被调用吗?

如果你在UI线程上,你可以调用'invalidate',如果你没有,你必须调用'postInvalidate'或者视图不会重绘自己。

只是我的2c价值:

在MapActivity中工作时,请求自定义标题导致根本没有显示标题。

幸运的是,我想做的就是以不同的方式设置标题文本,我很快意识到只是在onCreate()中调用setTitle()对我有用(我在调用setContentView()之后调用它)

很抱歉,我现在没有时间再调试这个,弄清楚为什么我做的不起作用,为什么更改它使它工作。正如我所说,只是认为这可能有助于某人走出困境。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top