本文介绍了问题来选择onViewCreated()中的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

onViewCreated()中启动应用程序时,我需要自动选择所有复选框.

I need to select automatically all checkboxes when I launch my app in 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中,我连续5次看到true,但没有看到复选框处于选中状态(因此视图).

In LOGCAT I see true for 5 times but I don't see checkboxes checked (so the View).

谁可以帮助我?

这就是全部代码:

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

自定义适配器:

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

推荐答案

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

Try with plAdapter.notifyDataSetChanged() after for loop ends. In adapter after set the value, you have to refresh the listview.

这篇关于问题来选择onViewCreated()中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 10:55