How to get the context in a Fragment?

Asked

Viewed 3,044 times

2

What should I insert into a method that needs the context argument in this Fragment ?

public class Tab1tests extends Fragment {

    private ViewPager mViewPager;
    private DatePickerDialog.OnDateSetListener hourSetListener;
    private DatePickerDialog.OnDateSetListener dateSetListener;
    private Button date_button;
    private Button hora_picker;
    private TextView date_text;
    private TextView hora_text;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.tab1tests, container, false);

        date_button = (Button) rootView.findViewById(R.id.date_button);


        date_button.setOnClickListener(
                new View.OnClickListener(){
                    public void onClick(View v){
                        Calendar cal = Calendar.getInstance();
                        int year = cal.get(Calendar.YEAR);
                        int month = cal.get(Calendar.MONTH);
                        int day = cal.get(Calendar.DAY_OF_MONTH);
                        DatePickerDialog date_dialog = new DatePickerDialog(
                                ,
                                android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                                dateSetListener,
                                year, month, day);
                        date_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                        date_dialog.show();


                    };
                }

        );

        dateSetListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                month=month+1;
                date_button.setVisibility(View.GONE);
                date_text = (TextView) rootView.findViewById(R.id.date_text);
                date_text.setVisibility(View.VISIBLE);
                String dt = day+"-"+month+"-"+year;
                SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
                try {
                    sdf.parse(dt);
                    date_text.setText(dt);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }
        };
        return rootView;
    }
}

1 answer

2


In a Fragment the context can be obtained through getActivity()

Eventually getActivity() can return null. To ensure you get a valid context get it in the method onAttach() and keep it in a field so you can use it anywhere:

//Declara um atributo para guardar o context.
private Context context;

@Override
public void onAttach(Context context) {
    this.context = context;
    super.onAttach(context);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.