non-static method “getActivity” cannot be referenc

2019-07-24 13:47发布

问题:

This question already has an answer here:

  • non-static method getActivity() 4 answers

i make a method static but i have this problem: android.support.v4.app.FragmentTransaction transaction2 = getActivity().getSupportFragmentManager().beginTransaction();....

getActivity() is underline in red by IDE why?

I show you my code

THANKS IN ADVANCE EVERYBODY!

FRAGMENT:

public class MyListFragment extends Fragment implements
        android.widget.CompoundButton.OnCheckedChangeListener {

    ListView lv;
    ArrayList<Planet> planetList;
    static PlanetAdapter plAdapter;
    BirraAdapter biAdapter;
    PlanetAdapter.PlanetHolder holder;
    private static Context context = null;
    private static Main mInstance;





    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list2, container, false);
        context = getActivity();
        mInstance= getActivity();
        Button mButton = (Button) rootView.findViewById(R.id.button);
        mButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showResult(v);


            }
        });
        //return inflater.inflate(R.layout.fragment_list2, container, false);
        return rootView;
    }




    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        lv = (ListView)getView().findViewById(R.id.listview);
        displayPlanetList();


    }


    private void displayPlanetList() {

        planetList = new ArrayList<Planet>();
        planetList.add(new Planet("Margherita", 6, "€",1));
        planetList.add(new Planet("Diavola", 7,"€",2));
        planetList.add(new Planet("Bufalina", 5,"€",3));
        planetList.add(new Planet("Marinara", 5, "€",4));
        planetList.add(new Planet("Viennese", 4, "€", 5));

        plAdapter = new PlanetAdapter(planetList, getContext()) {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                int pos = lv.getPositionForView(buttonView);
                if (pos != ListView.INVALID_POSITION) {
                    Planet p = planetList.get(pos);
                    p.setSelected(isChecked);


            /*Toast.makeText(
                getActivity(),
                "Clicked on Pizza: " + p.getName() + ". State: is "
                        + isChecked, Toast.LENGTH_SHORT).show();*/
                }


            }
        };

        lv.setAdapter(plAdapter);
    }



    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        /*int pos = lv.getPositionForView(buttonView);
        if (pos != ListView.INVALID_POSITION) {
            Planet p = planetList.get(pos);
            p.setSelected(isChecked);


            *//*Toast.makeText(
                getActivity(),
                "Clicked on Planet: " + p.getName() + ". State: is "
                        + isChecked, Toast.LENGTH_SHORT).show();*//*
        }*/

    }


    public static void showResult(View v) {
        String  result = "Selected Product are :";
        int totalAmount=0;
        String  result2 = "";
        int totalAmount2=0;

        String a="";
        String z="";
        /*for (Birra b : biAdapter.getBox()){

            if (b.selected){

                result += "\n" + b.name+" "+b.distance+"€"+"q.tà :"+b.getQuantità();
                int quantitaInt= Integer.parseInt(b.getQuantità());
                totalAmount+=b.distance * quantitaInt;
                //a=String.valueOf(totalAmount);


            }
        }*/
        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){


                result2 += "\n" + p.getName()+" "+p.getDistance()+"€"+"q.tà :"+p.getQuantità();
                int quantitaInt= Integer.parseInt(p.getQuantità() );
                totalAmount2+=p.getDistance() * quantitaInt;
                //z=String.valueOf(totalAmount2);


            }
            int totale=totalAmount+totalAmount2;
            z=String.valueOf(totale);

        }

        Toast.makeText(context, result2 + "\n" + "Total Amount:=" + totalAmount2 + "€", Toast.LENGTH_LONG).show();
        //Toast.makeText(getActivity(), result2 + "\n" + "Total Amount:=" + totalAmount2 + "€", Toast.LENGTH_LONG).show();


        Bundle bun2 = new Bundle();
        bun2.putString("scelta", result2);
        ThreeFragment fgsearch2 = new ThreeFragment();
        fgsearch2.setArguments(bun2);
        android.support.v4.app.FragmentTransaction transaction2 = mInstance.getSupportFragmentManager().beginTransaction();
        transaction2.replace(R.id.content_main, fgsearch2);
        transaction2.commit();




/*Bundle bun = new Bundle();
        bun.putString("totale", a);
        TwoFragment fgsearch = new TwoFragment();
        fgsearch.setArguments(bun);
        android.support.v4.app.FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.content_main2, fgsearch);
        transaction.commit();*//*
*/
/*



        Bundle bun = new Bundle();
        bun.putString("scelta", result2);
        TwoFragment fgsearch = new TwoFragment();
        fgsearch.setArguments(bun);
        android.support.v4.app.FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.content_main2, fgsearch);
        transaction.commit();

*/









    }



}

ACTIVITY:

public class Main extends AppCompatActivity{



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        getSupportFragmentManager().beginTransaction().

                replace(R.id.fragmentContainer, new MyListFragment()).commit();




    }




}

回答1:

getActivity().getSupportFragmentManager().beginTransaction();

change to this

context.getSupportFragmentManager().beginTransaction();

Use dynamic context you initialize above in onCreateView() methods



回答2:

You can change your method as @sasikumar suggests or you can do this if you dont want to modify your method:

Create a static instance of your Activity: e.g if your activity's name is MainActivity, the instance would be private static MainActivity mInstance then inside your fragment's onCreateView(), add initialize it:

mInstance=getActivity()

then change

android.support.v4.app.FragmentTransaction transaction2 = getActivity().getSupportFragmentManager().beginTransaction(); to

android.support.v4.app.FragmentTransaction transaction2 = mInstance.getSupportFragmentManager().beginTransaction();


回答3:

change your method like as below

public static void showResult(View v,Context context) 
{
 //your code
}