layout_extra.xml
的新布局文件,其中 id
为 layout_extra
,它只包含一个开关,id
为 switch1
。activity_main.xml
包含一个按钮,其中 id
为 button
,用于导航到 layout_extra
。MainActivity.java
的内容如下:public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(v->{
setContentView(R.layout.layout_extra);
});
findViewById(R.id.switch1).setOnClickListener(v->{
findViewById(R.layout.layout_extra).setBackgroundColor(Color.RED);
});
}
}
我在 Android Studio 上遇到以下错误。
工具提示提供以下信息。
我做了所有给定的建议,但没有奏效(应用程序崩溃)。
如何在匿名类方法中正确调用资源 ID?
答案 0 :(得分:1)
嗯,方法“findViewById()”正在询问对象的 ID,而不是资源。
基本上我认为你应该做的是在你的主布局的“XML”中设置“ID”,而不是你可以使用“findViewById()”方法,任何对象在“XML”中都有一个 id,甚至是布局可以设置ID。
例如: 在 XML 中设置主要对象的 id:
<块引用>android:id="@+id/layout_extra"
在代码中:
<块引用>findViewById(R.id.layout_extra).setBackgroundColor(Color.RED);
答案 1 :(得分:1)
我想我有错误。您正在对空对象调用 setOnClickListener()
。因此,更新后的代码应该是:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// The following does not set the layout 'layout_extra' as root view until the button press
findViewById(R.id.button).setOnClickListener(v->{
// This block executes on button press
setContentView(R.layout.layout_extra);
final View layout_extra = findViewById(R.id.layout_extra);
findViewById(R.id.switch1).setOnClickListener(v2->{
layout_extra.setBackgroundColor(Color.RED);
});
});
}
}
其中 R.id.layout_extra
指的是 id
的根元素的 layout_extra.xml
。
答案 2 :(得分:0)
setOnClickListener() 使用新视图,因此 findViewById(R.layout.layout_extra).setBackgroundColor(Color.RED);
不起作用,您应该尝试:
public class MainActivity extends AppCompatActivity {
private Layout layout_extra; // TextView, Button ...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(v->{
setContentView(R.layout.layout_extra);
});
layout_extra = findViewById(R.layout.layout_extra);
findViewById(R.id.switch1).setOnClickListener(v->{
layout_extra.setBackgroundColor(Color.RED);
});
}
}