Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toast inside onClick method in Fragment

I have a following Fragment:

public class FragmentSocial extends Fragment implements ActionBar.TabListener, OnClickListener 
{

private Fragment mFragment;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActivity().setContentView(R.layout.fragment_social);
}

public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // relevant code...
}

public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    // relevant code...
}

public void onTabReselected(Tab tab, FragmentTransaction ft) {
    // TODO Auto-generated method stub

}

public void onClick(View v) {
    switch(v.getId())
    {
    case R.id.imgBtnFB:
        Toast.makeText(this, "FB pressed", Toast.LENGTH_LONG).show();
        break;
    case R.id.imgBtnTwitter:
        Toast.makeText(this, "Twitter pressed", Toast.LENGTH_LONG).show();
        break;
    }

}

I have a few image buttons in my fragment_social layout. For now I just want to make a Toast message to see what button was pressed. However, if I use this as context, I'm getting this error message: The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (FragmentSocial, String, int) I tried to change this to FragmentSocial.this, to FragmentSocial.this.getActivity(), tried to create private Context mContext and to instantiate it to mContext = (I tried various options here) inside the onCreate method - but nothing worked. I either didn't have an error message, but also didn't see the Toast, or got other errors.

So how can I create a Toast here?

Thank you!

like image 476
Igal Avatar asked Dec 01 '22 20:12

Igal


1 Answers

use:

getActivity().getBaseContext();
like image 165
Marcin S. Avatar answered Dec 20 '22 23:12

Marcin S.