简体   繁体   中英

android : LayoutInflater in static method

i want to call LayoutInflater from static method as below :

    private static void inflateLayout_keluarga_pp(int counter2, String name) {
            LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.layoutkeluarga, null);
..................
..................
}

this is how i call method inflateLayout_keluarga_pp :

    public static void onRetrieve(int position){
    List<ModelKeluargaPP> mk = helper.getSelectTable_Marital();
        for (int i=0; i<mk.size();i++){
        inflateLayout_keluarga_pp(i,mk.get(position).getAnggota_pp());


  }
}

but i got error in getActivity() , they said : Cannot make a static reference to the non-static method getActivity() from the type Fragment i need to make this method into static. how to fix it? i hope someone can help to solve my problem, thank you.

getActivity() belongs to the instance of the current Fragment ; it cannot be part of a static context.

When you declare a method static , you are stating that this method will not belong to each particular instance of the Class ; it belongs to the Class itself. Since the static method will be available regardless if you instantiate an object of the Class , you cannot guarantee that object members and methods (that are not static) will be available. Hence you cannot reference "things" that will be available only when the object is instantiated inside a static method that will always be available.

Like Jems said, if you need to access the Fragment you need to always make it available within the method's scope. This can be accomplished by either passing a Fragment to the static method or by instantiating it inside the static method.

If it must be static, pass a reference to the Fragment you want to call getActivity on into the method.

private static void inflateLayout_keluarga_pp(int counter2, String name, Fragment myFragment) {
            LayoutInflater inflater = (LayoutInflater)myFragment.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM