4 回答
TA贡献1784条经验 获得超8个赞
您需要在调用 voiceBtn = findViewById(R.id.goToVoice) 之前调用 setContentView(); 由于您未指定布局,因此 findViewById 方法将不会获取按钮实例
public class RecogActivity extends AppCompatActivity {
private Button voiceBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the layout first
setContentView(R.layout.YOUR_LAYOUT_XML_FILE_NAME)
voiceBtn = findViewById(R.id.goToVoice);
// some unrelated code
configureActivitySwap();
}
public void configureActivitySwap(){
// Button voiceBtn = (findViewById(R.id.goToVoice));
voiceBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
TA贡献1752条经验 获得超4个赞
我猜试试)在你的// some unrelated codeis containssetContentView方法中?
public class RecogActivity extends AppCompatActivity {
private Button voiceBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
voiceBtn = findViewById(R.id.goToVoice);
setContentView(R.layout.some_layout)
// some unrelated code
configureActivitySwap();
}
public void configureActivitySwap(){
// Button voiceBtn = (findViewById(R.id.goToVoice));
voiceBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
}
你抓到 NPE 是因为findViewById调用了膨胀的视图。在第一种情况下,你findViewById之前一直在打电话,但得到了例外。setContentView而在第二种情况下configureActivitySwap,那是追赶setContentView。setContentView之后移动super.onCreate(savedInstanceState),一切都会正常工作。
TA贡献1804条经验 获得超7个赞
voiceBtn = (Button) findViewById(R.id.goToVoice);
用上面的替换你的onCreate()
方法中的语句。它应该工作。
并使用
super.finish() instead of finish()
添加回答
举报