新手在这里。两个按钮,note1和note2,在单击时将显示相同的AlertDialog,然后分开存储用户的选择。试图避免重复的代码我遇到问题,我很难有一个简单的方法,但我找不到它。感谢
@Override
public void onClick(View v) {
// respond to clicks
if (v.getId() == R.id.btnNote1) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.selNoteBtn).setSingleChoiceItems(notes, 0,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
note1.setText(which);
}
});
}
else if (v.getId() == R.id.btnNote2) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.selNoteBtn).setSingleChoiceItems(notes, 0,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
note2.setText(which);
}
});
}
}
答案 0 :(得分:0)
你可以在noteN.setText(which);
语句之前将条件置于onClick函数中,因为这是两者之间唯一的变化。
答案 1 :(得分:0)
你可以设置EditText(或者说note1和note2基于ID和按钮Listener中的用法。
@Override
public void onClick(View v) {
// respond to clicks
EditText note;
if (v.getId() == R.id.btnNote1) {
note = note1;
} else {
note = note2;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.selNoteBtn).setSingleChoiceItems(notes, 0,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
note.setText(which);
}
});
}
答案 2 :(得分:0)
您可以创建一个最终的ViewID变量,以便您可以在onClick()
@Override
public void onClick(View v) {
final int viewID = v.getId();
// respond to clicks
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.selNoteBtn).setSingleChoiceItems(notes, 0,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if(viewID == R.id.btnNote1) {
note1.setText(which);
} else {
note2.setText(which);
}
}
}
);
}
答案 3 :(得分:0)
@Override
public void onClick(View v) {
// respond to clicks
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.selNoteBtn).setSingleChoiceItems(notes, 0,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (v.getId() == R.id.btnNote1)
note1.setText(which);
else
note2.setText(which);
}
});
}
答案 4 :(得分:0)
如果您想对 OTHER 项目使用onClick(),请使用此方法。
@Override
public void onClick(View v) {
// respond to clicks
if (v.getId() == R.id.btnNote1 || v.getId() == R.id.btnNote2) {
showAlerts(View v)
}
}
private void showAlerts(View v)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.selNoteBtn).setSingleChoiceItems(notes, 0,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if(v.getId() == R.id.btnNote2)note2.setText(which);
else if(v.getId() == R.id.btnNote1)note1.setText(which);
}
});
}