无法解析方法setText(java.lang.String)

问题描述:

我已经看过类似于我得到的错误的其他问题,但我似乎无法找出这里的问题。我想要做的只是点击一个按钮并更改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(字符串)

我然后我看了一封教程,看不到我犯了什么错误,所以如果你们能帮助我,我会很感激!谢谢!

您可以更改

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

不客气:) –

您正在尝试视图对象上的setText()方法。您需要在TextView对象上调用它,或者将品牌声明更改为TextView,或者在调用setText()之前将您的品牌对象包装为TextView。

变化

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

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