Android 找出屏幕上当前显示的布局文件
我目前有一个Android 找出屏幕上当前显示的布局文件,android,xml,android-layout,android-view,setcontentview,Android,Xml,Android Layout,Android View,Setcontentview,我目前有一个AppCompatActivity,我希望能够使用我设置的菜单按钮之一切换其布局 我现在可以使用setContentView来实现这一点,但是为了切换回原来显示的视图,我需要知道当前显示的是哪一个 如何获取正在显示的布局文件的当前ID 这就是我目前拥有的,逻辑还可以,但代码似乎不起作用: View currentLayout = findViewById(android.R.id.content); int currentLayoutID = currentLayout.getId(
AppCompatActivity
,我希望能够使用我设置的菜单按钮之一切换其布局
我现在可以使用setContentView
来实现这一点,但是为了切换回原来显示的视图,我需要知道当前显示的是哪一个
如何获取正在显示的布局文件的当前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);
}
您可以使用findViewById
查找仅存在于当前视图中的特定视图。如果findViewById
未返回null,则表示您正在查看该特定布局 将视图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()-行为。取决于您的用例
if (currentLayoutID == R.layout.two) {
setContentView(R.layout.one);
} else if (currentLayoutID == R.layout.one) {
setContentView(R.layout.two);
}
您正在将id
与R.layout
进行比较。这是R
文件中的两个不同条目。您需要将实际ID与您提供的视图进行比较。通常在xml文件中设置它们。
例如<代码> R.ID.LayOut<1/代码> 也许你应该考虑使用VIEW Switter。这将比setContentView快得多
您只需将ViewSwitcher定义为xml中视图的父视图(只能在两个视图之间切换),如下所示:
<ViewSwitcher
android:id="@+id/viewSwitcher"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
switcher.setDisplayedChild(1);
尝试使用isShown()方法。@Nikunj这只与可见性有关,不幸的是,我正在切换布局文件,而不是在一个布局文件中处理视图的可见性。我认为这样使用setContentView()
是不明智的。您应该使用片段
。