public class FindBeerActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_beer);
}
Spinner color = (Spinner) findViewById(R.id.color);
TextView brands = (TextView) findViewById(R.id.brands);
public void onClickFindBeer(View view) {
//Get the selected item in the spinner
String beerType = String.valueOf(color.getSelectedItem());
//Display the selected item
brands.setText(beerType);
}
}
我知道如果将findviewbyid
移动到onclick
方法中,代码将运行良好但我想理解为什么它不会以这种方式工作,即使已经调用了setContentView 。
答案 0 :(得分:2)
也许你放错了结束的大括号。这个应该修复你的NPE。
public class FindBeerActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_beer);
Spinner color = (Spinner) findViewById(R.id.color);
TextView brands = (TextView) findViewById(R.id.brands);
}
public void onClickFindBeer(View view) {
//Get the selected item in the spinner
String beerType = String.valueOf(color.getSelectedItem());
//Display the selected item
brands.setText(beerType);
}
}