单击布局中的按钮时,如何显示警告对话框?下面的代码如果按钮来自菜单但我需要它从布局按钮起作用。我尝试用case R.id.action_add_task
替换case R.id.button
(按钮是布局按钮的名称),但它没有'工作。任何帮助将不胜感激。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_add_task:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add something");
builder.setMessage("What do you nat to do?");
final EditText inputField = new EditText(getActivity());
builder.setView(inputField);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Get user input
String inputTask = inputField.getText().toString();
//Get DBHelper to write to database
TaskDBHelper helper = new TaskDBHelper(getActivity());
SQLiteDatabase db = helper.getWritableDatabase();
//Put in the values within a ContentValues.
ContentValues values = new ContentValues();
values.clear();
values.put(TaskContract.TaskEntry.COLUMN_TASK, inputTask);
//Insert the values into the Table for Tasks
db.insertWithOnConflict(
TaskContract.TaskEntry.TABLE_NAME,
null,
values,
SQLiteDatabase.CONFLICT_IGNORE);
//Query database again to get updated data
Cursor cursor = db.query(TaskContract.TaskEntry.TABLE_NAME,
new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COLUMN_TASK},
null, null, null, null, null);
//Swap old data with new data for display
mTaskAdapter.swapCursor(cursor);
}
});
builder.setNegativeButton("Cancel", null);
builder.create().show();
return true;
}
return super.onOptionsItemSelected(item);
}
答案 0 :(得分:1)
如果您想在按钮上执行某些操作,请使用:
RecyclerView
这适用于您活动中的任何按钮(不适用于操作栏图标和溢出菜单项)
答案 1 :(得分:0)
像这样用XML声明Button
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="handleButton"
android:text="Button" />
在Java类中,通过使用在Xml中声明的onClick属性为按钮创建方法来处理单击
`public void handleButton(View view) {
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("Your title here");
dialog.setMessage("Message body");
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
return ;
}