动态检查onViewCreated()中的复选框

时间:2017-05-20 13:45:55

标签: java android listview checkbox android-adapter

我需要在午餐时查看onViewCreated()中的所有复选框,但是使用此代码

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


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

        ck=(CheckBox)getView().findViewById(R.id.chk_box);



        displayPlanetList();


        CheckBox chBox;
        for (int i = 0; i < lv.getCount(); i++) {
            view = lv.getAdapter().getView(i, null, null);
            chBox = (CheckBox) view.findViewById(R.id.chk_box);

            chBox.setChecked(true);
        }

        plAdapter.notifyDataSetChanged();



    }

复选框都是未选中的。

我不知道为什么。

我告诉你我的代码!

CUSTOM ADAPTER:

public abstract class PlanetAdapter extends ArrayAdapter<Planet> implements CompoundButton.OnCheckedChangeListener, View.OnClickListener

{
    private List<Planet> planetList;
    private Context context ;
    ArrayList<Birra> objects;
    public boolean Checked;
    private Integer[] imageId;
    String ciao;
    static PlanetAdapter plAdapter;
    String selState ;
    boolean[] itemChecked;

    public PlanetAdapter(List<Planet> planetList, Context context,Integer[] imageId) {
        super(context, R.layout.single_listview_item,planetList);
        //itemChecked = new boolean[planetList.size()];

        this.planetList = planetList;
        this.context = context;
        this.imageId = imageId;

    }

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

    }

    @Override
    public void onClick(View v) {

    }



    public class PlanetHolder {
        public TextView planetName;
        public TextView distView;
        public TextView valuta;
        public CheckBox chkBox;
      //  public EditText edit;
        public TextView caratteristica;
        public TextView id;
        public ImageView imageView;
        public Spinner spinner;
        public NumberPicker np;


    }


    @Override
    public int getCount() {
        return planetList.size();
    }

    @Override
    public Planet getItem(int position) {
        return planetList.get(position);
    }






    @Override
    public View getView(final int position, final View convertView, final 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.spinner = (Spinner) row.findViewById(R.id.simpleSpinner);
            holder.np=(NumberPicker)row.findViewById(R.id.np);
           // holder.edit2 = (EditText) row.findViewById(R.id.editText2);
          //  holder.iterator = (Button) row.findViewById(R.id.iterator);
           // Button iterator=(Button) row.findViewById(R.id.iterator);
           // iterator.setOnClickListener(this.PlanetHolder);
            holder.caratteristica=(TextView) row.findViewById(R.id.caratteristica);
            holder.imageView = (ImageView) row.findViewById(R.id.ivImage);
         //   holder.edit.setVisibility(View.GONE);
         //   holder.edit.setEnabled(false);
            holder.spinner.setVisibility(View.GONE);
          //  holder.edit.setVisibility(View.GONE);


            // holder.id = (TextView) row.findViewById(R.id.id);


            row.setTag(holder);

        } else {
            holder = (PlanetHolder) row.getTag();


        }



        final Planet p = planetList.get(position);
        System.out.println("stampato P" + p);
        holder.imageView.setImageResource(imageId[position]);
        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.caratteristica.setText(p.getCaratteristica());

        // holder.edit.setEnabled(false);

        SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
        boolean isChecked = states.getBoolean("holder.chkBox" + holder.planetName.getText().toString(), false);
        System.out.println(isChecked);


        //holder.chkBox.setChecked(true);


        if (isChecked) {



            holder.spinner.setVisibility(View.VISIBLE);
            holder.np.setVisibility(View.VISIBLE);







        } else {
            holder.chkBox.setChecked(false);
          //  holder.edit.setVisibility(View.GONE);
          //  holder.edit.setEnabled(false);
            holder.spinner.setVisibility(View.GONE);
            holder.np.setVisibility(View.GONE);

         }


        holder.chkBox.setOnCheckedChangeListener(PlanetAdapter.this);



        final PlanetHolder finalHolder = holder;
        Planet z=getItem(position);
        System.out.println(z);



       /* holder.chkBox.setChecked(true);
        holder.spinner.setVisibility(View.VISIBLE);
        holder.np.setVisibility(View.VISIBLE);*/


       // holder.chkBox.setChecked(true);



        holder.chkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (finalHolder.chkBox.isChecked()) {
                   // finalHolder.edit.setVisibility(View.VISIBLE);
                   // finalHolder.edit.setEnabled(true);
                    finalHolder.spinner.setVisibility(View.VISIBLE);
                    finalHolder.np.setVisibility(View.VISIBLE);
                    finalHolder.np.setMaxValue(10);
                    finalHolder.np.setMinValue(0);
                    finalHolder.np.setWrapSelectorWheel(true);
                   // finalHolder.np.getMinValue();
                   // System.out.println("valore picker alla selezione della checkbox"+finalHolder.np.getMinValue());

                    // finalHolder.edit2.setVisibility(View.VISIBLE);
                    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                            getContext(),
                            R.array.country_arrays,
                            android.R.layout.simple_spinner_item);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    //finalHolder.spinner.setAdapter(adapter);
                    finalHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            finalHolder.spinner.setSelection(position);
                          //  selState = finalHolder.spinner.getSelectedItem().toString();
                         //   p.setQuantità(finalHolder.edit.getText().toString().trim());
                            p.setTipo(finalHolder.spinner.getSelectedItem().toString());

                          //  finalHolder.edit2.setText(selState);
                          //  System.out.println(selState);
                            System.out.println("p.getTipo()"+p.getTipo());

                           /* Toast.makeText(
                                    getContext(),
                                    "Clicked on Planet: " + selState + "", Toast.LENGTH_SHORT).show();*/



                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }


                    });
                    finalHolder.np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                        @Override
                        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                            p.setQuantità2(newVal);
                            System.out.println(p.getQuantità2());
                            SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = states.edit();
                            editor.putInt("finalHolder.picker" + finalHolder.planetName.getText().toString(), finalHolder.np.getId());
                            editor.commit();
                        }
                    });



                    SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = states.edit();
                    editor.putBoolean("holder.chkBox" + finalHolder.planetName.getText().toString(), true);
                    editor.commit();



                } else {
                    finalHolder.spinner.setVisibility(View.GONE);
                    finalHolder.np.setVisibility(View.GONE);
                    finalHolder.np.setValue(0);


                }

            }
        });




        return row;
    }

