Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onClick inside fragment called on Activity

i am encapsulating stuff into a fragment at the moment and run into a problem that is hard to google. Inside my fragment are some buttons with onClick attributes but they are called on the Activity rather the fragment from the android system - this makes encapsulating a bit clumsy. Is there a way to have the reflection stuff from onClick to call on the fragment? The only solution to this I see at the moment is not to use onClick in the xml and set click-listeners inside the fragment via code.

like image 644
ligi Avatar asked Sep 27 '11 14:09

ligi


People also ask

How to call fragment in activity?

Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.

How to use onClick in xml on fragment Android?

Solution: You have to use the onClick="."" Transfer entry from the layout/fragment. xml page to the codebehind page in java/project/fragment_page. java and connect it to an onClicklistener on a resource.


2 Answers

I spoke to some googlers @ #adl2011 - they recognize the problem and perhaps there will be a fix of that in the future. Until then - one should use .setOnClick in the Fragment.

like image 193
ligi Avatar answered Oct 02 '22 16:10

ligi


The problem is that when layout's are inflated it is still the hosting Activity that is receiving the button clicks, not the individual Fragments.

I prefer using the following solution for handling onClick events. This works for Activity and Fragments as well.

public class StartFragment extends Fragment implements OnClickListener{      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,             Bundle savedInstanceState) {          View v = inflater.inflate(R.layout.fragment_start, container, false);          Button b = (Button) v.findViewById(R.id.StartButton);         b.setOnClickListener(this);         return v;     }      @Override     public void onClick(View v) {         switch (v.getId()) {         case R.id.StartButton:              ...              break;         }     } } 

Then problem is gone.

like image 39
Zar E Ahmer Avatar answered Oct 02 '22 15:10

Zar E Ahmer