2012-05-23 35 views
0

我是Android新手。我試圖爲不同的字符串數組構成一個條件適配器(取決於一個String變量)。android:忽略微調條件數組適配器

TextView textPrompt; 
    textPrompt = (TextView)findViewById(R.id.textprompt); 
    final String acType = i.getStringExtra("type"); 
    textPrompt.setText(acType); 
    if (acType == "400G"){ 
    spinnerSurface = (Spinner) findViewById(R.id.spinnerSurface); 
    ArrayAdapter<CharSequence> adapterSurface = ArrayAdapter.createFromResource(
      this, R.array.surface_option_1, android.R.layout.simple_spinner_item); 
    adapterSurface.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    spinnerSurface.setAdapter(adapterSurface); 

    } 
    else if (acType != "400G"){ 
     spinnerSurface = (Spinner) findViewById(R.id.spinnerSurface); 
     ArrayAdapter<CharSequence> adapterSurface = ArrayAdapter.createFromResource(
       this, R.array.surface_option, android.R.layout.simple_spinner_item); 
     adapterSurface.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
     spinnerSurface.setAdapter(adapterSurface); 

    } 

    spinnerSurface.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() { 
     public void onItemSelected(AdapterView<?> parent, View v, 
       int position, long id) { 
      TextView tx = (TextView)v; 
      Log.i("\n\nid",String.valueOf(tx.getText())); 
     } 
     public void onNothingSelected(AdapterView<?> arg0) { 
      // TODO Auto-generated method stub 
     } 
    }); 

我使用textPrompt來檢查acType的值。無論acType是「400G」還是不是「400G」,程序都會將acType視爲不是「400G」,因此採用R.array.surface_option代替R.array.surface_option1。 請幫忙。

回答

0

它實際上是一個Java的問題,而不是Android的 - 你不應該使用==String我們比較,使用equals()代替

if (acType != null && acType.equals("400G")){ 
    ... 
} 
else { 
    ... 
} 

由於String s爲對象,==比較基準,其中最有可能會在不同的情況相同的字符串。

+0

弗拉基米爾,感謝您的及時回覆。我複製了你的代碼,但仍然無法工作。 – brompton

+0

多數民衆贊成在奇怪的。你確定你對'surface_option_1'的資源是正確的嗎?無論如何,你可以嘗試在if語句之前添加'Log.d(「EqualityTest」,acType +「等於400G:」+ acType.equals(「400G」));'以檢查它返回的內容。另外,如果'acType'可以是「400g」,考慮使用'equalsIgnoreCase(「400G」)'而不是'equals()' – Vladimir

+0

Vladmir,我查看了LogCat,它是「400G等於400G:false」 。所以acType真的是「400G」,但它說「假」?發生了什麼? – brompton