FRGMENT:

public class MyListFragment extends Fragment  /*implements
        CompoundButton.OnCheckedChangeListener, View.OnClickListener*/ {


    ListView lv;
    ArrayList<Planet> planetList;
    static PlanetAdapter plAdapter;
    private TextView txtName;
    private TextView txtEmail;
    private Button btnLogout;
    ListView listView;
    String user = "";
    private Spinner spinner;
    String selState;
    EditText cristo;
    private String zao;
    CheckBox ck;
    //private SQLiteHandler db;
    private SessionManager session;
    BirraAdapter biAdapter;
    PlanetAdapter.PlanetHolder holder;
    private static Context context = null;
    private static FragmentActivity mInstance;
    ArrayList<Integer> hm=new ArrayList<>();
    HashMap<Integer,String> ar=new HashMap<>();


    Integer[] imageId = {
            R.mipmap.androtuto,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ok,
            /*R.drawable.image6,
            R.drawable.image7
            Environment.getExternalStorageDirectory()" +
                    "                                .getAbsolutePath() + /ordinazioni/16:Maggio:2017-13:36:38 Pm.xml*/

    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        /*try {
            int a=0;
            String status="";
            boolean statuss = false;
            File file = new File(Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/ordinazioni/16:Maggio:2017-21:48:49 PM.xml");
            FileInputStream is = new FileInputStream(file);

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(is);

            Element element = doc.getDocumentElement();
            element.normalize();

            NodeList nList = doc.getElementsByTagName("checkboxes_pizza");

            for (int i = 0; i < nList.getLength(); i++) {
                Node node = nList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element2 = (Element) node;
                    //tv1.setText(tv1.getText()+"\nName : " + getValue("name", element2)+"\n");
                    String id = getValue("id", element2);
                    a = Integer.parseInt(id);
                    status = getValue("status", element2);

                    statuss= Boolean.parseBoolean(status);

                    System.out.println("XML:" + a);

                    hm.add(a);




                    }

                }

            for(int i=0;i<hm.size();i++){
                int z=0;
                z=hm.get(i);
                System.out.println("XML STATUS:" + z);

                for(int j=0;j<plAdapter.getCount();j++){
                    Planet p=plAdapter.getItem(j);

                    System.out.println("XML STATUSS:" + p.getName());


                    if(p.getId()==z){

                        System.out.println("XML STATUSSS:" + p.getName());

                        p.setSelected(statuss);
                    }

                }




            }

        } catch (Exception e) {
            e.printStackTrace();
        }*/



}

    private static String getValue(String tag, Element element) {
        NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
        Node node = nodeList.item(0);
        return node.getNodeValue();
    }




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the custom_spinner_items for this fragment
        //super.onDestroy();

        SharedPreferences settings = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.clear();
        editor.commit();


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




        //ck=(CheckBox)rootView.findViewById(R.id.chk_box);



        //lv = (ListView) rootView.findViewById(R.id.listview);
        //ListAdapter listAdapter = new MyListAdapter(getContext());
        //lv.setAdapter(listAdapter);



        context = getActivity();
        mInstance = getActivity();
        btnLogout = (Button) rootView.findViewById(R.id.btnLogout);


        return rootView;
    }



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


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

        ck=(CheckBox)getView().findViewById(R.id.chk_box);



        displayPlanetList();


        CheckBox chBox;
        for (int i = 0; i < lv.getCount(); i++) {
            view = lv.getAdapter().getView(i, null, null);
            chBox = (CheckBox) view.findViewById(R.id.chk_box);

            chBox.setChecked(true);
        }

        plAdapter.notifyDataSetChanged();



    }



    private void displayPlanetList() {

        planetList = new ArrayList<Planet>();
        planetList.add(new Planet(1, "Margherita", "6", "€", "(pomodoro e mozzarella)"));
        planetList.add(new Planet(2,"Diavola", "7","€","(pomodoro,mozzarella e salsiccia piccante)"));
        planetList.add(new Planet(3,"Bufalina", "5","€","(pomodoro e mozzarella di bufala)"));
        planetList.add(new Planet(4, "Marinara", "5", "€", "(pomodoro)"));
        planetList.add(new Planet(5,"Viennese", "4", "€", "(pomodoro,mozzarella e wrustel)"));

        plAdapter = new PlanetAdapter(planetList, getContext(),imageId) {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String pero="";

                int la=0;
                int pos = lv.getPositionForView(buttonView);

                System.out.println("POS:"+pos);


                if (pos != ListView.INVALID_POSITION) {
                    Planet p = planetList.get(pos);

                    p.setSelected(isChecked);



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


            }

        };

        lv.setAdapter(plAdapter);
    }

1 个答案:

答案 0 :(得分:0)

   `chBox = (CheckBox) view.findViewById(R.id.chk_box);`

您只搜索一个复选框 - &gt; R.id.chk_box。在为。