java - 设置背景颜色时应用程序崩溃

标签 java android

每次我运行我的应用程序时,它都会崩溃,给我一个空指针异常,我想根据情况以编程方式更改我的背景,这是我的代码:

主要 Activity :

public class Activity extends AppCompatActivity {


ConstraintLayout layout;

String messageSafe = "Item is Safe for Consumption";
String messageUnSafe = "Item is NOT Safe for Consumption";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_information);


    layout = new ConstraintLayout(this);
    if (matched.length == 0) {
        layout.setBackgroundResource(R.drawable.background_safe);
        setContentView(layout);
        changeColor("#00FF00");
        messageView.setText(messageSafe);
    }
    else{
        layout.setBackgroundResource(R.drawable.background_unsafe);
        setContentView(layout);
        changeColor("#FF0000");
        messageView.setText(messageUnSafe);
    }


    ListView listContains = (ListView) findViewById(R.id.lvItemsFound);
    ArrayAdapter<String> contains = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, foundItems);
    listContains.setAdapter(contains);

    ListView listRestricted = (ListView) findViewById(R.id.lvItemsRestricted);
    ArrayAdapter<String> found = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, matched);
    listRestricted.setAdapter(found);


}

最佳答案

您正在失去对旧 View 的引用,因为您将布局更改为新的 ConstraintLayout目的。这意味着您现在没有 ListView XML 中的对象和其他项目,因为该 View 已消失。它不再是 ContentView 了。如果您想使用现有布局,则需要为 Root View 提供一个 ID。

<constraintlayout android:id="@+id/container" ... />

然后您可以使用 findViewById(R.id.container) 引用该 ID并使用从中获得的对象来改变你的背景,就像你正在做的那样。

试试这个:

  • 1.给你的 Root View 一个ID
  • 2.设置ConstraintLayout对象 ConstraintLayout layout = findViewById(R.id.container) (注意:您可以将其称为任何名称,而不仅仅是容器,我只是放弃上面的示例,因为我给了它 ID“容器”)
  • 3.调用setBackgroundResource()就像你正在做的那样。
  • 4.无需调用setContentView()同样,这是在一开始就设置的,您不想将其重置为您刚刚构建的新 View ,就像您最初所做的那样。
  • 5.尝试调用 setAdapter() 时不应崩溃给您ListView现在因为您没有对不在内容 View 中的对象的引用。

    layout = (ConstraintLayout)findViewById(R.id.container);
    if (matched.length == 0) {
        layout.setBackgroundResource(R.drawable.background_safe);
        changeColor("#00FF00"); //assuming this is some local function?
        messageView.setText(messageSafe);
    }
    else{
        layout.setBackgroundResource(R.drawable.background_unsafe);
        changeColor("#FF0000");
        messageView.setText(messageUnSafe);
    }
    
  • 关于java - 设置背景颜色时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48932520/

    相关文章:

    hudson - 远程安装 Hudson?

    java - 在docker中启动helloWorld.java时出错

    java - java中的Elasticsearch正则表达式查询未按预期工作

    android - 如何制作带有可拖动项目的 ListView?

    android - 有没有办法在eclipse中自动化模拟器android

    android - resConfigs 如何在 android (gradle) 中工作?

    java - Maven MOJO - 在另一个参数中使用一个参数

    java - 创建列表深拷贝

    android - F-Droid 应用程序会从 GitHub 发布在 F-Droid 服务器中自动更新吗?

    android - 带有 robolectric 的 sqlcipher 的 UnsatisfiedLinkError