簡體   English   中英

設置背景顏色時,應用崩潰

[英]App crashes when setting background colour

每當我運行我的應用程序時,崩潰都會給我一個nullpointerexception,我想根據情況以編程方式更改我的背景,這是我的代碼:

主要活動:

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);


}

您丟失了對舊視圖的引用,因為您將布局更改為新的ConstraintLayout對象。 這意味着您現在在XML中沒有ListView對象和其他項,因為該視圖已消失。 它不再是ContentView了。 如果要處理現有布局,則需要給根視圖一個ID。

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

然后,您可以使用findViewById(R.id.container)引用該ID,並findViewById(R.id.container)使用從中獲取的對象來更改背景。

嘗試這個:

  • 1.給您的根視圖一個ID
  • 2.使用ConstraintLayout layout = findViewById(R.id.container)設置一個ConstraintLayout對象(注意:您可以調用任何東西,而不僅僅是容器,我只是從上面的示例開始,因為我給它指定了ID“容器” )
  • 3.像您一樣調用setBackgroundResource()
  • 4.無需再次調用setContentView() ,這是在開始時設置的,並且您不想將其重置為剛構建的新視圖,就像您最初所做的那樣。
  • 5.立即嘗試將setAdapter()調用到ListView時,您應該不會崩潰,因為您沒有對不在內容視圖中的對象的引用。

     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); } 
  • 您試圖通過替換活動視圖來設置背景(這是setContentView()作用)。 稍后會導致空指針異常,因為已替換了舊布局(在XML中定義),因此列表視圖不再存在。

    相反,您應該獲得對現有根視圖的引用( ConstraintLayout ,盡管如果您只是設置背景,則可以將其引用為View ,而不必太具體),然后像這樣設置背景:

    findViewById(R.id.container).setBackgroundResource(R.drawable.unsafe);
    

    您還需要在現有布局XML中給包含的布局一個ID:

    <android.support.constraint.ConstraintLayout
        android:id="@+id/container"
        ... etc.
    

    暫無
    暫無

    聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

     
    粵ICP備18138465號  © 2020-2024 STACKOOM.COM