以编程方式更改android布局

问题描述 投票:2回答:2

我用这样的布局main.xml开始我的应用程序:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/relative" xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent">
    <ImageButton android:id="@+id/applogo" ... android:src="@drawable/app_logo"/>
    <TabHost android:id="@android:id/tabhost" ... android:layout_below="@+id/applogo">
        <LinearLayout ...>
            <TabWidget.../>
            <FrameLayout android:id="@android:id/tabcontent"...>
            </FrameLayout>
        </LinearLayout>
    </TabHost>
</RelativeLayout>

设置菜单中的用户可以选择另一个较小的布局(tiny.xml),其布局如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/relative" xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent">
    <TabHost android:id="@android:id/tabhost" ...>
        <LinearLayout ...>
            <TabWidget.../>
            <FrameLayout android:id="@android:id/tabcontent"...>
            </FrameLayout>
        </LinearLayout>
    </TabHost>
</RelativeLayout>

mainActivity扩展TabActivityonCreate方法:

...

if (isTiny())
setContentView(R.layout.tiny);
else
setContentView(R.layout.main);
mTabHost = getTabHost();

TabSpec newsTab = mTabHost.newTabSpec(NewsActivity.static_getTabActivityTag());
newsIntent = new Intent(this, NewsActivity.class);      
newsTab.setContent(newsIntent);
TextView textView = new TextView(this);

textView.setText(getResources().getString(NewsActivity.static_getIndicatorStringID());
textView.setTextSize(size);
textView.setTextColor(color);
textView.setBackgroundDrawable(background);
tab.setIndicator(textView);
mTabHost.addTab(newsTab);

我的想法是在mainActivity#onRestart中编写一些代码,这样如果用户通过设置面板更改了布局,则为他加载新的布局。怎么实现呢?我尝试使用setContentView 但它只是崩溃了 并再次为选项卡创建视图但它只是不起作用,视图是空白的。

更新:添加了如何在Activity中创建选项卡。

更新可以多次执行setContentView。我的问题与意图中的活动有关。

android layout
2个回答
3
投票

您可以随时调用setContentView,而不必在onCreate中。我会用aSharedPreferences来存储用户想要的内容视图。希望这可以帮助。


0
投票

对于片段布局,我这样做:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (MainActivity.isDarkMode) {
        return inflater.inflate(R.layout.layout_dark, container, false);
    } else {
        return inflater.inflate(R.layout.layout_light, container, false);
    }
}

所以你明白了。

© www.soinside.com 2019 - 2024. All rights reserved.