在使用android Fragment时出现Cannot resolve method ‘findViewById‘ in ‘Fragment_one‘错误解决方法

Fragment中不能直接使用findViewById,应该在onCreateView方法里,通过根视图对象来查找。例如,先inflate布局,然后对根视图调用findViewById找到对应的视图元素,如TextView。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在 Fragment 中,不能直接使用 'findViewById' 方法来获取视图元素,正确的做法是在 Fragment 的 onCreateView 方法中,使用根视图对象调用 'findViewById' 方法

解决方法

public class FragmentOne extends Fragment {
    private View rootView;
    private TextView textView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_one, container, false);
        textView = rootView.findViewById(R.id.text_view);

        // 在这里可以对 textView 进行操作
		//也可以封装一下,另外去写方法进行调用
        return rootView;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值