java - EditText View 返回 null

标签 java android android-fragments null

我有两个 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's lifecycle


确保在触发 Fragment 的 onCreateView() 回调后调用 updateUserData 方法。


尝试使用 getView() 而不是 this answer 中提到的 getActivity() .

getActivity() returns the Activity hosting the Fragment, while getView() returns the view you inflated and returned by onCreateView. The latter returns a value != null only after onCreateView returns.


另外,正如评论中提到的,检查您是否确实拥有 ID 为 Input_NameEditText

关于java - EditText View 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37105513/

相关文章:

java - 在java中的线程和标志之间交换多个对象

android - 在 MainActivity 中创建对话框并在整个应用程序的 fragment 中使用它

android - UI元素是在Fragment还是FragmentActivity中发起的?

java - 如何将 ajax 事件绑定(bind)到 primefaces 中的 selectManyMenu 组件

java - 在父类(super class)构造函数中调用抽象方法

java - 使用 Lambda 表达式对多个属性进行排序

构建时发生 Android 数据绑定(bind)错误

java - 在 Javafx 中切换场景时如何保持窗口大小?

java - 从包 "library"调用 android 函数

android - 从 fragment 按钮单击( Intent )开始 Activity 会抛出空白屏幕