我不能使用findViewById

 韩大妖丫头 发布于 2023-02-08 11:22

为什么我不能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....
}
}

我得到错误
是因为我使用碎片?

1 个回答
  • 你不能在片段中使用它,因为它是活动的方法

    尝试下面

    在onActivityCreated()中

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

    或者在onCreateView()中

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

    2023-02-08 11:23 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有