0

I would like to have a popup contextual help when the user clicks a button in a FRAGMENT of an activity. I have tried using the Toast to perform this action but in vain. The popup dialog box does not show (please also note that the recommendations in Use Toast inside Fragment did not help).

My code in the fragment class is written below:

            final Button help = (Button) view.findViewById(R.id.help_button);
        del.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
            Context context = (TabsActivity) getActivity().getApplicationContext();
            CharSequence text = "Hello toast!";
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(view.getContext(), text, duration);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
            }
        });

I have tried several variations of CONTEXT, two of which are shown in the code. I have also tried getActivity(), getView().getContext(), getContext() all of which went in vain. Can you please help understanding how to set the CONTEXT in a fragment?

Community
  • 1
  • 1
user1124702
  • 1,015
  • 4
  • 12
  • 22
  • your context(ing) is somewhat good. keep using `view.getContext()` except write `v.getContext()`! most code I've seen totally forgets about getting the context from the view param. – petey Dec 26 '12 at 15:37

4 Answers4

5

Use your application context, instead of getting it again off the view.

        Context context = getActivity().getApplicationContext();
        Toast.makeText(context, "Hello toast!", Toast.LENGTH_LONG).show();

Keep it simple and work up from there, so you can figure our which bit actually is causing your error.

Put logging into your code then you can determine when your onClick listeners are actually used instead of relying on Toast

 setOnClickListener(new View.OnClickListener(){
     @Override
     public void onClick(View v) {
          Log.d("MyTag", "Button 1 was pressed");
     }
 }
Blundell
  • 75,855
  • 30
  • 208
  • 233
4

Use simply getActivity() no other things. Doesn't required Casting or else getting application context too.

I use Toast.makeText(getActivity(), "Simple Toast",1000).show();

and it works for me.

TNR
  • 5,839
  • 3
  • 33
  • 62
1

in your code:

        final Button help = (Button) view.findViewById(R.id.help_button);
        del.setOnClickListener(new View.OnClickListener(){

Shouldnt it read (Note that help is now getting this onclick listener) :

        final Button help = (Button) view.findViewById(R.id.help_button);
        help.setOnClickListener(new View.OnClickListener(){
petey
  • 16,914
  • 6
  • 65
  • 97
1

Try this,

Toast toast = Toast.makeText(getActivity().getApplicationContext(), "text", 100);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
Talha
  • 12,673
  • 5
  • 49
  • 68