我有延伸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());
}
}
});
當我運行該應用程序時,單擊該按鈕會拋出由以下原因引起的NullPointerException:txt.setText(userInfo.toString());
。 通過使用調試器,我發現(EditText)findViewById(R.id.infoEdit)
返回null
,我想我不能通過使用findViewById
訪問我的MainActivity中的EditText視圖。有沒有辦法做到這一點?
嘗試:EditText上TXT =(EditText)getDialog()。findViewById(R.id.infoEdit); – Zaki