android - LinearLayout findViewById 问题 - 崩溃

标签 android android-layout

我的问题可能很简单。 我在我的 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/

相关文章:

android - 将 @Component.Builder 与构造函数参数一起使用

android - Cordova 通知中的多行消息

Android ScrollView 高度不变

android - 展开 View 下方的布局不可见?

android - 观看次数是如何限制的?

android - 在 Android 上以编程方式输入密码,如 *#*#4636#*#*

java - 从另一个应用程序切换回来后如何阻止我的应用程序崩溃?

android - CardView 角半径

android - 在titlecase工具栏android中添加菜单项文本和文本

android - 如何使用固定 View 创建垂直分页