选中复选框时,列表视图中选择了错误的项目

时间:2015-02-25 04:19:45

标签: android listview

** 当我选择列表视图底部的项目时,它们不会被选中, 而只选择列表中的前四项。因为项目不在视野范围内。 怎么做才能看到这些项目?有时候该项目是随机选择的。 请帮我。 谢谢 这是我的代码**

 Main activity

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;


public class ExceptionAppActivity extends Activity implements OnClickListener, OnItemSelectedListener {

    private final int REQUEST_CODE = 20;
    String flagg;
    String empNm = Constants.Common.STR_BLNK;
    String empCode = Constants.Common.STR_BLNK;

    SessionManager session = null;
    final Context context = this;
    static Typeface custom_font = null;
    TextView lblExcId, lblExcEmpNm, lblExcFrmDt, lblExcFrmDtVal, lblExcToDtVal, lblExcTyp, lblExcStat, lblExcEmpCmt;
    Button btnExcRej, btnExcApp, btnExcSrch, btnExcExit;
    CheckBox cb, chkBox;
    ListView excSrchListView;
    ArrayList<Excp> Results;
    CustomListViewAdapter cla;
    ExceptionAppDao eCon = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.exception_app_activity);

        /* get Resources from Xml file */
        btnExcApp = (Button) findViewById(R.id.btnExcApp);
        btnExcRej = (Button) findViewById(R.id.btnExcRej);
        btnExcSrch = (Button) findViewById(R.id.btnExcSrch);
        btnExcExit = (Button) findViewById(R.id.btnExcExit);
        lblExcEmpNm = (TextView) findViewById(R.id.lblExcEmpNm);
        lblExcFrmDt = (TextView) findViewById(R.id.lblExcFrmDt);
        lblExcFrmDtVal = (TextView) findViewById(R.id.lblExcFrmDtVal);
        lblExcToDtVal = (TextView) findViewById(R.id.lblExcToDtVal);
        lblExcTyp = (TextView) findViewById(R.id.lblExcTyp);
        lblExcStat = (TextView) findViewById(R.id.lblExcStat);
        lblExcEmpCmt = (TextView) findViewById(R.id.lblExcEmpCmt);
        lblExcId = (TextView) findViewById(R.id.lblExcId);
        chkBox = (CheckBox) findViewById(R.id.chkBx);
        excSrchListView = (ListView) findViewById(R.id.excSrchListView);

        // Session Manager
        session = new SessionManager(getApplicationContext());

        custom_font = Typeface.createFromAsset(getAssets(), "fonts/DejaVuSans.ttf");

        // Connection object for Login
        eCon = new ExceptionAppDao(context);
        // get User Details from Session
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap = session.getUserDetails();
        empNm = hashMap.get(SessionManager.KEY_EMP_NM);
        empCode = hashMap.get(SessionManager.KEY_EMP_CODE);

        btnExcApp.setTypeface(custom_font);
        btnExcRej.setTypeface(custom_font);
        btnExcSrch.setTypeface(custom_font);
        btnExcExit.setTypeface(custom_font);
        new SyncData(empCode).execute();

        if (getIntent().getBooleanExtra("EXIT", false)) {
        }
        // on click any button
        addButtonListener();
    }

    /**
     * on click any button
     */
    private void addButtonListener() {
        btnExcApp.setOnClickListener(this);
        btnExcRej.setOnClickListener(this);
        btnExcSrch.setOnClickListener(this);
        btnExcExit.setOnClickListener(this);
    }

    public class SyncData extends AsyncTask<String, String, ArrayList<Excp>> {
        private final ProgressDialog dialog = new ProgressDialog(context);

        List<ExcpMstVo> rtnExcVo = new ArrayList<ExcpMstVo>();
        ExcpMstVo rtnExcMstVo = new ExcpMstVo();
        ArrayList<Excp> resultLst = new ArrayList<Excp>();
        ExceptionService_Service excpServObj = new ExceptionService_Service();
        String syncFlg = Constants.Common.STR_BLNK;
        private View rootView;
        String flag = "";
        int x;
        boolean success = false;
        boolean successSyncFlag = false;
        int countApp = 0;

        public SyncData(String str) {
            syncFlg = str;
        }

        public SyncData(View rootView) {
            // TODO Auto-generated constructor stub
            this.rootView = rootView;
        }

        @Override
        protected ArrayList<Excp> doInBackground(String... params) {
            ExceptionSearchCriteria vo = new ExceptionSearchCriteria();
            ExcpMstVo excpMstVo = new ExcpMstVo();

            try {
                if (syncFlg.equals(empCode)) {
                    vo = setAppData(vo);
                    rtnExcVo = excpServObj.getExceptionPort().searchExceptionApproval(vo);
                    if (!(rtnExcVo.isEmpty())) {
                        System.out.println("rtnExcVo" + rtnExcVo.size());
                        Excp exc = null;
                        for (ExcpMstVo excMstVo : rtnExcVo) {
                            exc = new Excp();
                            exc.setExcId(excMstVo.getExcpId());
                            exc.setEmpCode(excMstVo.getEmpCode());
                            exc.setEmpNm(excMstVo.getEmpnm());
                            exc.setFromDt(excMstVo.getFromDt());
                            exc.setToDt(excMstVo.getToDt());
                            exc.setExcType(excMstVo.getExcpType());
                            exc.setExcStatus(excMstVo.getStatus());
                            exc.setEmpComments(excMstVo.getEmpComments());
                            exc.setExcFor(excMstVo.getExcpFor());
                            exc.setExcReason(excMstVo.getExcpReason());

                            resultLst.add(exc);
                            Results = resultLst;
                            success = true;
                        }
                    }
                } else if (btnExcApp.equals(rootView.getRootView().findViewById(rootView.getId()))) {
                    for (x = excSrchListView.getChildCount() - 1; x >= 0; x--) {
                        cb = (CheckBox) excSrchListView.getChildAt(x).findViewById(R.id.chkBx);
                        if (cb.isChecked()) {

                            excpMstVo = setEmpData();
                            rtnExcMstVo = excpServObj.getExceptionPort().changeExceptionStatus(excpMstVo);

                            System.out.println("rtnExcMstVo:::::" + rtnExcMstVo.getExcpId());
                            System.out.println("rtnExcMstVoStatuss:::::" + rtnExcMstVo.getStatus());
                            countApp++;
                            success = false;
                        }
                    }
                    /*if (countApp == 0) {

                    } else*/ if (countApp > 0) {
                        new SyncData(rootView).execute();
                        //flagg = false;

                    }
                    System.out.println("rtnExcMstVo:::::" + rtnExcMstVo.getExcpId());
                    System.out.println("rtnExcMstVoStatuss:::::" + rtnExcMstVo.getStatus());
                }
                // get dump from device
                CopyDbFromDevice cd = new CopyDbFromDevice();
                cd.copyDbToSdcard(context);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("success::::" + success);
            successSyncFlag = success;
            System.out.println("successSyncFlag::::::::" + successSyncFlag);
            return resultLst;
        }

        private ExcpMstVo setEmpData() {
            ExcpMstVo excpMstVo = new ExcpMstVo();

            excpMstVo.setExcpId(Results.get(x).getExcId());
            excpMstVo.setFromDt(Results.get(x).getFromDt());
            excpMstVo.setStatus(Constants.Status.STAT_APPRV);
            excpMstVo.setMngrComments("");
            excpMstVo.setApprovedBy(empCode);
            excpMstVo.setLoggedInUser(empCode);

            return excpMstVo;
        }

        private ExceptionSearchCriteria setAppData(ExceptionSearchCriteria vo) {
            vo.setApprover(empCode);
            vo.setStatus(Constants.Status.PENDING_APPROVAL);
            return vo;
        }

        protected void onPostExecute(ArrayList<Excp> searchResults) {
            System.out.println("successSyncFlag1::::::::" + successSyncFlag);
            if (successSyncFlag == true) {
                System.out.println("entering ON POST IF");
                cla = new CustomListViewAdapter(ExceptionAppActivity.this, resultLst);
                excSrchListView.setAdapter(cla);
            } 
            else {
                System.out.println("ENTERING ONPOST ELSE PART ");
                System.out.println("successSyncFlag2:;;;;;; " + successSyncFlag);
                System.out.println("success2:::::::::::: " + success);
                System.out.println("NEW METHOD STARTED:::::;");
                if (countApp == 0) {
                    System.out.println("ENTERING COUNT APP 0 ");
                    String flag = "checkItemApp";
                    dialogBox(flag);
                } else {
                    new SyncData(empCode).execute();
                    String flag = "excApp";
                    dialogBox(flag);
                    System.out.println("NEW METHOD STARTED1:::::::::");
                }
            }
            if (this.dialog.isShowing()) {
                this.dialog.dismiss();
            }
        }
    }

    @Override
    public void onClick(View v) {
        int countRej = 0;
        int id = v.getId();
        Intent intent = null;
        if (id == R.id.btnExcApp) {
            new SyncData(v).execute();

        } else if (id == R.id.btnExcRej) {
            int itemPos = 0;
            for (int y = excSrchListView.getChildCount() - 1; y >= 0; y--) {
                cb = (CheckBox) excSrchListView.getChildAt(y).findViewById(R.id.chkBx);
                if (cb.isChecked()) {
                    itemPos = y;
                    cla.notifyDataSetChanged();
                    countRej++;
                }
            }
            // Check if any Exception is selected for Rejection and proceed
            // accordingly
            if (countRej == 1) {
                CustomListViewAdapter cla = (CustomListViewAdapter) excSrchListView.getAdapter();
                Object o = cla.getItem(itemPos);
                Excp selectedExcp = (Excp) o;
                intent = new Intent(getBaseContext(), ExcAppDtlsActivity.class);
                intent.putExtra("selectedExcp", selectedExcp);
                intent.putExtra("readOnly", false);
                startActivityForResult(intent, REQUEST_CODE);

            } else if (countRej == 0) {
                // show dialogue of Select at least 1
                String flag = "checkItemRej";
                dialogBox(flag);

            } else if (countRej > 1) {
                String flag = "checkOnlyOne";
                dialogBox(flag);
                for (int y = excSrchListView.getChildCount() - 1; y >= 0; y--) {
                    cb = (CheckBox) excSrchListView.getChildAt(y).findViewById(R.id.chkBx);
                    if (cb.isChecked()) {
                        itemPos = y;
                        cb.setChecked(false);
                        cla.notifyDataSetChanged();
                    }
                }
            }
        } else if (id == R.id.btnExcSrch) {
            intent = new Intent(this, FurtherSearchActivity.class);
            intent.putExtra("readOnly", false);
            startActivity(intent);
        } else if (id == R.id.btnExcExit) {
            finish();
        }
    }

    /**
     * create alert dialog
     * 
     * @param flag
     */
    private void dialogBox(String flag) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        /*if (flag == "excApp") {
            alertDialogBuilder.setTitle("Exception Approved successfully !");
        } else*/ if (flag == "checkOnlyOne") {
            alertDialogBuilder.setTitle("Please select only one item to reject !");
        } else if (flag == "checkItemRej") {
            alertDialogBuilder.setTitle("Select Exception to Reject !");
        }
        /*else if (flag == "checkItemApp") {
            alertDialogBuilder.setTitle("Select Exception to Approve !");
        } */
        else if (flag == "excRej") {
            alertDialogBuilder.setTitle("Exception Rejected successfully !");
        } 
        /*else {
            alertDialogBuilder.setTitle("Flag - " + flag);
        }*/

        Dialogbox dbx = new Dialogbox(context);
        dbx.createDialogAlert(flag, alertDialogBuilder);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void

    onActivityResult(int requestCode, int resultCode, Intent data) {
        // REQUEST_CODE is defined above
        /*
         * if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) { //
         * Extract name value from result extras flagg =
         * data.getExtras().getString("flagg"); if ((flagg.equals("Approve")) ||
         * (flagg.equals("Reject"))) { for (int x = 0; x <
         * excSrchListView.getChildCount(); x++) { cb = (CheckBox)
         * excSrchListView.getChildAt(x).findViewById( R.id.chkBx); if
         * (cb.isChecked()) { // If Approval is successful remove from list
         * Results.remove(x); cb.setChecked(false); cla.notifyDataSetChanged();
         * if (flagg.equals("Approve")) { dialogBox("excApp"); } else {
         * dialogBox("excRej"); } } }
         * 
         * } }
         */

    }
}

