我有一个问题,我相信解决方案相对简单,但我错过了一些东西。基本上我的程序从用户端的流程是我有一个“主屏幕”,其中屏幕上的按钮是半透明的并且没有响应,直到从下拉菜单(微调器小部件)中选择一个项目。在代码方面,我在 XML 文件中定义了布局,然后用 Java 编写所有相关联的内容。所以在 onCreate() 方法中,我已经像这样初始化了按钮:
public void initButtons() {
Button buttonOne = (Button) findViewById(R.id.button_one);
Button buttonTwo = (Button) findViewById(R.id.button_two);
Button buttonThree = (Button) findViewById(R.id.button_three);
Button buttonFour = (Button) findViewById(R.id.button_four);
buttonOne.setClickable(false);
buttonTwo.setClickable(false);
buttonThree.setClickable(false);
buttonFour.setClickable(false);
buttonOne.setAlpha(0.5f);
ButtonTwo.setAlpha(0.5f);
buttonThree.setAlpha(0.5f);
buttonFour.setAlpha(0.5f);
}
这很好用,但我想在从我的微调器中选择一个项目之后设置一些 onClickListeners。所以我的活动类实现了 onItemClickListener 并且我的代码中有以下回调:
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
if (position != 0) {
selectedTown = parent.getItemAtPosition(position).toString();
CharSequence text = "You've Selected " + selectedItem;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(SampleUI.this, text, duration);
toast.show();
itemSelected = true;
handler.sendEmptyMessage(1);
} else {
itemSelected = false;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
boolean itemSelected 在活动类中具有全局范围,Toast 用于调试目的而不是必需的。但我遇到的问题是,当我在微调器上的项目(位置 0 以下)被选中后尝试更改按钮时。我有一个这样定义的消息处理程序:
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if ((itemSelected == true) && (buttonsActivated == false)) {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(SampleUI.this,"Activating Buttons", duration);
toast.show();
activateButtons();
}
super.handleMessage(msg);
}
};
这个处理程序正常工作,直到我调用了如下所示的 activateButtons() 方法:
public void activateButtons() {
buttonOne.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Code to respond to buttonClick
}
});
}
每当我尝试与回调或处理程序之一中的 UI 元素进行交互时,我都会收到 Java NULL 指针异常。我很确定这是我错过的相当简单和基本的东西,但我似乎无法发现问题。如果有人有任何想法,我很想听听你的意见 :) 将 SJ