简体   繁体   中英

Cannot resolve method setText(java.lang.String)

I've looked at other questions similar to the error I'm getting, but I can't seem to figure out the issue here. All I'm trying to do is click a button and change a TextView's text.

My code is as follows:

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);

  }
}

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

When I build I get: "error: cannot find symbol method setText(String)

I'm following a tutorial to the letter and I can't see where I've made a mistake, so I'd appreciate it if you guys could help me out! Thanks!

You can either change

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

to

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

OR change

brands.setText(beerType);

to

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

In either ways, you need to call the setText method on a TextView reference .

You are trying setText() method on a view object. You need to call it on a TextView object.so either change the declaration of brands to TextView or just wrap ur brands object to TextView before calling setText() over it.

Change

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

To

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM