在onViewCreated()中选择复选框的问题

时间:2017-05-18 19:20:32

标签: java android listview arraylist checkbox

我需要在onViewCreated()启动我的应用时自动选择所有复选框。

使用此代码:

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

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

    for (int i=0;i<plAdapter.getCount();i++) {
        Planet p=plAdapter.getItem(i);
        //if(p.getId()==3) {
            //System.out.println("NOME PIANETA:" + p.getName());
            p.setSelected(true);
        //}
        p.setSelected(true);

        System.out.println("NOME PIANETA2:" + p.isSelected());
    }
}

在LOGCAT中,我看到true 5次,但我没有看到复选框(因此查看)。

谁能帮帮我?

这是所有代码:

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

}


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

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

            //if(p.getId()==3) {

            //  System.out.println("NOME PIANETA:" + p.getName());
                p.setSelected(true);
            //}

            System.out.println("NOME PIANETA2:" + p.isSelected());
        }
    }



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

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 ;

    public PlanetAdapter(List<Planet> planetList, Context context,Integer[] imageId) {
        super(context, R.layout.single_listview_item,planetList);
        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);


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

         }
        final PlanetHolder finalHolder2 = holder;


        holder.chkBox.setOnCheckedChangeListener(PlanetAdapter.this);



        // final BirraHolder finalHolder = birraHolder;
        final PlanetHolder finalHolder = holder;
        Planet z=getItem(position);
        System.out.println(z);
        final PlanetHolder finalHolder1 = holder;
        final PlanetHolder finalHolder3 = holder;

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


                  /*  SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = states.edit();
                    editor.putBoolean("holder.chkBox" + finalHolder.planetName.getText().toString(), true);
                    editor.commit();*/
                    //Utility.putPizzaItem(p);
                    //Utility.getPizzaItem(p);
                } else {
                    finalHolder.spinner.setVisibility(View.GONE);
                    finalHolder.np.setVisibility(View.GONE);
                    finalHolder.np.setValue(0);
                }
            }
        });

        return row;
    }

2 个答案:

答案 0 :(得分:3)

在for循环结束后尝试使用plAdapter.notifyDataSetChanged()。在设置值后的适配器中,您必须刷新列表视图。

答案 1 :(得分:2)

在您的适配器getView()方法中,请尝试以下操作:

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

    ...........
    ...................

    if (isChecked) {
        holder.chkBox.setChecked(true);

        holder.spinner.setVisibility(View.VISIBLE);
        holder.np.setVisibility(View.VISIBLE);
    } else {
        holder.chkBox.setChecked(false);

        holder.spinner.setVisibility(View.GONE);
        holder.np.setVisibility(View.GONE);
     }

     .........
     ...................

     return row;
}