我在自定义列表视图中有3个切换按钮。如何为这些按钮实现onclick侦听器。我不能在适配器类中这样做,因为它没有onCreate。我被困住,因为我不知道如何访问列表视图的子按钮。
mytoggle1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
Toast.makeText(getContext(), "This Level is Locked", Toast.LENGTH_SHORT).show();
} else {
mytoggle1.setChecked(true);
String str = (String) mytoggle1.getText();
int curr_level = Integer.parseInt(str);
SharedPreferences sharedpreference = getContext().getSharedPreferences(
getString(R.string.preference_key), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreference.edit();
editor.putInt(getString(R.string.current_level), curr_level);
editor.apply();
Intent i = new Intent(this, GamePage.class);
startActivity(i);
}
}
});
这是我在getView方法中的监听器。这是错误的,它无法解析getString(),startActivity(),在行Intent i = new Intent(this,GamePage.class)中它给出了错误,我们无法解析构造函数Intent。
答案 0 :(得分:2)
您可以在适配器的getView中执行此操作
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
LayoutInflater layoutInflater = context.getLayoutInflater();
convertView = layoutInflater.inflate(R.layout.item, null);
}
Button button1 = (Button) convertView.findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
}
});
return convertView;
}
答案 1 :(得分:0)
你应该这样:
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.listview, parent, false);
Button lvButton = (Button) row.findViewById(R.id.lvButton);
lvButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//...
}
});
}
并且不要忘记在xml上定义这些以防止listview无法点击
ListView - >机器人:可聚焦="真"
按钮 - >机器人:可聚焦="假"