使用对话框

时间:2017-07-31 00:52:41

标签: java android android-recyclerview android-alertdialog

我正在构建一个管理任务的应用程序。用户可以输入任务名称,设置优先级并添加该任务。我想要实现的是用户能够点击一个项目,启动一个警告对话框并从该对话框编辑该项目的详细信息(名称,优先级),单击“保存编辑”并保存该特定列表的编辑项目。但是,单击项目时不会启动警报对话框。我试图通过onclick调用包含对话框的方法:

recyclerView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                addTaskActivity.onClickEditTask(view);
                return true;
            }
        });

这是onClickEditText方法:

public class AddTaskActivity extends AppCompatActivity {
    ...

    public void onClickEditTask(View view){
        String editedInput = ((EditText)findViewById(R.id.edit_task)).getText().toString();
        if(editedInput.length() == 0){
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(getLayoutInflater().inflate(R.layout.edit_dialog, null))
                .create();
    }
    ...
}

目前,我想知道如何在每个项目点击时启动此方法,并将该项目的详细信息贴在已启动的对话框上。以下是我的相关课程:

AddTaskActivity.java:

public class AddTaskActivity extends AppCompatActivity {
    private int mPriority;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_task);

        ((RadioButton) findViewById(R.id.radButton1)).setChecked(true);
        mPriority = 1;
    }

    public void onClickAddTask(View view) {
        String input = ((EditText) findViewById(R.id.editTextTaskDescription)).getText().toString();
        if (input.length() == 0) {
            return;
        }
        ContentValues contentValues = new ContentValues();
        contentValues.put(TaskContract.TaskEntry.COLUMN_DESCRIPTION, input);
        contentValues.put(TaskContract.TaskEntry.COLUMN_PRIORITY, mPriority);
        Uri uri = getContentResolver().insert(TaskContract.TaskEntry.CONTENT_URI, contentValues);

        if(uri != null) {
            Toast.makeText(getBaseContext(), uri.toString(), Toast.LENGTH_LONG).show();
        }

        finish();

    }

    public void onClickEditTask(View view){
        String editedInput = ((EditText)findViewById(R.id.edit_task)).getText().toString();
        if(editedInput.length() == 0){
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(getLayoutInflater().inflate(R.layout.edit_dialog, null))
                .create();
    }

    public void onPrioritySelected(View view) {
        if (((RadioButton) findViewById(R.id.radButton1)).isChecked()) {
            mPriority = 1;
        } else if (((RadioButton) findViewById(R.id.radButton2)).isChecked()) {
            mPriority = 2;
        } else if (((RadioButton) findViewById(R.id.radButton3)).isChecked()) {
            mPriority = 3;
        }
    }
}

MainActivity.java:

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int LOADER_ID = 0;

    private CustomCursorAdapter customCursorAdapter;
    RecyclerView recyclerView;
    private AddTaskActivity addTaskActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.recyclerViewTasks);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        customCursorAdapter = new CustomCursorAdapter(this);
        recyclerView.setAdapter(customCursorAdapter);

        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
                int id = (int) viewHolder.itemView.getTag();

                String itemId = Integer.toString(id);
                Uri uri = TaskContract.TaskEntry.CONTENT_URI;
                uri = uri.buildUpon().appendPath(itemId).build();

                getContentResolver().delete(uri, null, null);

                getSupportLoaderManager().restartLoader(LOADER_ID, null, MainActivity.this);

            }
        }).attachToRecyclerView(recyclerView);

        recyclerView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                addTaskActivity.onClickEditTask(view);
                return true;
            }
        });

        FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.fab_btn);

        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent addTaskIntent = new Intent(MainActivity.this, AddTaskActivity.class);
                startActivity(addTaskIntent);
            }
        });

        getSupportLoaderManager().initLoader(LOADER_ID, null, this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        getSupportLoaderManager().restartLoader(LOADER_ID, null, this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, final Bundle loaderArgs) {

        return new AsyncTaskLoader<Cursor>(this) {

            Cursor cursor = null;

            @Override
            protected void onStartLoading() {
                if (cursor != null) {
                    deliverResult(cursor);
                } else {
                    forceLoad();
                }
            }
            @Override
            public Cursor loadInBackground() {

                try {
                    return getContentResolver().query(TaskContract.TaskEntry.CONTENT_URI,
                            null,
                            null,
                            null,
                            TaskContract.TaskEntry.COLUMN_PRIORITY);

                } catch (Exception e) {
                    Log.e(TAG, "Failed to load data.");
                    e.printStackTrace();
                    return null;
                }
            }

            public void deliverResult(Cursor data) {
                cursor = data;
                super.deliverResult(data);
            }
        };
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        customCursorAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
            customCursorAdapter.swapCursor(null);
        }

}

