Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment implements OnClickListener

I've got an application that I'm modernizing. One step of this process is changing to a Fragment based layout (using the Fragments from the support library). I converted my Activities into Fragments, and got the layout working nicely (using a ViewPager, cool stuff!)

I was having my Activities implement OnClickListener for all of my button-pressing needs. I have the new Fragment incarnations doing the same thing of course, but it looks like "onClick" is never getting hit. Is there something special about Fragments that prevents them from working this way?

like image 885
Nick Avatar asked Aug 08 '12 02:08

Nick


People also ask

What does set OnClickListener do?

setOnClickListener(this); means that you want to assign listener for your Button “on this instance” this instance represents OnClickListener and for this reason your class have to implement that interface. If you have more than one button click event, you can use switch case to identify which button is clicked.

Why my setOnClickListener is not working?

You need to put the setOnClickListener in one of the activity callbacks. In your onCreate() method, move the button there and then setOnClickListener() . Save this answer.


2 Answers

Just do one this

public class fragmentOne extends Fragment implements OnClickListener {
    Button myButton;

    @Override
    public View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState) {
        View myView = inflater.inflate(R.layout.fragment_1, container, false);
        myButton = (Button) myView.findViewById(R.id.myButton);
        myButton.setOnClickListener(this);
        return myView;
    }

    @Override
    public void onClick(View v) {
        // implements your things
    }
}

very simple

like image 169
Abhijit Chakra Avatar answered Sep 23 '22 09:09

Abhijit Chakra


I will Focus to use the OnClick action for global access, You have to do like this is your project, Must Implement the View.OnClickListener, then Override the Method OnClick(), In OnCreateView() have to do like this button_submit.setOnClickListener(this); for the Views you need, Please see the below code for Clear Answer,Thankyou.

public class New_Project extends Fragment implements View.OnClickListener{
private View mView;
private Button button_submit;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mView = inflater.inflate(R.layout.fragment_newproject, container,false);
    button_submit=(Button)mView.findViewById(R.id.button_submit);
    button_submit.setOnClickListener(this);
    return mView;
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.button_submit:
            //do your stuff
            break;
    }
}

}

like image 24
MohanRaj S Avatar answered Sep 25 '22 09:09

MohanRaj S