Toast.makeText不起作用

时间:2016-05-03 07:33:56

标签: android listview android-fragments android-studio android-toast

我有片段问题....当我点击按钮调用showResult方法时,Toast.makeText没有显示所选复选框的名称。

我不知道为什么。

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

    ListView lv;
    ArrayList<Planet> planetList;
    PlanetAdapter plAdapter;

    @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, "€"));
        planetList.add(new Planet("Diavola", 7,"€"));
        planetList.add(new Planet("Bufalina", 5,"€"));
        planetList.add(new Planet("Marinara", 5,"€"));
        planetList.add(new Planet("Viennese", 4,"€"));

        plAdapter = new PlanetAdapter(planetList, getContext());
        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 void showResult(View v) {
        String result = "Selected Product are :";
        int totalAmount=0;

        for (Planet p : plAdapter.getBox()) {
            if (p.selected){
                System.out.println("pizza selezionata: " + p.name);

                    System.out.println("nessuna pizza selezionata: ");

                result += "\n" + p.name+" "+p.distance+"€"+"q.tà :"+p.getQuantità();
                //if (p.quantità.equals("") && p.quantità.equals(null) ){
                System.out.println("leggo questo record:"+p.name + " " + p.distance + " " + p.quantità );

                System.out.println("leggo questo p.getquatità :"+p.quantità );
                //}
                //else{
                System.out.println("leggo questo in p.quantità: " + p.getQuantità());
                int quantitaInt= Integer.parseInt(p.getQuantità() );
                totalAmount+=p.distance * quantitaInt;

                //}
            }

        }
      Toast.makeText(getActivity(), result+"\n"+"Total Amount:="+totalAmount, Toast.LENGTH_LONG).show();
        System.out.println("leggo result e total amount: " + result + " " + totalAmount);


        //Integer.toString(totalAmount);
    //  Intent i = new Intent(getActivity(), TwoFragment.class);
        /*i.putExtra("NomeDati1", result);
        i.putExtra("NomeDati2", String.valueOf(totalAmount));
        startActivity(i);
*/    
    }    
}

这是主要的

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

class Planet {

    String name;
    int distance;
    String quantità;
    String valuta;
    boolean selected = false;



    public Planet(String name, int distance, String valuta) {
        super();
        this.name = name;
        this.distance = distance;
        this.valuta = valuta;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getDistance() {
        return distance;
    }

    public void setDistance(int distance) {
        this.distance = distance;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

    public String getQuantità() {
        return quantità;
    }

    public void setQuantità(String quantità) {
        this.quantità = quantità;
    }
    public String getValuta() {
        return valuta;
    }

    public void setValuta(String valuta) {
        this.valuta = valuta;
    }

}

  class PlanetAdapter extends ArrayAdapter<Planet> implements CompoundButton.OnCheckedChangeListener

{

    private List<Planet> planetList;
    private Context context;
    ArrayList<Planet> objects;


    public  PlanetAdapter(List<Planet> planetList, Context context) {
        super(context, R.layout.single_listview_item, planetList);
        this.planetList = planetList;
        this.context = context;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    }


    public  class PlanetHolder  {
        public TextView planetName;
        public TextView distView;
        public TextView valuta;
        public CheckBox chkBox;
        public EditText edit;
        public String quantità;



    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

View row = convertView;
        PlanetHolder holder = null;
        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(R.layout.single_listview_item, parent, false);
            holder = new PlanetHolder();
            holder.planetName = (TextView) row.findViewById(R.id.name);
            holder.distView = (TextView) row.findViewById(R.id.dist);
            holder.valuta = (TextView) row.findViewById(R.id.valuta);
            holder.chkBox = (CheckBox) row.findViewById(R.id.chk_box);
            holder.edit = (EditText) row.findViewById(R.id.editText);
            holder.edit.setVisibility(View.GONE);
            holder.edit.setEnabled(false);
            row.setTag(holder);
        } else {
            holder = (PlanetHolder) row.getTag();
        }
        final Planet p = planetList.get(position);

        holder.chkBox.setOnCheckedChangeListener(PlanetAdapter.this);
        final PlanetHolder finalHolder = holder;
        holder.chkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (finalHolder.chkBox.isChecked()) {
                    finalHolder.edit.setVisibility(View.VISIBLE);
                    finalHolder.edit.setEnabled(true);
                    finalHolder.edit.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            p.setQuantità(finalHolder.edit.getText().toString().trim());
                            System.out.println(finalHolder.edit.getText().toString().trim());
                        }
                    });
                } else {
                    finalHolder.edit.setVisibility(View.GONE);
                    finalHolder.edit.setEnabled(false);
                    finalHolder.edit.setText(null);
                }
            }
        });
        holder.planetName.setText(p.getName());
        holder.distView.setText("" + p.getDistance());
        holder.valuta.setText(""+p.getValuta());
        holder.chkBox.setChecked(p.isSelected());
        holder.chkBox.setTag(p);
        holder.edit.setEnabled(false);

        return row;
    }


    ArrayList<Planet> getBox() {
        ArrayList<Planet> box = new ArrayList<Planet>();
        for (Planet p : planetList) {
            if (p.selected)
                box.add(p);
        }
        return box;
    }


}

4 个答案:

答案 0 :(得分:1)

Toast.makeText(getActivity(), result+"\n"+"Total Amount:="+totalAmount, Toast.LENGTH_LONG).show();
        System.out.println("leggo result e total amount: " + result + " " + totalAmount);

将此行放在showResult()方法

答案 1 :(得分:0)

尝试在上下文中使用getActivity().getApplicationContext(),这应该有用!!

答案 2 :(得分:-1)

getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer, new MyListFragment()).commit();

答案 3 :(得分:-1)

Toast.makeText(getActivity(), result+"\n"+"Total Amount:="+totalAmount, Toast.LENGTH_LONG).show();
    System.out.println("leggo result e total amount: " + result + " " + totalAmount);

将此代码放在showResult()方法中 并使用getApplicationContext()而不是getAtcivity(),因为有时getActivity会返回null。