android - 表示中 - settargetfragment
フラグメントからダイアログを表示しますか? (5)
DialogFragmentを使用することが最善の選択肢であるという以前に受け入れられた答えを慎重に疑う必要があります。 DialogFragmentの意図された(主な)目的は、表示するダイアログを持つフラグメントを表示するのではなく、ダイアログ自体であるフラグメントを表示することです。
私は、ダイアログとフラグメントの間の仲介にフラグメントのアクティビティを使用する方が望ましい選択肢だと考えています。
私は定期的なダイアログを表示する必要があるいくつかの断片があります。 これらのダイアログでは、ユーザーは「はい/いいえ」の回答を選択することができ、それに応じてフラグメントが動作します。
さて、 Fragment
クラスにはオーバーライドするonCreateDialog()
メソッドがありません。そのため、 Activity
を含む外部にダイアログを実装する必要があります。 大丈夫ですが、 Activity
は、選択した回答をどうにかフラグメントに戻す必要があります。 もちろん、ここではコールバックパターンを使用することができます。そのため、フラグメントはActivity
にリスナークラスで登録され、 Activity
はそれを介して答えを返すでしょう。
しかし、これはフラグメントに「シンプルな」イエス・ノー・ダイアログを表示するという単純な作業にとっては非常に難しいようです。 また、私のFragment
は自己完結型ではありません。
これを行うためのよりクリーンな方法がありますか?
編集:
この質問に対する答えは、DialogFragmentsを使ってFragmentsのダイアログを表示する方法を詳しく説明していません。 だからAFAIK、行く道は:
- フラグメントを表示する。
- 必要に応じて、DialogFragmentをインスタンス化します。
-
.setTargetFragment()
を.setTargetFragment()
、このDialogFragmentのターゲットとして元のフラグメントを設定し.setTargetFragment()
。 - 元のフラグメントから.show()でDialogFragmentを表示します。
- ユーザーがこのDialogFragmentでいくつかのオプションを選択し、元のFragmentにこの選択について通知すると(たとえば、ユーザーが「はい」をクリックした)、元のフラグメントの参照を.getTarget()で取得できます。
- DialogFragmentを閉じます。
yes / no DialogFragmentの完全な例を次に示します。
クラス:
public class SomeDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("Title")
.setMessage("Sure you wanna do this!")
.setNegativeButton(android.R.string.no, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do nothing (will close dialog)
}
})
.setPositiveButton(android.R.string.yes, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do something
}
})
.create();
}
}
ダイアログを開始するには:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Create and show the dialog.
SomeDialog newFragment = new SomeDialog ();
newFragment.show(ft, "dialog");
クラスにonClickListenerを実装させ、埋め込みリスナーの代わりにそのクラスを使用することもできます。
アクティビティへのコールバック
コールバックを実装したい場合は、これがどのように行われているかあなたのアクティビティで:
YourActivity extends Activity implements OnFragmentClickListener
そして
@Override
public void onFragmentClick(int action, Object object) {
switch(action) {
case SOME_ACTION:
//Do your action here
break;
}
}
コールバッククラス:
public interface OnFragmentClickListener {
public void onFragmentClick(int action, Object object);
}
次に、フラグメントからコールバックを実行するには、リスナーが次のようにアタッチされていることを確認する必要があります。
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentClickListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement listeners!");
}
}
コールバックは次のように実行されます。
mListener.onFragmentClick(SOME_ACTION, null); // null or some important object as second parameter.
私にとっては、
MyFragment:
public class MyFragment extends Fragment implements MyDialog.Callback
{
ShowDialog activity_showDialog;
@Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
activity_showDialog = (ShowDialog)activity;
}
catch(ClassCastException e)
{
Log.e(this.getClass().getSimpleName(), "ShowDialog interface needs to be implemented by Activity.", e);
throw e;
}
}
@Override
public void onClick(View view)
{
...
MyDialog dialog = new MyDialog();
dialog.setTargetFragment(this, 1); //request code
activity_showDialog.showDialog(dialog);
...
}
@Override
public void accept()
{
//accept
}
@Override
public void decline()
{
//decline
}
@Override
public void cancel()
{
//cancel
}
}
MyDialog:
public class MyDialog extends DialogFragment implements View.OnClickListener
{
private EditText mEditText;
private Button acceptButton;
private Button rejectButton;
private Button cancelButton;
public static interface Callback
{
public void accept();
public void decline();
public void cancel();
}
public MyDialog()
{
// Empty constructor required for DialogFragment
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.dialogfragment, container);
acceptButton = (Button) view.findViewById(R.id.dialogfragment_acceptbtn);
rejectButton = (Button) view.findViewById(R.id.dialogfragment_rejectbtn);
cancelButton = (Button) view.findViewById(R.id.dialogfragment_cancelbtn);
acceptButton.setOnClickListener(this);
rejectButton.setOnClickListener(this);
cancelButton.setOnClickListener(this);
getDialog().setTitle(R.string.dialog_title);
return view;
}
@Override
public void onClick(View v)
{
Callback callback = null;
try
{
callback = (Callback) getTargetFragment();
}
catch (ClassCastException e)
{
Log.e(this.getClass().getSimpleName(), "Callback of this class must be implemented by target fragment!", e);
throw e;
}
if (callback != null)
{
if (v == acceptButton)
{
callback.accept();
this.dismiss();
}
else if (v == rejectButton)
{
callback.decline();
this.dismiss();
}
else if (v == cancelButton)
{
callback.cancel();
this.dismiss();
}
}
}
}
アクティビティ:
public class MyActivity extends ActionBarActivity implements ShowDialog
{
..
@Override
public void showDialog(DialogFragment dialogFragment)
{
FragmentManager fragmentManager = getSupportFragmentManager();
dialogFragment.show(fragmentManager, "dialog");
}
}
DialogFragmentレイアウト:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/dialogfragment_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:text="@string/example"/>
<Button
android:id="@+id/dialogfragment_acceptbtn"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_below="@+id/dialogfragment_textview"
android:text="@string/accept"
/>
<Button
android:id="@+id/dialogfragment_rejectbtn"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_alignLeft="@+id/dialogfragment_acceptbtn"
android:layout_below="@+id/dialogfragment_acceptbtn"
android:text="@string/decline" />
<Button
android:id="@+id/dialogfragment_cancelbtn"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:layout_alignLeft="@+id/dialogfragment_rejectbtn"
android:layout_below="@+id/dialogfragment_rejectbtn"
android:text="@string/cancel" />
<Button
android:id="@+id/dialogfragment_heightfixhiddenbtn"
android:layout_width="200dp"
android:layout_height="20dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:layout_alignLeft="@+id/dialogfragment_cancelbtn"
android:layout_below="@+id/dialogfragment_cancelbtn"
android:background="@android:color/transparent"
android:enabled="false"
android:text=" " />
</RelativeLayout>
dialogfragment_heightfixhiddenbtn
という名前が示すように、私はちょうどwrap_content
と言っていたにもかかわらず、ボトムボタンの高さが半分になってしまったことを修正する方法をwrap_content
られなかったので、代わりに半分にカットされる隠しボタンを追加しました。 ハックのために申し訳ありません。
私は自分で初心者です。私は理解したり実装したりできる満足のいく答えを見つけられませんでした。
だからここに私が私が欲しいものを達成するのを本当に助けた外部リンクがあります。 それは非常にまっすぐ進み、従うのも簡単です。
http://www.helloandroid.com/tutorials/how-display-custom-dialog-your-android-application
私がコードを達成しようとしたもの:
私は断片をホストするMainActivityを持っています。 レイアウトの上にダイアログを表示してユーザの入力を求め、それに応じて入力を処理することを希望しました。 スクリーンショットを見る
ここで私のフラグメントのonCreateViewがどのように見えるのですか
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_activity, container, false);
Button addTransactionBtn = rootView.findViewById(R.id.addTransactionBtn);
addTransactionBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_trans);
dialog.setTitle("Add an Expense");
dialog.setCancelable(true);
dialog.show();
}
});
それがあなたを助けることを願っています
混乱があれば教えてください。 :)
public void showAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View alertDialogView = inflater.inflate(R.layout.test_dialog, null);
alertDialog.setView(alertDialogView);
TextView textDialog = (TextView) alertDialogView.findViewById(R.id.text_testDialogMsg);
textDialog.setText(questionMissing);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
.test_dialogはxmlカスタムのものです