我有两个活动 - 一个“主页”片段活动和一个普通的“选项”活动。
在我的主页片段活动中,我尝试使用从选项活动检索的数据来更新 EditText 视图。
不幸的是,由于某种原因,片段活动无法检测到我的视图以进行更新。我不太清楚为什么。这是我的功能:
//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 视图的公式在我的代码的其他部分工作得非常好。但这里它总是返回 null。有什么建议么?
编辑:这是我在 OnCreateView 中调用该函数的地方:
if(getActivity().getIntent() != null && getActivity().getIntent().getExtras() != null) {
String[] prelimUserArray = getActivity().getIntent().getExtras().getStringArray("userArray");
updateUserData(prelimUserArray);
}
Edit:
移动这个片段:
if (getActivity().getIntent() != null && getActivity().getIntent().getExtras() != null) {
String[] prelimUserArray = getActivity().getIntent().getExtras().getStringArray("userArray");
updateUserData(prelimUserArray);
}
to the onViewCreated
方法,该方法将在视图膨胀后调用。
public void onViewCreated(View view, @Nullable Bundle savedInstanceState){
// Your code here
}
检查此图片以获取有关 Fragment 生命周期的更多信息。
确保您拨打的是您的updateUserData
Fragment 之后的方法onCreateView()
回调已被触发。
尝试使用getView()
代替getActivity()
如中提到的这个答案 https://stackoverflow.com/a/32501845/2503185.
getActivity()
返回托管 Fragment 的 Activity,同时getView()
返回您膨胀并由 onCreateView 返回的视图。后者仅在 onCreateView 返回后才返回值 != null 。
另外,正如评论中提到的,检查您是否确实拥有EditText
有身份证输入名称.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)