How to get the context in a fragment?

1

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;
    }
}
    
asked by anonymous 08.07.2017 / 13:37

1 answer

2

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

Eventually getActivity() can return null . To ensure that you get a valid context get it in the onAttach() method and save it in an attribute 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);
}
    
08.07.2017 / 14:04