LinearLayout findViewById问题

jea*_*e91 12 android android-layout

我的问题可能很简单,我太傻了.我在layout.xml文件中定义了一个LinearLayout,并希望在代码中设置背景drawable.

layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linlay"
android:orientation="vertical"
android:layout_width="fill_parent">
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

的.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));
}
Run Code Online (Sandbox Code Playgroud)

如果我运行应用程序,它说应用程序意外停止.有任何想法吗?

jet*_*hro 13

您必须从资源设置Activity的布局

setContentView(R.layout.my_layout);
Run Code Online (Sandbox Code Playgroud)

然后你可以调用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));
}
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您可以通过添加到LinearLayout简单地在xml资源文件中设置壁纸

android:background="@drawable/wallpaper"
Run Code Online (Sandbox Code Playgroud)