簡體   English   中英

如何將數據從活動傳遞到DialogFragment

[英]How to pass data from Activity to DialogFragment

我知道有一些關於如何將數據從活動傳遞到對話框的示例(即Bundle或Intent)。 但是,我嘗試的所有方法均無效。 我不斷收到NPE和"Unable to find explicit activity class"錯誤。 即使當我使用對話框構建超基本活動時,它也不起作用。 我必須在代碼中添加什么才能使其正常工作?

主要活動:

public class MainActivity extends AppCompatActivity {

  Button button;
  String textIWantToSee;

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

    button = (Button) findViewById(R.id.button);

    textIWantToSee = "If this is the text I want to pass form this activity to the Fragment";

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


        }
    });
  }
}

對話:

public class Dialog extends DialogFragment {

  TextView textView;

  @Override
  public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View v = inflater.inflate(R.layout.dialog_layout, null);

    textView = (TextView) v.findViewById(R.id.textView);

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(v);

    return builder.create();
  }
}

更新

主要活動:

public class MainActivity extends AppCompatActivity {

TextView tvIntent;
Button button;
String textIWantToSee;

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

    tvIntent = (TextView) findViewById(R.id.tvIntent);
    button = (Button) findViewById(R.id.button);

    textIWantToSee = "If this is the text I want to pass form this activity to the Fragment";
    tvIntent.setText(textIWantToSee);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String intent = String.valueOf(tvIntent);
            Intent intentToDialog = new Intent(MainActivity.this, Dialog.class);
            intentToDialog.putExtra("keyForIntent", intent);
            startActivity(intentToDialog); //Here is the exception

        }
    });
}

對話框:

public class Dialog extends DialogFragment {

TextView textView;
String intent;

@Override
public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View v = inflater.inflate(R.layout.dialog_layout, null);

    textView = (TextView) v.findViewById(R.id.textView);
    Intent intentFromDialog = new Intent(getActivity().getApplicationContext(),MainActivity.class);
    intent = intentFromDialog.getStringExtra("keyForIntent");
    textView.setText(intent);

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(v);

    return builder.create();
}

}

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: nl.blogvandetoekomst.passdatafromactivitytodialog, PID: 2947
              android.content.ActivityNotFoundException: Unable to find explicit activity class {nl.blogvandetoekomst.passdatafromactivitytodialog/nl.blogvandetoekomst.passdatafromactivitytodialog.Dialog}; have you declared this activity in your AndroidManifest.xml?
                  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1794)
                  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512)
                  at android.app.Activity.startActivityForResult(Activity.java:3917)
                  at android.app.Activity.startActivityForResult(Activity.java:3877)
                  at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:842)
                  at android.app.Activity.startActivity(Activity.java:4200)
                  at android.app.Activity.startActivity(Activity.java:4168)
                  at nl.blogvandetoekomst.passdatafromactivitytodialog.MainActivity$1.onClick(MainActivity.java:36)
                  at android.view.View.performClick(View.java:5198)
                  at android.view.View$PerformClick.run(View.java:21147)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

表現:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nl.blogvandetoekomst.passdatafromactivitytodialog">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

這是將數據從Activity傳遞到DialogFragment的方法:

MainActivity.java

public class MainActivity extends AppCompatActivity {

Button button;
String textIWantToSee;

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

    button = (Button) findViewById(R.id.button);

    textIWantToSee = "If this is the text I want to pass form this activity to the Fragment";

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Dialog dialogFragment = new Dialog();
            Bundle bundle = new Bundle();
            bundle.putString("TEXT",textIWantToSee);
            dialogFragment.setArguments(bundle);
            dialogFragment.show((MainActivity.this).getSupportFragmentManager(),"Image Dialog");

        }
    });
}
}

Dialog.java

public class Dialog extends DialogFragment {

TextView textView;

@Override
public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View v = inflater.inflate(R.layout.dialog_layout, null);

    Bundle bundle = getArguments();
    String imageLink = bundle.getString("TEXT","");

    textView = (TextView) v.findViewById(R.id.textView);

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(v);

    return builder.create();
}
}

您的對話框片段需要一個托管活動,它需要在一個活動中膨脹。

要在MainActivity中膨脹/顯示DialogFragment,請使用:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Bundle bundle = new Bundle(); //Bundle containing data you are passing to the dialog
        bundle.putString("text", textIWantToSee);

        Dialog dialog = new Dialog(); //Create a new Dialog
        dialog.setArguments(bundle);

        dialog.show(getSupportFragmentManager(), "MY_DIALOG_TAG"); //Inflate the dialog
    }
});

如果您使用的是支持庫,則應使用android.support.v4.app.DialogFragment而不是android.app.Dialog。 另外,您可以張貼用於顯示對話框的部分代碼嗎?

然后,必須使用OBX指出的DialogFragment框架版本:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    Button button;
    String textIWantToSee;

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

        button = (Button) findViewById(R.id.button); 

        textIWantToSee = "If this is the text I want to pass form this activity to the Fragment";

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Dialog dialogFragment = new Dialog();
                Bundle bundle = new Bundle();
                bundle.putString("TEXT",textIWantToSee);
                dialogFragment.setArguments(bundle);
                dialogFragment.show(getFragmentManager(),"Image Dialog");
            }
        });
    }
}

Dialog.java

public class Dialog extends DialogFragment {

    TextView textView;

    @Override
    public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {

        LayoutInflater inflater = getActivity().getLayoutInflater();
        View v = inflater.inflate(R.layout.dialog_layout, null);

        Bundle bundle = getArguments();
        String imageLink = bundle.getString("TEXT","");

        textView = (TextView) v.findViewById(R.id.textView);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(v);
        return builder.create();
    }
}

這種方式對我來說很好。

編輯:

在onClick中執行此操作時:

Intent intentToDialog = new Intent(MainActivity.this, Dialog.class);
intentToDialog.putExtra("keyForIntent", intent);
startActivity(intentToDialog); //Here is the exception

您沒有啟動活動,Dialog.class是擴展的DialogFragment,無法顯示啟動活動的對話框。 試試我發布的最后一個代碼。

使用Dialog片段的newInstance。 參考: https : //developer.android.com/reference/android/app/DialogFragment.html

   static MyDialogFragment newInstance(int num) {
    MyDialogFragment f = new MyDialogFragment();

    // Supply num input as an argument.
    Bundle args = new Bundle();
    args.putInt("num", num);
    f.setArguments(args);

    return f;
}

如果您使用的是Kotlin,請嘗試在隨播對象中定義newInstance

companion object {
        fun newInstance(num: Int): MyDialogFragment{
            val f = DimensionDialogFragment()
            val args = Bundle()
            args.putInt("num", num)
            f.setArguments(args)

            return f
        }
    }

您可以直接在“活動”中創建對話框:

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        LayoutInflater inflater = MainActivity.this.getLayoutInflater();
        View v = inflater.inflate(R.layout.dialog_layout, null);

        TextView textView = (TextView) v.findViewById(R.id.textView);
        textView.setText(textIWantToSee);

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setView(v);
        builder.show();

        }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM