非静态方法getActivity()

时间:2016-05-19 12:30:50

标签: android android-fragments android-studio static-methods

我将方法“showResult”设为静态,但我遇到了问题:

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

如何解决我的问题? 我将分享我的代码。

感谢每一个人!

这是我的第一个类Fragment.java

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

    ListView lv;
    ArrayList<Planet> planetList;
    static PlanetAdapter plAdapter;
    BirraAdapter biAdapter;
    PlanetAdapter.PlanetHolder holder;




    @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);

        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(getActivity().getApplication(), 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 = getActivity().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();

*/









    }



}

另一个类ThreeFragment.java

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

    ListView lv2;
    ArrayList<Planet> planetList;
    ListView lv;

    ArrayList<Birra> birraList;
    BirraAdapter biAdapter;
    PlanetAdapter plAdapter;
    Planet p;
    String myInt="";
    //MyListFragment mlf;



    PlanetAdapter.PlanetHolder holder;


    public ThreeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_three, container, false);

        Button mButton = (Button) rootView.findViewById(R.id.button2);
        mButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
               // mlf.showResult(v);
                MyListFragment.showResult(v);
                showResult2(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);

        lv2 = (ListView) getView().findViewById(R.id.listview2);
        displayBirraList();
    }


    private void displayBirraList() {

        birraList = new ArrayList<Birra>();
        birraList.add(new Birra("Paulaner", 6, "€"));
        birraList.add(new Birra("Forst", 7, "€"));
        birraList.add(new Birra("Peroni", 5, "€"));
        birraList.add(new Birra("Corona", 5, "€"));
        birraList.add(new Birra("Nastro Azzurro", 4, "€"));
        biAdapter = new BirraAdapter(birraList, getContext()) {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int pos = lv2.getPositionForView(buttonView);
                if (pos != ListView.INVALID_POSITION) {
                    Birra b = birraList.get(pos);
                    b.setSelected(isChecked);


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


            }


        };


        lv2.setAdapter(biAdapter);
    }


    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 void showResult2(View v) {
        String result = "Selected Product are :";
        int totalAmount = 0;
        String c = "";


        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()) {


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


            }
        }*/



        Toast.makeText(getActivity(), result + "\n" +myInt + "\n" + "Total Amount:=" + totalAmount + "€", Toast.LENGTH_LONG).show();
         /*   Bundle bun2 = new Bundle();
            bun2.putString("scelta2", result);
            TwoFragment fgsearch2 = new TwoFragment();
            fgsearch2.setArguments(bun2);
            android.support.v4.app.FragmentTransaction transaction2 = getActivity().getSupportFragmentManager().beginTransaction();
            transaction2.replace(R.id.content_main, fgsearch2);
            transaction2.commit();


            Bundle bun = new Bundle();
            bun.putString("totale2", c);
            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();

        */


    }
}

4 个答案:

答案 0 :(得分:8)

尝试使用context代替getActivity.getApplication()

context声明为:

private static Context context = null;

然后将其初始化为:

context=getActivity();

然后Toast

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

答案 1 :(得分:1)

试试这个

private static Context context = null;

在onCreateView()中初始化它,如

   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        context = getActivity(); //check this
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list2, container, false);

        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;
    }

在那个像这样的吐司改变

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

答案 2 :(得分:1)

错误解释本身你不能使用静态方法中不是静态的getActivity() 您可以执行以下方案 定义Activity act;  在onCreateView

中初始化它
act =getActivity();

并在您的方法中:

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

答案 3 :(得分:0)

删除.getApplication()

并添加

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