2015-12-02 96 views
3

我已經看過類似於我得到的錯誤的其他問題,但我似乎無法找出這裏的問題。我想要做的只是點擊一個按鈕並更改TextView的文本。無法解析方法setText(java.lang.String)

我的代碼如下:

public class FindBeerActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_find_beer); 
} 
//call when the user clicks the button 
public void onClickFindBeer(View view) { 

    //Get a reference to the TextView 
    View brands = (TextView) findViewById(R.id.brands); 

    //Get a reference to the Spinner 
    Spinner color = (Spinner) findViewById(R.id.color); 

    //Get the selected item in the Spinner 
    String beerType = String.valueOf(color.getSelectedItem()); 

    //Display the beers. This is where the error is 
    brands.setText(beerType); 

    } 
} 

和XML

<TextView 
    android:id="@+id/brands" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@id/find_beer" 
    android:layout_alignStart="@id/find_beer" 
    android:layout_below="@id/find_beer" 
    android:layout_marginTop="18dp" 
    android:text="@string/brands" /> 

當我建立我得到:「錯誤:找不到符號法的setText(字符串)

我然後我看了一封教程,看不到我犯了什麼錯誤,所以如果你們能幫助我,我會很感激!謝謝!

回答

7

您可以更改

View brands = (TextView) findViewById(R.id.brands); 

TextView brands = (TextView) findViewById(R.id.brands); 

OR變化

brands.setText(beerType); 

((TextView)brands).setText(beerType); 

我無論哪種方式,您需要撥打撥打setText方法TextView參考

+0

是啊,有錯誤。我不知道爲什麼我將它創建爲視圖而不是TextView!謝謝! – jblittle

+0

不客氣:) –

0

您正在嘗試視圖對象上的setText()方法。您需要在TextView對象上調用它,或者將品牌聲明更改爲TextView,或者在調用setText()之前將您的品牌對象包裝爲TextView。

0

變化

View brands = (TextView) findViewById(R.id.brands); 

TextView brands = (TextView) findViewById(R.id.brands); 
相關問題