[英]Android/Java question. How are these two decision trees different?
我對這兩個決策樹有何不同感到非常困惑。 我正在構建一個應用程序,它需要根據從 ListView 中選擇的 position 來決定加載哪個視圖。 我嘗試將邏輯構建到單個 controller 模塊中,發現 switch-case 會導致 NullPointerException 和 FC,而 if-else 會完美運行。 誰能告訴我為什么? 我在 C 和 C++ 方面有很強的背景,並且習慣於能夠輕松地將開關重寫為 if-else,反之亦然。
定義的變量:
private final int VALUEA = 0;
private final int VALUEB = 1;
private final int VALUEC = 2;
開關盒:
TextView t = new TextView(null);
switch(value){
case VALUEA:
setContentView(R.layout.valuealayout);
t = (TextView) findViewById(R.id.valuealayout);
t.findViewById(R.id.valuealayout);
break;
case VALUEB:
setContentView(R.layout.valueblayout);
t = (TextView) findViewById(R.id.valueblayout);
t.findViewById(R.id.valueblayout);
break;
case VALUEC:
setContentView(R.layout.valueclayout);
t = (TextView) findViewById(R.id.valueclayout);
t.findViewById(R.id.valueclayout);
break;
default:
break;
}
上面的塊將導致 NullPointerException。
如果別的:
if(value == VALUEA ){
setContentView(R.layout.valuealayout);
TextView t = (TextView) findViewById(R.id.valuealayout);
t.findViewById(R.id.valuealayout);
}else if(value == VALUEB){
setContentView(R.layout.valueblayout);
TextView t = (TextView) findViewById(R.id.valueblayout);
t.findViewById(R.id.valueblayout);
}else if(value == VALUEC){
setContentView(R.layout.valueclayout);
TextView t = (TextView) findViewById(R.id.valueclayout);
t.findViewById(R.id.valueclayout);
}else{
}
這個版本完美運行。 第二個塊是否工作是因為一些時髦的 Java 范圍規則允許決策樹的每個分支以第一個塊沒有的方式創建和正確初始化 TextView?
TextView
構造函數需要一個Context
。 你不能只通過它null
。 而是這樣做:
TextView t = null;
switch(value){
case VALUEA:
setContentView(R.layout.valuealayout);
t = (TextView) findViewById(R.id.valuealayout);
t.findViewById(R.id.valuealayout);
break;
case VALUEB:
setContentView(R.layout.valueblayout);
t = (TextView) findViewById(R.id.valueblayout);
t.findViewById(R.id.valueblayout);
break;
case VALUEC:
setContentView(R.layout.valueclayout);
t = (TextView) findViewById(R.id.valueclayout);
t.findViewById(R.id.valueclayout);
break;
default:
break;
}
我猜是這條線
TextView t = new TextView(null);
那就是問題所在。 將 null 傳遞給TextView
構造函數是否合法?
在沒有看到堆棧跟蹤的情況下,這只是在黑暗中刺傷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.