NullPointerException
NullPointerException

Reputation: 37681

How to work with Fragments using 100% java code? (without xml)

I'm trying to develop and app using 100% and only java code, without .xml files. I just want to understand how to achieve it. I want to achieve it also without extending Fragment class, just using Fragment as a layout container.

I finally got it but i don't like the approach, as i must create an extension class of Fragment with a special method for setting the View of the Fragment.

I don't like it. It whould be munch better if Fragment has a way to set the view programatically, something like for example:

Fragment fragment = new Fragment();
fragment.setView(new TextView());

It is possible to do it? or the only way to achieve this is with my solution?

This is my working sample code with two classes:

public class BasicActivityWithFragment extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout ll = new LinearLayout(this);
        ll.setId(1);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        TextView tv = new TextView(this);
        tv.setText("prueba fragment todo por codigo java");

        CustomFragment fragment = new CustomFragment();
        fragment.setView(tv);
        fragmentTransaction.add(ll.getId(), fragment);
        fragmentTransaction.commit();

        setContentView(ll);
    }
}

and

public class CustomFragment extends Fragment{
    View view;

    public CustomFragment(){
        super();
    }

    public void setView(View view){
        this.view = view;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return view;
    }
}

Upvotes: 1

Views: 817

Answers (1)

Simon Marquis
Simon Marquis

Reputation: 7526

You could just create an anonymous Fragment and override this method:

Fragment fragment = new Fragment() {
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            TextView tv = new TextView(container.getContext());
            tv.setText("prueba fragment todo por codigo java");
            return tv;
        }
    };

But this comes with a lint warning:

Fragments should be static such that they can be re-instantiated by the system, and anonymous classes are not static

Upvotes: 1

Related Questions