ListView Checkbox每隔4个项目重复一次

时间:2016-05-28 11:00:06

标签: android listview checkbox

我有一个填充了复选框的ListView。当我点击一个复选框时,第四个复选框及其乘法(第8,第12等等)也会自动检查,而不会点击它们。

更新代码

public class CarActivity extends Activity implements
        DownloadResultReceiver.Receiver {

    private DownloadResultReceiver mReceiver;
    List<Item> items;
    String carNumber;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Button submit;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car);


        Bundle b = this.getIntent().getExtras();
        String url = b.getString("url");
        carNumber = b.getString("carNumber");
        String model = b.getString("model");
        final String category = b.getString("category");


        submit = (Button) findViewById(R.id.submit);

        submit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                String url = null;
                if (category.equals("الأجهزة الطبية")) {
                    url = "http://192.168.1.136/final/medical_equipments/insert.php";
                } else if (category.equals("الأفراد")) {
                    url = "http://192.168.1.136/final/persons/insert.php";
                } else if (category.equals("التدريب")) {
                    url = "http://192.168.1.136/final/training/insert.php";
                } else if (category.equals("الصيانة الميكانيكية")) {
                    url = "http://192.168.1.136/final/mechanical_repair/insert.php";
                } else if (category.equals("الصيانة الطبية")) {
                    url = "http://192.168.1.136/final/medical_repair/insert.php";
                } else if (category.equals("المستلزمات الطبية")) {
                    url = "http://192.168.1.136/final/medical_requirments/insert.php";
                } else if (category.equals("تجهيزات كابينة السائق")) {
                    url = "http://192.168.1.136/final/driver_equipment/insert.php";
                } else if (category.equals("سجلات السيارة")) {
                    url = "http://192.168.1.136/final/car_records/insert.php";
                }

                new SubmitItems().execute(url);

            }
        });


        //getActionBar().setTitle("");
        //if (Connection.isConnectedToInternet(getApplicationContext())) {
        if (true) {
            /* Starting Download Service */
            mReceiver = new DownloadResultReceiver(new Handler());
            mReceiver.setReceiver(this);
            Intent intent = new Intent(Intent.ACTION_SYNC, null, this,
                    DownloadService.class);

            /* Send optional extras to Download IntentService */
            intent.putExtra("url", url);
            String data = null;
            try {
                data = URLEncoder.encode("model", "UTF-8") + "=" + URLEncoder.encode(model, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            intent.putExtra("data", data);
            intent.putExtra("receiver", mReceiver);
            intent.putExtra("requestId", 101);
            startService(intent);
        } else {
            new AlertDialog.Builder(CarActivity.this)
                    .setTitle("Oops")
                    .setMessage("No Internet Connection!")
                    .setPositiveButton("Ok",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int id) {
                                }
                            }).show();

        }

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Car Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.example.khloud.qery/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Car Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.example.khloud.qery/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }


    class SubmitItems extends AsyncTask<String, String, String> {
        private ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(CarActivity.this);
            pDialog.setMessage("Attempting submitting...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            String url = args[0];


            try {
                for (Item item : items) {
                    String data = URLEncoder.encode("carNumber", "UTF-8") + "=" + URLEncoder.encode(carNumber, "UTF-8") + "&" +
                            URLEncoder.encode("itemName", "UTF-8") + "=" + URLEncoder.encode(item.getName(), "UTF-8") + "&" +
                            URLEncoder.encode("found", "UTF-8") + "=" + URLEncoder.encode(item.getFound() + "", "UTF-8") + "&" +
                            URLEncoder.encode("notFound", "UTF-8") + "=" + URLEncoder.encode(item.getNotFound() + "", "UTF-8") + "&" +
                            URLEncoder.encode("working", "UTF-8") + "=" + URLEncoder.encode(item.getWorking() + "", "UTF-8") + "&" +
                            URLEncoder.encode("notWorking", "UTF-8") + "=" + URLEncoder.encode(item.getNotWorking() + "", "UTF-8") + "&" +
                            URLEncoder.encode("notes", "UTF-8") + "=" + URLEncoder.encode(item.getNotes(), "UTF-8");
                    Connection.getJSONfromURL(url, data);
                }

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                return null;
            }

            return "save Successfully";
        }

        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
            if (file_url != null) {
                Toast.makeText(CarActivity.this, file_url, Toast.LENGTH_SHORT)
                        .show();
                finish();
            }

        }

    }

    @Override
    public void onReceiveResult(int resultCode, Bundle resultData) {
        switch (resultCode) {
            case DownloadService.STATUS_RUNNING:
                break;
            case DownloadService.STATUS_FINISHED:
                String response = resultData.getString("result");
                if (response == null)
                    Log.d("respooo", "null");
                intializeProcess(response);
                break;
            case DownloadService.STATUS_ERROR:
            /* Handle the error */
                String error = resultData.getString("error");
                Log.d("error", error);
                break;
        }
    }


    private void intializeProcess(String response) {
        Log.d("response", response);
        ItemsRetrieval itemRetrieval = new ItemsRetrieval();
        if (itemRetrieval.GetMainAPI(response)) {
            // load.setVisibility(View.GONE);
            items = itemRetrieval.getItems();

            Log.e("Items Size", items.size() + "");

            doWork();
            //getActionBar().setTitle(singer.getName());
            //getActionBar().setIcon(R.drawable.singer_icon);


        }
    }

    private void doWork() {
        populateListView();
        registerClickCallback();
    }




    private void populateListView() {
        ArrayAdapter<Item> adapter = new MyListAdapter();
        ListView list = (ListView) findViewById(R.id.items);
        list.setAdapter(adapter);
    }

    private void registerClickCallback() {
        ListView list = (ListView) findViewById(R.id.items);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {



            @Override
            public void onItemClick(final AdapterView<?> parent, View viewClicked,
                                    final int position, long id) {


                final Item item = items.get(position);


       ///////////////////////////////////




            }
        });





            }



    ///////////////////

    private class MyListAdapter extends ArrayAdapter<Item> {


        public MyListAdapter() {
            super(CarActivity.this, R.layout.item, items);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // Make sure we have a view to work with (may have been given null)
            Item item = items.get(position);
            ViewHolder holder = null;

            View itemView = convertView;
            if (itemView == null){
                itemView = getLayoutInflater().inflate(R.layout.item, parent, false);
                holder = new ViewHolder();
                holder.textView1  = (TextView) itemView.findViewById(R.id.textView1);

                itemView.setTag(holder);
            }
            else{
                holder = (ViewHolder) itemView.getTag();
            }
            //set the value of the item name   - you only do it here to avoid repeating the items when convertView is NULL (happens when you scroll to end of list)

            holder.textView1.setText(item.getName());

            return itemView;
        }

        private class ViewHolder {
            TextView textView1;
        }
    }}`

1 个答案:

答案 0 :(得分:1)

您应该为适配器实施ViewHolder模式 - 更改

adapter code into something like this:

private class MyListAdapter extends ArrayAdapter<Item> {

    public MyListAdapter() {
        super(CarActivity.this, R.layout.item, items);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Make sure we have a view to work with (may have been given null)
        Item item = items.get(position);
        ViewHolder holder = null;

        View itemView = convertView;
        if (itemView == null){
            itemView = getLayoutInflater().inflate(R.layout.item, parent, false);
            holder = new ViewHolder();
            holder.textView1  = (TextView) itemView.findViewById(R.id.textView1); 

            itemView.setTag(holder);
        }
        else{
          holder = (ViewHolder) itemView.getTag();
        }
         //set the value of the item name   - you only do it here to avoid repeating the items when convertView is NULL (happens when you scroll to end of list)

        holder.textView1.setText(item.getName());

        return itemView;
    }

    private class ViewHolder {  
        TextView textView1; 
    }
}

我希望这会有所帮助。 顺便说一句,我认为您的问题与讨论herehere非常相似。