每次我运行我的应用程序时,它都会崩溃,给我一个空指针异常,我想根据情况以编程方式更改我的背景,这是我的代码:
主要 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并使用从中获得的对象来改变你的背景,就像你正在做的那样。
试试这个:
ConstraintLayout
对象 ConstraintLayout layout = findViewById(R.id.container)
(注意:您可以将其称为任何名称,而不仅仅是容器,我只是放弃上面的示例,因为我给了它 ID“容器”)
setBackgroundResource()
就像你正在做的那样。
setContentView()
同样,这是在一开始就设置的,您不想将其重置为您刚刚构建的新 View ,就像您最初所做的那样。
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/