android.support.v4.app.Fragment $ InstantiationException:无法实例化片段

时间:2018-07-18 15:26:37

标签: java android android-fragments

我正在学习android。我从codecanyon获得了一个源代码。我正面临一个错误,如下所示。

android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment

我遇到错误的活动如下

public class HomeActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener{

    private ViewPager viewPager;
    private BottomNavigationView bottomNavigationView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);

        Activity mActivity = this;
        viewPager = findViewById(R.id.viewpager);
        bottomNavigationView = findViewById(R.id.bottomNavigationView);
        bottomNavigationView.setOnNavigationItemSelectedListener(this);

        setupViewPager(viewPager);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if(position == 0){
                    bottomNavigationView.setSelectedItemId(R.id.menuHome);
                }else if(position == 1){
                    bottomNavigationView.setSelectedItemId(R.id.menuAccount);
                }else{
                    bottomNavigationView.setSelectedItemId(R.id.menuSetup);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        SharedPreferences pref = mActivity.getSharedPreferences("setting", MODE_PRIVATE);
        int membership = pref.getInt("membership", 1);
        if(membership == 0) {
            if (!HomeActivity.this.isFinishing()) {
                AlertManager.createCallbackAlert(mActivity, "Warning", "Trial expired if premium not purchased your account history will be deleted in 3 days", false, "OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }, "BUY", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        viewPager.setCurrentItem(1);
                    }
                });
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new StateFragment(), "HOME");
        adapter.addFragment(new AccountFragment(), "ACCOUNT");
        adapter.addFragment(new SetupFragment(), "SETUP");
        viewPager.setAdapter(adapter);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.menuHome:
                viewPager.setCurrentItem(0);

                break;
            case R.id.menuAccount:
                viewPager.setCurrentItem(1);

                break;
            case R.id.menuSetup:

                viewPager.setCurrentItem(2);
                break;
        }


        return true;
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

我的片段如下所示

@SuppressLint("ValidFragment")
public class Weekly extends Fragment {

    AccountType accountType;

    @SuppressLint("ValidFragment")
    public Weekly(AccountType accountType) {
        this.accountType = accountType;

    }

    TextView tvSubType;
    TextView tvSubDesc;
    private ItemClickListner itemClickListner;

    public interface ItemClickListner {
        void onItemClick(int postion);
    }

    public void setItemClickListner(ItemClickListner itemClickListner) {
        this.itemClickListner = itemClickListner;
    }


    Button btnPurchase;


    private static final String TAG = "Weekly";
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.weekly_subscption, null, false);
        tvSubType = inflate.findViewById(R.id.tvSubType);
        btnPurchase = inflate.findViewById(R.id.btnPurchase);
        tvSubType.setText(accountType.getType());

        tvSubDesc = inflate.findViewById(R.id.tvSubDesc);
        tvSubDesc.setText(accountType.getDesc());


        btnPurchase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                accountType.itemClickListner.onItemClick(accountType.getIndex());

            }
        });


        return inflate;
    }
}

我的AccountType类如下

public class AccountType {

    String type;
    String desc;

    int index;
    MembershipFragment.ItemClickListner itemClickListner;

    public AccountType(String type, String desc, int index, MembershipFragment.ItemClickListner itemClickListner) {
        this.type = type;
        this.desc = desc;
        this.index = index;
        this.itemClickListner = itemClickListner;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public MembershipFragment.ItemClickListner getItemClickListner() {
        return itemClickListner;
    }

    public void setItemClickListner(MembershipFragment.ItemClickListner itemClickListner) {
        this.itemClickListner = itemClickListner;
    }
}

让我知道是否有人可以帮助我解决此错误。如果它很简单,请原谅我,因为我试图在过去一个半小时内修复它,但我无法做到。非常感谢。

1 个答案:

答案 0 :(得分:0)

一个片段必须有一个no-argument constructor。您用@SuppressLint("ValidFragment")压制的那些警告是真实的。

如果您需要将数据传递给片段,请改用参数包。您可以通过更改AccountType使其扩展为可序列化来进行捆绑:

public class AccountType implements Serializable {

然后在Weekly中删除当前的构造函数,然后使用静态方法将其传递给Fragment,该方法会将其放入束中。

public static Weekly newInstance(AccountType t) {
    Weekly fragment = new Weekly();
    Bundle args = new Bundle();
    args.putSerializable("ACCOUNT", t);
    fragment.setArguments(args);
    return fragment;
}

Weekly() {}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Bundle args = getArguments();
    accountType = (AccountType)args.getSerializable("ACCOUNT");
}

然后,而不是使用

创建片段
new Weekly(account);

您将使用

Weekly.newInstance(account);