gpt4 book ai didi

android - 从 DialogFragment 子类调用 findViewById() 给出 NullPointerException

转载 作者:行者123 更新时间:2023-11-30 02:31:56 25 4
gpt4 key购买 nike

在下面的代码中,我尝试在单击按钮时显示一个基本对话框。该对话框显示一些需要显示一些文本。在我偶然发现一个错误后,我已经开始工作了,但我仍然有一个问题,为什么会发生这个错误。在 DialogFragmentSubclass.onCreateView() 中,我通过调用 findViewById(R.id.someIdValue) 获得了对 TextView 的引用。这给了我 NullPointerException。但是,通过调用获取引用:

View v = inflate.inflate(someREsourceValue, container, fals);
TextView tv = (TextView) v.findViewById(R.id.someValue);

似乎可以解决问题。为什么这个有效,另一个给我一个 NullPointerException? (完整代码见下文)

public class MainActivity extends Activity {
DownloadImageDialogFragment myDialog;

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

// get reference to buttons
Button buttonDownloadImage = (Button) findViewById(R.id.downloadImage);
buttonDownloadImage.setText("Download new Image");

// upon button click, show a Dialog
buttonDownloadImage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentTransaction ft = getFragmentManager().beginTransaction();

myDialog = new DownloadImageDialogFragment();
myDialog.show(ft, null);
}
});

}

private class DownloadImageDialogFragment extends DialogFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View v = inflater.inflate(R.layout.fragment_dialog, container, false);
// TextView tv = findViewById(R.id.dialogTextView); // this gives an error
TextView tv = (TextView) v.findViewById(R.id.dialogTextView); // this works
tv.setText("This is my dialog");
return v;
}
}
}

这里是对话框的布局文件:

    <TextView 
android:id="@+id/dialogTextView"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />

</LinearLayout>

最佳答案

当您调用 findViewById() 时,您是从 Activity 的内部类执行此操作的,这就是此方法的来源。由于该 View ID 在您的 Activity 布局中不存在,因此您将获得 null。您的对话框 fragment 必须先扩充其布局(如您所见),然后才能获得其中定义的 View 。

关于android - 从 DialogFragment 子类调用 findViewById() 给出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27219908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com