Sreeram Boyapati
Sreeram Boyapati

Reputation: 89

Event listener not working in Fragment

When I click on the button1 Button I cannot see any Toast. I disabled the EditText event and even then I cannot see it. The Class "View1"is part of a pagerView.

public class View1 extends Fragment{

     ImageView album;
     Button b1;

    public View1(){}

   public void OnCreate(Bundle SavedInstanceState) {
         super.onCreate(SavedInstanceState);

                b1.findViewById(R.id.button1);

                b1.setOnClickListener(new OnClickListener(){
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(getActivity().getApplicationContext(), "asdasd", Toast.LENGTH_SHORT).show();     
                        }
                    });
   }   

        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            return inflater.inflate(R.layout.view1, container, false);
  }

Upvotes: 0

Views: 5743

Answers (2)

severine
severine

Reputation: 117

You can move your listener into onCreateView or onActivityCreated, it should work then

Upvotes: 0

user
user

Reputation: 87064

I would advise you to look over the Android life cycle chart for a Fragment.

Your so called OnCreate method isn't called because it's not the onCreate callback of a Fragment. In order to avoid this types of mistakes please use the @Override annotation with the proper methods to make sure you override the method and not just create a new one.

Even if your method would have been called your code would have thrown a NullPointerException as you don't initialize the Button(which isn't even created as the onCreateView callback is called after onCreate). Your code should look like this:

public class View1 extends Fragment {

    ImageView album;
    Button b1;

    @Override  
    public void OnCreate(Bundle SavedInstanceState) {
         super.onCreate(SavedInstanceState);
    }   

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.view1, container, false);
        b1 = (Button) v.findViewById(R.id.button1);
        b1.setOnClickListener(new OnClickListener(){
             @Override
             public void onClick(View v) {
                Toast.makeText(getActivity(), "asdasd", Toast.LENGTH_SHORT).show();     
             }
        });
    }
        return v;
}

Upvotes: 4

Related Questions