簡體   English   中英

我不能使用findViewById

[英]I can't use findViewById

為什么我不能在這個文件中使用findViewById

Regfragment:

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;


public class RegFragment extends Fragment {

EditText text1,text2,text3;
Button btn1;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.reg_layout, container, false);

    return rootView;


}
}

然后我試着這樣做:

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;


public class RegFragment extends Fragment {

EditText text1,text2,text3;
Button btn1;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.reg_layout, container, false);

    return rootView;

    text1 = (EditText) findViewById(R.id.text1);   -----> ERROR....
}
}

我收到了錯誤
是因為我使用片段嗎?

你不能在片段中使用它,因為它是活動的方法

嘗試下面

在onActivityCreated()中

text1 = (EditText) getView().findViewById(R.id.text1);

或者在onCreateView()中

text1 = (EditText) rootView.findViewById(R.id.text1);

你用過inflater

View rootView = inflater.inflate(R.layout.reg_layout, container, false);

所以用

text1 = (EditText) rootView.findViewById(R.id.text1); 
text2 = (EditText) rootView.findViewById(R.id.text2); 
text3 = (EditText) rootView.findViewById(R.id.text3); 

等等。

你必須在返回語句之前這樣做

    View rootView = inflater.inflate(R.layout.reg_layout, container, false);
   text1 = (EditText) rootView.findViewById(R.id.text1);
    return rootView;

希望它會奏效。

要訪問片段中的視圖,您需要通過包含布局的View類訪問它。

您需要更改以下代碼:

public class RegFragment extends Fragment {

EditText text1,text2,text3;
Button btn1;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.reg_layout, container, false);
    text1 = (EditText)rootView .findViewById(R.id.text1); 
    //Same way initialize other views also. 
    return rootView;
}
}

只是一個簡單的方法。 你已經誇大了布局。 只是繼承自那。 找到下面的代碼

View rootView = inflater.inflate(R.layout.reg_layout, container, false);
text1 = (EditText)rootView.findViewById(R.id.text1); 

return rootView;

由於您使用單獨的視圖來擴充布局,因此您需要使用該視圖來訪問該布局中存在的所有文本視圖/圖像視圖/編輯文本。

因此,要更正代碼,您需要調整代碼,如下所示

View rootView = inflater.inflate(R.layout.reg_layout, container, false);
text1 = (EditText) rootView.findViewById(R.id.text1);
return rootView;

暫無
暫無

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

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