CUSTOM LIST ADAPTER

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TableLayout;
import android.widget.TextView;

import com.eanda.smarttime_mobi.R;
import com.eanda.smarttime_mobi.model.Excp;

public class CustomListViewAdapter extends BaseAdapter {
    private static ArrayList<Excp> searchArrayList;
    HashMap<Integer, Boolean> checked;
    private LayoutInflater mInflater;
    Typeface custom_font = null;

    public CustomListViewAdapter(Context context, ArrayList<Excp> results) {

        searchArrayList = results;
        mInflater = LayoutInflater.from(context);
        checked = new HashMap<Integer, Boolean>(getCount());
        custom_font = Typeface.createFromAsset(context.getAssets(), "fonts/DejaVuSans.ttf");
    }

    public int getCount() {
        return searchArrayList.size();
    }

    public Object getItem(int position) {
        return searchArrayList.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    // created custom view
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.custom_row_view, null);
            holder = new ViewHolder();

            holder.myTable = (TableLayout) convertView.findViewById(R.id.myTable);

            holder.txtExcId = (TextView) convertView.findViewById(R.id.lblExcId);
            holder.txtEmpNm = (TextView) convertView.findViewById(R.id.lblExcEmpNm);
            holder.txtFrmDt = (TextView) convertView.findViewById(R.id.lblExcFrmDtVal);
            holder.txtToDt = (TextView) convertView.findViewById(R.id.lblExcToDtVal);
            holder.txtExcTyp = (TextView) convertView.findViewById(R.id.lblExcTyp);
            holder.txtExcStat = (TextView) convertView.findViewById(R.id.lblExcStat);
            holder.txtEmpCmt = (TextView) convertView.findViewById(R.id.lblExcEmpCmt);
            holder.checkBox = (CheckBox) convertView.findViewById(R.id.chkBx);

