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

5

我看过其他类似于我遇到的错误的问题,但是我似乎无法解决这个问题。我所尝试的只是点击一个按钮并更改TextView的文本。

我的代码如下:

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" />

在构建时我遇到了以下错误:"error: cannot find symbol method setText(String)"

我按照教程的要求进行操作,但是我没有发现自己哪里出了错。所以希望大家能帮我解决这个问题!谢谢!

3个回答

8

您可以选择更改

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

为了

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

或者更改

brands.setText(beerType);

为了

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

无论哪种方式,您都需要在TextView引用上调用setText方法。

是的,这就是错误所在。我不确定为什么我把它创建为View而不是TextView!谢谢! - jblittle

0
你正在尝试在一个视图对象上调用setText()方法。你需要在TextView对象上调用它。所以要么将声明的brands更改为TextView,要么在调用setText()之前将你的brands对象包装到TextView中。

0

更改

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接