Fragment$InstantiationException解决办法

android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.smile.android.open.ui.fragment.LeftBehideListFragment: make sure class name exists, is public,online casinos  and has an empty constructor that is public。

其错误翻译为:Fragment初始化异常。刚开始很纳闷,之前项目一直好好的怎么一锁屏就报错呢!后面看了下后面的解释:确保类名存在且是公共的,并且同时拥有一个公共的空构造方法,没办法,它提示啥咱就改呗!于是就将我这个Fragment类提供一个公共的空的构造函数!果不其然这次不报错了!

解决方法:
建议创建您自己的片段,然后进行您自己的实例化方法:

public class MyFragment extends Fragment {

    public MyFragment() {   
        // empty constructor  
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // here you can load whatever layout you want for your fragment
        View v = inflater.inflate(R.layout.your_fragment_layout, container, false);
        // for example set the address as a textview text, or do whatever you want with it
        TextView tv = (TextView) v.findViewById(R.id.tvAddress);
        tv.setText(getArguments().getString("address"));
        return v;
    }

    public static MyFragment newInstance(String address) {
        MyFragment myFragment = new MyFragment();
        Bundle args = new Bundle();
        args.putString("address", address);
        myFragment.setArguments(args);
        return myFragment;
    }
}

然后在 onItemClick() 方法内:

// new fragment handling
  FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.replace(R.id.content_frame, MyFragmet.newInstance(fragmentAddresses[position]);
            transaction.commit();

 

这个异常通常是由于Fragment类没有默认的构造函数而引起的。当你在创建Fragment实例时,系统会调用Fragment的默认构造函数进行实例化。如果你的Fragment类中没有默认构造函数,就会抛出上述异常。 为了解决这个问题,有以下两种方法: 1. 在Fragment类中添加默认构造函数 你可以在Fragment类中手动添加一个无参构造函数,如下所示: ```kotlin class MainFragment : Fragment() { // 添加一个无参构造函数 constructor() // 其他代码 } ``` 这样就可以保证系统在创建Fragment实例时能够正常地进行实例化。 2. 使用newInstance方法传递参数 如果你的Fragment需要传递参数,可以使用静态的newInstance方法来创建Fragment实例,并在newInstance方法中传递参数。例如: ```kotlin class MainFragment : Fragment() { companion object { fun newInstance(param1: String, param2: Int): MainFragment { val fragment = MainFragment() val args = Bundle() args.putString("param1", param1) args.putInt("param2", param2) fragment.arguments = args return fragment } } // 其他代码 } ``` 在上述代码中,我们添加了一个静态的newInstance方法,该方法接收两个参数,将这些参数存储在Bundle中,并将Bundle设置为Fragment的arguments属性。在创建Fragment实例时,我们可以使用该静态方法来传递参数,例如: ```kotlin val fragment = MainFragment.newInstance("Hello", 123) ``` 这样就可以保证系统在创建Fragment实例时能够正常地进行实例化,并且能够传递参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值