android 错误记录Attempt to invoke virtual method ‘void android.view.View.setVisibility(int)‘

博客讨论了在Android开发中遇到的一个常见错误:尝试在null对象上调用`setVisibility()`方法。问题源于最大父布局在XML中被设置为不可见,导致在代码中尝试显示该布局时出错。提供了两种解决方案:1) 直接通过`view.setVisibility(View.VISIBLE)`操作根布局;2) 改变布局结构,使R.id.ll_vv不再是最大布局,从而能正常设置可见性。
摘要由CSDN通过智能技术生成

android 错误记录:
Attempt to invoke virtual method ‘void android.view.View.setVisibility(int)’ on a null object reference site:blog.csdn.net

场景:
布局中 最大的父布局设置的是不可见
代码中

View  a = view.findViewById(R.id.ll_vv);//R.id.ll_vv这个是最大的父布局
        a.setVisibility(View.VISIBLE);//报这个错误

解决方法

public class ContentMainTwo extends Fragment {
    private TextView tv_title_specific;
    private TextView tv_content_specific;
    private View view;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.content_frag_two,container,false);
        view = v;
        return v;
    }

    public void refresh(String title,String content){
        /*View a = view.findViewById(R.id.ll_vv);
        a.setVisibility(View.VISIBLE);*/
        view.setVisibility(View.VISIBLE);//方法1,不要View a
        tv_title_specific = view.findViewById(R.id.tv_title_specific);
        tv_content_specific = view.findViewById(R.id.tv_content_specific);

        tv_title_specific.setText(title);
        tv_content_specific.setText(content);
    }
}

方法2:让R.id.ll_vv这个布局变成不是最大的布局(外面加个Relativelayout之类的,设置此时ll_vv为可见或者不可见),就可以用View a啥啥啥的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值