簡體   English   中英

EditText視圖返回null

[英]EditText View returns null

我有兩個活動-主頁片段活動和普通的選項活動。

在我的家庭片段活動中,我試圖使用從“選項”活動中檢索的數據來更新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 View的公式在我的代碼的其他部分運行得很好。 但是在這里,它總是返回null。 有什么建議么?

編輯:這是我在OnCreateView中調用函數的位置:

   if(getActivity().getIntent() != null && getActivity().getIntent().getExtras() != null) {
        String[] prelimUserArray = getActivity().getIntent().getExtras().getStringArray("userArray");
        updateUserData(prelimUserArray);
    }

編輯:

移動以下代碼段:

if (getActivity().getIntent() != null && getActivity().getIntent().getExtras() != null) {
    String[] prelimUserArray = getActivity().getIntent().getExtras().getStringArray("userArray");
    updateUserData(prelimUserArray);
}

onViewCreated方法,該方法將在視圖放大后調用。

public void onViewCreated(View view, @Nullable Bundle savedInstanceState){
    // Your code here
}

檢查此圖像以獲取有關片段生命周期的更多信息。

片段的生命周期


確保在觸發Fragment的onCreateView()回調后正在調用updateUserData方法。


嘗試使用getView()代替此答案中提到的getActivity()

getActivity()返回承載片段的Activity,而getView()返回您通過onCreateView展開並返回的視圖。 后者僅在onCreateView返回后才返回值!= null。


另外,如注釋中所述,檢查是否確實具有ID為Input_NameEditText

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM