Using context in a fragment

后端 未结 30 2615
Happy的楠姐
Happy的楠姐 2020-11-22 00:05

How can I get the context in a fragment?

I need to use my database whose constructor takes in the context, but getApplicationContext() and Fragmen

相关标签:
30条回答
  • 2020-11-22 00:31
    public class MenuFragment extends Fragment implements View.OnClickListener {
        private Context mContext;
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            FragmentMenuBinding binding=FragmentMenuBinding.inflate(inflater,container,false);
            View view=binding.getRoot();
            mContext=view.getContext();
            return view;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:32

    To do as the answer above, you can override the onAttach method of fragment:

    public static class DummySectionFragment extends Fragment{
    ...
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            DBHelper = new DatabaseHelper(activity);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:33

    In kotlin just use activity instead of getActivity()

    0 讨论(0)
  • 2020-11-22 00:34

    getContext() method helps to use the Context of the class in a fragment activity.

    0 讨论(0)
  • 2020-11-22 00:37

    You can call getActivity() or,

    public void onAttach(Context context) {
        super.onAttach(context);
        this.activity = (CashActivity) context;
        this.money = this.activity.money;
    }
    
    0 讨论(0)
  • 2020-11-22 00:37

    I need context for using arrayAdapter IN fragment, when I was using getActivity error occurs but when i replace it with getContext it works for me

    listView LV=getView().findViewById(R.id.listOFsensors);
    LV.setAdapter(new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1 ,listSensorType));
    
    0 讨论(0)
提交回复
热议问题