我有两个 Activity - 一个“主页” fragment Activity 和一个普通的“选项” Activity 。
在我的主页 fragment Activity 中,我尝试使用从选项 Activity 检索的数据来更新 EditText View 。
不幸的是,由于某种原因, fragment Activity 无法检测到我的 View 以进行更新。我不太清楚为什么。这是我的功能:
//update text box
public void updateUserData (String[] userArray){
Log.d("User Update:", "beginning...");
//get username
EditText et=(EditText)getActivity().findViewById(R.id.Input_Name);
if (et == null) {
Log.d("ERROR:", "View returning null");
}
if (userArray[0] != null) {
Log.d("Updating name:", userArray[0]);
et.setText(userArray[0]); }
}
奇怪的是...用于检索 EditText View 的公式在我的代码的其他部分中工作得非常好。但这里它总是返回 null。有什么建议么?
编辑:这是我在 OnCreateView 中调用该函数的位置:
if(getActivity().getIntent() != null && getActivity().getIntent().getExtras() != null) {
String[] prelimUserArray = getActivity().getIntent().getExtras().getStringArray("userArray");
updateUserData(prelimUserArray);
}
最佳答案
编辑:
移动此 fragment :
if (getActivity().getIntent() != null && getActivity().getIntent().getExtras() != null) {
String[] prelimUserArray = getActivity().getIntent().getExtras().getStringArray("userArray");
updateUserData(prelimUserArray);
}
到 onViewCreated
方法,该方法将在 View 膨胀后调用。
public void onViewCreated(View view, @Nullable Bundle savedInstanceState){
// Your code here
}
查看此图片以获取有关 Fragment 生命周期的更多信息。
确保在触发 Fragment 的 onCreateView()
回调后调用 updateUserData
方法。
尝试使用 getView()
而不是 this answer 中提到的 getActivity()
.
getActivity()
returns the Activity hosting the Fragment, whilegetView()
returns the view you inflated and returned by onCreateView. The latter returns a value != null only after onCreateView returns.
另外,正如评论中提到的,检查您是否确实拥有 ID 为 Input_Name 的 EditText
。
关于java - EditText View 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37105513/