从另一个活动访问DialogFragment视图

时间:2016-03-02 16:12:17

标签: android view android-dialogfragment

我有一个扩展DialogFragment的类,它使用布局过热来显示不同的视图

public class MyDialog extends DialogFragment {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater layoutInflater = getActivity().getLayoutInflater();
    builder.setView(layoutInflater.inflate(R.layout.dialog_pin_layout,null))
            .setTitle("Enter info")
            ...
    return builder.create();
}

布局仅包含EditText

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/infoEdit" />

</RelativeLayout>

现在我尝试从我的MainActivity中自动填充此EditText

//When the user clicks on the button in the main activity, prompt MyDialog
ImageButton usr = (ImageButton)findViewById(R.id.usrImageButton);

 usr.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new MyDialog().show(getFragmentManager(),"fragment_info");

            //If userInfo exists, fill the DialogFragment's EditText
            if(userInfo!=null){
               EditText txt = (EditText)findViewById(R.id.infoEdit);
               txt.setText(userInfo.toString());
            }
        }
    });

当我运行应用程序时,单击该按钮会抛出由txt.setText(userInfo.toString());引起的NullPointerException。 通过使用调试器,我发现(EditText)findViewById(R.id.infoEdit)返回null,我想我无法使用findViewById访问MainActivity中的EditText视图。有办法吗?

1 个答案:

答案 0 :(得分:1)

您最好的选择是将String传递给DialogFragment并将其设置为:

public class MyDialog extends DialogFragment {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState){

    Bundle args = getArguments();
    String text = args.getString("TEXT_TO_SET");

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater layoutInflater = getActivity().getLayoutInflater();
    View view = layoutInflater.inflate(R.layout.dialog_pin_layout,null);
    EditText txt = (EditText) view.findViewById(R.id.infoEdit);
    txt.setText(text);

    builder.setView(view)
            .setTitle("Enter info")
            ...
    return builder.create();
}

并且在创建DialogFragment时传递额外的:

 DialogFragment fragment =  new MyDialog();
 Bundle bundle = new Bundle();
 bundle.putString("TEXT_TO_SET",userInfo.toString());
 fragment.setArguments(bundle);
 fragment.show(getFragmentManager(),"fragment_info");