Android使用Fragment传参打包时报错

准备上线打包时候出现问题- - - -别慌碰到问题就要解决(分分钟消灭它)

Error:Error: This fragment should provide a default constructor (a public constructor with no arguments) (com.---.---.recored.recordFragment) [ValidFragment]

这是因为我们传参时候提供了一个代参数的构造方法而Fragment需要提供一个默认的构造方法这时可以参考谷歌提供的示例修改代码。
示例如下:

public static class MyFragment extends Fragment {
    CharSequence mLabel;

    /**
     * Create a new instance of MyFragment that will be initialized
     * with the given arguments.
     */
    static MyFragment newInstance(CharSequence label) {
        MyFragment f = new MyFragment();
        Bundle b = new Bundle();
        b.putCharSequence("label", label);
        //通过setArguments保存数据在onCreate方法中获取所需的数据
        f.setArguments(b);
        return f;
    }

    /**
     * Parse attributes during inflation from a view hierarchy into the
     * arguments we handle.
     */
    @Override
    public void onInflate(Context context, AttributeSet attrs, Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);

        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.FragmentArguments);
        mLabel = a.getText(R.styleable.FragmentArguments_android_label);
        a.recycle();
    }

    /**
     * During creation, if arguments have been supplied to the fragment
     * then parse those out.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //拿到数据使用
        Bundle args = getArguments();
        if (args != null) {
            CharSequence label = args.getCharSequence("label");
            if (label != null) {
                mLabel = label;
            }
        }
    }

    /**
     * Create the view for this fragment, using the arguments given to it.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.hello_world, container, false);
        View tv = v.findViewById(R.id.text);
        ((TextView)tv).setText(mLabel != null ? mLabel : "(no label)");
        ViewCompat.setBackground(
                tv, ContextCompat.getDrawable(getContext(), android.R.drawable.gallery_thumb));
        return v;
    }
}

下面是在activity里面进行调用

 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment newFragment = MyFragment.newInstance("这是你要传的参数");
        ft.add(R.id.created, newFragment);
        ft.commit();

这样使用Fragment在打包时候就不会出现那样的错误了!


有时候我们在使用Fragment时候getSupportFragmentManager( )获取
不到这时候就应该检查一线是否是导包出现错误这个方法位于v4包下而app包下是getFragmentManager( )

有空多看看开发文档必将受益无穷 - - - - - - -

https://developer.android.google.cn/reference/android/support/v4/app/Fragment.html

你可能感兴趣的:(基础知识)