我正在制作一段语言游戏,其中将单词和翻译匹配。我需要存储先前单击的按钮,然后在单击另一个按钮后将它们进行比较,以及它们是否匹配以使其不可见。
但是我遇到了错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.Button.getText()' on a null object reference
在线String text = buf.getText().toString();
所有按钮均已定义。
@Override
public void onClick(View v) {
if (button_prev != 9) {
if (v.getId() != button_prev) {
Button buf = (Button) v.findViewById(button_prev);
String text = buf.getText().toString();
if (book_array.indexOf(text) - book_array.indexOf((String) ((Button) v).getText()) != 0) {
// book_array obj contains word and translating
i--;
v.findViewById(v.getId()).setVisibility(View.INVISIBLE);
v.findViewById(button_prev).setVisibility(View.INVISIBLE);
}
}
}
switch (v.getId()) {
// Storage the previously clicked the button in button_prev
case R.id.button1:
button_prev = Button_1.getId();
// button_prev = R.id.button1;
break;
case R.id.button2:
button_prev = Button_2.getId();
break;
case R.id.button3:
button_prev = Button_3.getId();
break;
case R.id.button4:
button_prev = Button_4.getId();
break;
case R.id.button5:
button_prev = Button_5.getId();
break;
case R.id.button6:
button_prev = Button_6.getId();
break;
case R.id.button7:
button_prev = Button_7.getId();
break;
case R.id.button8:
button_prev = Button_8.getId();
break;
default:
break;
也许有人可以修复代码?有什么正确的方法来存储单击的按钮吗?
答案 0 :(得分:1)
您可以为lastclicked视图声明POJO,如下所示,以存储lastClicked视图。
public class LastViewClicked {
private View view;
public View getView() {
return view;
}
public void setView(View view) {
this.view = view;
}
}
现在,当您单击任何按钮时,使用setView方法更新LastClickedView中的视图对象,并且当您需要知道最后单击的按钮是什么时,您将创建一个switch语句,将所有Id用作大小写,并且如果匹配则可以做你的手术。
// This Function gets the last clicked item which has opened up the Alert Dialog for
// selection and Updates its UI...
private void UpdateLastClickedView(int position, ArrayAdapter arrayAdapter) {
View v = lastViewClicked.getView();
// cast according to your views...
AppCompatTextView appCompatTextView = (AppCompatTextView) v;
// do your operation...
switch(appCompatTextView.getId()){
case R.id.tv1:
// hide or whatever you want to do...
break;
case R.id.tv2:
// hide or whatever you want to do...
break;
}
}
答案 1 :(得分:0)
在活动或片段中将button_prev声明为字段,并使用getter和setter在onclick内对其进行访问。
答案 2 :(得分:0)