Raghavendra Shivhare
Raghavendra Shivhare

Reputation: 714

button in fragment not working when clicked

I have a button in fragment, and for that button i had override onClick() method, but its not working. i have a Taost and a Log too when the button is being clicked.

public class DataShown extends Fragment  implements OnClickListener{

Button tv;
TextView textview;
Activity activity=getActivity();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    Log.d("3", "started");
    View rootView = inflater.inflate(R.layout.datashown, container, false);
    Log.d("3", "closed");
    textview=(TextView) rootView.findViewById(R.id.textView1);
    tv = (Button) rootView.findViewById(R.id.configButton);
    tv.setOnClickListener((OnClickListener) activity);
return rootView;
}//onCtreate

@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    Log.d("onClick","1");
    Toast.makeText(activity, "on click", Toast.LENGTH_SHORT).show();
}
}

why its happening, i have no idea, may be its silly mistake. Now the toast is showing error, is accepts context object so i provided activity, not working.

Upvotes: 2

Views: 168

Answers (4)

Sreedev
Sreedev

Reputation: 6653

This is the problem with your context in setOnClickListener, you need to give your actvivities context to work fine.

setOnClickListener(getActivity); will pass the actvities context to the onclicklistner.

Upvotes: 0

Giru Bhai
Giru Bhai

Reputation: 14398

Change

tv.setOnClickListener((OnClickListener) activity);

to

tv.setOnClickListener(this);

and in onClick method change

Toast.makeText(activity, "on click", Toast.LENGTH_SHORT).show();

to

Toast.makeText(getActivity(), "on click", Toast.LENGTH_SHORT).show();

and remove

Activity activity=getActivity();

because you did initiate it before fragment attached to activity.

Upvotes: 1

Panther
Panther

Reputation: 9408

You are creating the view in the fragment, but binding the on click listener to the activity. tv.setOnClickListener(this); since fragment is the one tat is overriding the onClick listener and not the activity

Upvotes: 1

Harsh Parikh
Harsh Parikh

Reputation: 3845

Yon can do this: tv.setOnClickListener(getActivity);

Upvotes: 0

Related Questions