            convertView.setTag(holder);
            convertView.setTag(R.id.chkBx, holder.checkBox);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        System.out.println("exception_name" + searchArrayList.get(position).getEmpNm());

        holder.txtExcId.setText(Integer.toString(searchArrayList.get(position).getExcId()));
        holder.txtEmpNm.setText(searchArrayList.get(position).getEmpNm());
        holder.txtFrmDt.setText(searchArrayList.get(position).getFromDt());
        holder.txtToDt.setText(searchArrayList.get(position).getToDt());
        holder.txtExcTyp.setText(searchArrayList.get(position).getExcType());
        holder.txtExcStat.setText(searchArrayList.get(position).getExcStatus());
        holder.txtEmpCmt.setText(searchArrayList.get(position).getEmpComments());

        holder.checkBox.setTag(position);
        holder.checkBox.setChecked(searchArrayList.get(position).isChecked());
        CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.chkBx);

        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                System.out.println("selected");

                int checkBoxId = (Integer) buttonView.getTag();
                holder.checkBox.setChecked(buttonView.isChecked() ? true : false);
                searchArrayList.get(checkBoxId).setChecked(buttonView.isChecked() ? true : false);
                System.out.println("checkBoxId " + checkBoxId);
            }
        });

        holder.checkBox.setTag(position);

        holder.txtExcId.setTypeface(custom_font);
        holder.txtEmpNm.setTypeface(custom_font);
        holder.txtFrmDt.setTypeface(custom_font);
        holder.txtToDt.setTypeface(custom_font);
        holder.txtExcTyp.setTypeface(custom_font);
        holder.txtExcStat.setTypeface(custom_font);
        holder.txtEmpCmt.setTypeface(custom_font);

        return convertView;
    }

    static class ViewHolder {
        TableLayout myTable;
        TextView txtExcId;
        TextView txtEmpNm;
        TextView txtFrmDt;
        TextView txtToDt;
        TextView txtExcTyp;
        TextView txtExcStat;
        TextView txtEmpCmt;
        CheckBox checkBox;

    }

}

1 个答案:

答案 0 :(得分:0)

  • CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.chkBx);

    您已经在持有人中存储了复选框参考,我想知道您为什么要再次初始化它。

  • holder.checkBox.setChecked(buttonView.isChecked() ? true : false);

    当用户点击复选框时,将会更改已检查状态,因此无需再次更改已检查状态。

尝试以下代码

----
----
holder.checkBox.setTag(position);
holder.checkBox.setChecked(searchArrayList.get(position).isChecked());
holder.checkBox..setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                System.out.println("selected");

                int checkBoxId = (Integer) buttonView.getTag();

                searchArrayList.get(checkBoxId).setChecked(buttonView.isChecked() ? true : false);
                System.out.println("checkBoxId " + checkBoxId);
            }
        });
holder.checkBox.setTag(position);
-----
----