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

los*_*sit 23 android android-custom-view

我在我的应用程序中为每个活动使用自定义标题视图.在其中一个活动中,基于按钮点击,我需要更改自定义标题视图.现在,每当我调用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();
Run Code Online (Sandbox Code Playgroud)

Jos*_*ger 31

问题是,只有Window实现(PhoneWindow)使用LayoutInflatersetFeatureInt方法与实例化新的布局inflateattachToRoot=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..
    }
}
Run Code Online (Sandbox Code Playgroud)

我不确定当前的setFeatureInt行为是否有意,但肯定没有记录的方式或其他,这就是为什么我会把它带到android开发者;)

编辑

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

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

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/custom_title_1" ...
Run Code Online (Sandbox Code Playgroud)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/custom_title_2" ...
Run Code Online (Sandbox Code Playgroud)

并且要替换custom_title_1custom_title_2,你可以隐藏前和使用setFeatureInt中添加后:

findViewById(R.id.custom_title_1).setVisibility(View.GONE);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_2);
Run Code Online (Sandbox Code Playgroud)


Jam*_*ans 13

正确的方法如下:

requestWindowFeature( Window.FEATURE_CUSTOM_TITLE );
setContentView( R.layout.my_layout );
getWindow().setFeatureInt( Window.FEATURE_CUSTOM_TITLE, R.layout.my_custom_title );
super.onCreate( savedInstanceState );
Run Code Online (Sandbox Code Playgroud)

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

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