Ertai87
Ertai87

Reputation: 1316

Layout in Dynamic Fragments

I'm writing a calculator application in which I would like to be able to switch between 4 modes of calculation: Decimal, Binary, Octal, and Hex. In order to manage the different UIs for the different modes, I have 4 Fragment subclasses in my Activity. Each Fragment has its own XML layout file, in addition to the main XML file for the Activity. I found a guide on the Android Developer site for inflating layouts for Fragments, and I've followed that guide. However, I would like to add listeners and so on to the various components of the layouts, preferably within the onCreateLayout method of the Fragment, or somewhere else where I could do it easily and minimize code duplication.

It appears, however, that when I try to call findViewByID to access one of the inflated Views (after I've called LayoutInflater.inflate, obviously), I get a null return value. This issue occurs whether I call findViewByID from within onCreateLayout or from elsewhere in the Activity (after the Views have, theoretically, been created). What's going wrong here?

One issue I think might be a problem is that I've overloaded the names of the Views between the various Fragment layouts. For example, the "1" button in the Binary layout has the same ID as the "1" button in the Hex layout. Is this allowed, assuming the Binary and Hex layouts are never both part of the Activity at the same time?

Thanks.

Upvotes: 1

Views: 252

Answers (1)

Chinmoy Debnath
Chinmoy Debnath

Reputation: 2824

I think same id in different layout is not problem in Fragement. First you have to catch the inflated view then find whatever inside this. For example --

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

    view = inflater.inflate(R.layout.frg1, container, false);
    android.util.Log.v("", "!!!!!!!!!! Frg1  !!!!!!!!!");   


    Button b = (Button) view.findViewById(R.id.b1);
    b.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
            Toast.makeText(getActivity(), "here", Toast.LENGTH_SHORT).show();
        }
    });

    return view;
}

Upvotes: 1

Related Questions