How to programmatically create the layout for a Fr

2019-03-14 23:50发布

问题:

Now to create fragment I did the following codes.

file name : fragment_a.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/frag_a"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

</LinearLayout>

In Java

public class FragA extends Fragment{
    View view_a;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        view_a = inflater.inflate(R.layout.fragment_a, container, false);

        return view_a;
    }



}

Now I need to know if there is any way to create a fragment view without creating an xml file and writing code into it?

What I am trying to say is I don't want to create a xml file for a fragment rather I want to create the view for that fragment using java code.

Is that possible?

回答1:

Yes, of course that is possible. Simply replace the inflation line with for example your CustomView.

public class FragA extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return new YourCustomView();
    }
}

Or like that:

public class FragA extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return new LinearLayout(getActivity());
    }
}

Or add more Views:

public class FragA extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        LinearLayout ll = new LinearLayout(getActivity());
        ll.addView(new TextView(getActivity()));

        return ll;
    }
}