我的问题可能很简单。 我在我的 layout.xml 文件中定义了一个 LinearLayout 并希望在代码中设置可绘制背景。
布局.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linlay"
android:orientation="vertical"
android:layout_width="fill_parent">
</LinearLayout>
.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ln = (LinearLayout) this.findViewById(R.id.linlay);
setContentView(ln);
ln.setBackgroundDrawable(getResources().getDrawable(R.drawable.wallpaper));
}
如果我运行应用程序,它说应用程序意外停止。 有任何想法吗?
最佳答案
您必须从资源中为您的 Activity 设置布局
setContentView(R.layout.my_layout);
然后你可以调用findViewById()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout); // add this code
LinearLayout ln = (LinearLayout) this.findViewById(R.id.linlay);
ln.setBackgroundDrawable(getResources().getDrawable(R.drawable.wallpaper));
}
在您的情况下,您可以通过添加到 LinearLayout 来简单地在 xml 资源文件中设置墙纸
android:background="@drawable/wallpaper"
关于android - LinearLayout findViewById 问题 - 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5263563/