找出当前正在屏幕上显示的布局文件

时间:2015-12-14 12:37:20

标签: android xml android-layout android-view setcontentview

我目前有AppCompatActivity,我希望能够使用我设置的菜单按钮切换其布局。

我目前可以使用setContentView执行此操作,但是为了切换回显示的原始View,我需要知道当前显示的是哪一个。

如何获取正在显示的布局文件的当前ID?

这就是我目前的情况,逻辑是可以的,但代码似乎不起作用:

View currentLayout = findViewById(android.R.id.content);
int currentLayoutID = currentLayout.getId();
if (currentLayoutID == R.layout.two) {
    setContentView(R.layout.one);
} else if (currentLayoutID == R.layout.one) {
    setContentView(R.layout.two);
}

4 个答案:

答案 0 :(得分:1)

您可以使用findViewById查找仅存在于当前视图中的特定视图。如果findViewById未返回null,则表示您正在查看该特定布局。

答案 1 :(得分:0)

您将视图的ID与布局名称进行比较:

int currentLayoutID = currentLayout.getId();
if (currentLayoutID == R.layout.two) {

我将介绍一个存储当前所选布局的简单类属性:

private static final int CUR_LAYOUT_ONE = 1;
private static final int CUR_LAYOUT_TWO = 2;
private int currentLayoutID;

// ....

if (currentLayoutID == CUR_LAYOUT_TWO) {
    setContentView(R.layout.one);
    currentLayoutID = CUR_LAYOUT_ONE;
} else if (currentLayoutID == R.layout.one) {
    setContentView(R.layout.two);
    currentLayoutID = CUR_LAYOUT_TWO;
}

也许您需要一些额外的onSaveInstanceState() - 行为。取决于您的用例。

答案 2 :(得分:0)

if (currentLayoutID == R.layout.two) {
    setContentView(R.layout.one);
} else if (currentLayoutID == R.layout.one) {
    setContentView(R.layout.two);
}

您正在将idR.layout进行比较。这是R文件中的两个不同条目。您需要比较您给出的观点的实际ID。通常您将它们设置在xml文件中。 例如R.id.layout1

答案 3 :(得分:0)

也许您应该考虑使用ViewSwitcher。这比setContentView

快得多

http://developer.android.com/reference/android/widget/ViewSwitcher.html

您只需将ViewSwitcher定义为您的视图的父级(您只能在2个视图之间切换),如下所示:

<ViewSwitcher 
android:id="@+id/viewSwitcher"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

并以编程方式在这样的视图之间切换:

switcher.setDisplayedChild(1);