CustomCursorAdapter.java:

public class CustomCursorAdapter extends RecyclerView.Adapter<CustomCursorAdapter.TaskViewHolder> {
    private Cursor cursor;
    private Context con;

    public CustomCursorAdapter(Context context) {
        this.con = context;
    }

    @Override
    public TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(con).inflate(R.layout.task_layout, parent, false);
        return new TaskViewHolder(view);
    }

    @Override
    public void onBindViewHolder(TaskViewHolder holder, int position) {

        int index = cursor.getColumnIndex(TaskContract.TaskEntry._ID);
        int descriptionOfIndex = cursor.getColumnIndex(TaskContract.TaskEntry.COLUMN_DESCRIPTION);
        int priorityofIndex = cursor.getColumnIndex(TaskContract.TaskEntry.COLUMN_PRIORITY);

        cursor.moveToPosition(position);

        final int id = cursor.getInt(index);
        String description = cursor.getString(descriptionOfIndex);
        int priority = cursor.getInt(priorityofIndex);

        holder.itemView.setTag(id);
        holder.taskDescriptionView.setText(description);

        String priorityString = "" + priority;
        holder.priorityView.setText(priorityString);

        GradientDrawable priorityCircle = (GradientDrawable) holder.priorityView.getBackground();
        int priorityColor = getPriorityColor(priority);
        priorityCircle.setColor(priorityColor);

    }

    private int getPriorityColor(int priority) {
        int priorityColor = 0;

        switch(priority) {
            case 1: priorityColor = ContextCompat.getColor(con, R.color.materialRed);
                break;
            case 2: priorityColor = ContextCompat.getColor(con, R.color.materialOrange);
                break;
            case 3: priorityColor = ContextCompat.getColor(con, R.color.materialYellow);
                break;
            default: break;
        }
        return priorityColor;
    }

    @Override
    public int getItemCount() {
        if (cursor == null) {
            return 0;
        }
        return cursor.getCount();
    }

    public Cursor swapCursor(Cursor c) {
        if (cursor == c) {
            return null;
        }
        Cursor temp = cursor;
        this.cursor = c;

        if (c != null) {
            this.notifyDataSetChanged();
        }
        return temp;
    }

    class TaskViewHolder extends RecyclerView.ViewHolder {

        TextView taskDescriptionView;
        TextView priorityView;

        public TaskViewHolder(View itemView) {
            super(itemView);

            taskDescriptionView = (TextView) itemView.findViewById(R.id.taskDescription);
            priorityView = (TextView) itemView.findViewById(R.id.priorityTextView);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您似乎已省略通过编码builder.show();

显示更改对话框

此外可能需要设置一些按钮(您可以使用中性,正面和负面按钮,下面的示例只有中性按钮)。

您可能想要设置标题并使AlertDialog可取消。

您可能也遇到自定义布局的问题,因此下面的代码会忽略它并使用默认布局。

我相信以下代码将解决此问题: -

public void onClickEditTask(View view){
    String editedInput = ((EditText)findViewById(R.id.edit_task)).getText().toString();
    if(editedInput.length() == 0){
        return;
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Test");
    builder.setCancelable(true);
    builder.setNeutralButton("TEST", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Log.d("TAG","You click the TEST button of the dialog.");
        }
    });
    builder.show();
}

介绍自定义布局

以下是上述内容,但附加了一个基本的自定义视图,首先是布局,即 test_hi.xml : -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/buildertv"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_marginTop="30dp"
        android:layout_marginStart="30dp"
        android:layout_marginLeft="30dp"
        android:text="TEST"
        android:textColor="#ff557799"
        android:gravity="center"
        >
    </TextView>
</LinearLayout>

代码(即添加了 builder.setView(R.layout.test_hi); ): -

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(R.layout.test_hi);
    builder.setTitle("Test");
    builder.setCancelable(true);
    builder.setNeutralButton("TEST", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Log.d("TAG","You clicked the TEST button of the dialog.");
        }
    });
    builder.show();

运行上面应该是这样的(*运行前面的代码不会有中*测试**): -

enter image description here

单击底部(红色)测试将在日志中添加一行: -

....D/TAG: You clicked the TEST button of the dialog.

单击中性按钮时,您将使用要运行的代码替换Log.d("TAG","You clicked the TEST button of the dialog.");。如果您需要其他选项,则可以通过相应的方式添加builder.setPositiveButton(....builder.setNegativeButton(....,以类似的方式使用肯定否定按钮。