Отправить AlertDialog положительный вызов кнопки для пользовательского просмотра
Я пытаюсь отправить AlertDialog
положительное событие кнопки DialogFragment
на мой пользовательский вид CustomViewGroup
который встраивается трижды в Activity Overview
,
Я следовал руководству из https://developer.android.com/guide/topics/ui/dialogs.html, которое передает положительный вызов кнопки переопределенному методу onDialogPositiveClick
в деятельности. В моем случае нет необходимости обрабатывать это в обзоре действий.
Как можно вызвать метод processInput
пользовательского класса представления после положительного нажатия кнопки в AlertDialog?
Следующая структура должна дать вам общее представление (здесь обобщены названия):
ДЕЯТЕЛЬНОСТЬ
public class Overview extends AppCompatActivity implements MyDialogFragment.DialogListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.overview);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final CustomViewGroup cvg1 = (CustomViewGroup) findViewById(R.id.first_view_group);
// TODO Custom listener for onDialogPositiveClick needed?
// TODO CustomViewGroup 2 and 3
}
@Override
public void onDialogPositiveClick(DialogFragment dialog) {
// Is called for each of my three CustomViewGroup instances
// after clicking positive button in AlertDialog.
}
@Override
public void onDialogNegativeClick(DialogFragment dialog) {
// Not needed
}
}
с макетом обзора деятельности:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.my.project.views.CustomViewGroup
android:id="@+id/first_view_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<com.my.project.views.CustomViewGroup
android:id="@+id/second_view_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<com.my.project.views.CustomViewGroup
android:id="@+id/third_view_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
CUSTOM VIEW GROUP
public class CustomViewGroup extends LinearLayout {
public CustomViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
// process some attributes, not relevant here, remove from layout too
setOrientation(LinearLayout.HORIZONTAL);
final AppCompatActivity activity = (AppCompatActivity) getContext();
final LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.custom_view_group, this, true);
final Button mButton = (Button) getChildAt(1);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final DialogFragment dialog = CodeViewGroup.newInstance();
dialog.show(activity.getSupportFragmentManager(), "DialogFragment");
}
});
}
public static DialogFragment newInstance() {
DialogFragment dialog = new MyDialogFragment();
// pass arguments to dialog, not relevant here
return dialog;
}
public void processInput(DialogFragment dialog) {
// do some stuff with AlertDialog input
}
}
с макетом группы пользовательских видов:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/view_group_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/view_group_label_text" />
<Button
android:id="@+id/view_group_button"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/view_group_button_text" />
</merge>
MYDIALOGFRAGMENT
public class MyDialogFragment extends DialogFragment {
public interface DialogListener {
void onDialogPositiveClick(DialogFragment dialog);
void onDialogNegativeClick(DialogFragment dialog);
}
// Use this instance of the interface to deliver action events
DialogListener mListener;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getString(R.string.dialog_title))
.setView(R.layout.my_dialog_fragment)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogPositiveClick(MyDialogFragment.this);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogNegativeClick(MyDialogFragment.this);
}
});
// Create the AlertDialog object and return it
return builder.create();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
Activity activity;
// Verify that the host activity implements the callback interface
try {
if (context instanceof Activity) {
activity = (Activity) context;
// Instantiate the DialogListener so we can send events to the host
mListener = (DialogListener) activity;
} else {
mListener = (DialogListener) context;
}
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(context.toString()
+ " must implement DialogListener");
}
}
}
с разметкой фрагмента диалога "my_dialog_fragment":
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="@+id/dialog_edit_text"
android:inputType="textEmailAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Надеюсь, после переименования и объединения в опечатках нет опечаток:)
1 ответ
Почему вы не используете AlertDialog для отображения диалогового окна с пользовательским представлением?
AlertDialog.Builder alert = new AlertDialog.Builder (это);
Проверьте эту ссылку, чтобы узнать, как использовать AlertDialog с пользовательским представлением.
Это очень простой и эффективный метод.
Вы можете добавить положительную кнопку, отрицательную кнопку, нейтральную кнопку в диалог.
http://android.pcsalt.com/create-alertdialog-with-custom-layout-using-xml-layout/