ListView의 배치 로드 및 페이지 로드

35352 단어
1. 분할 로드의 원리: 사실 분할 로드는 DAO 제어 데이터베이스에서 고정된 항목의 데이터를 되돌려주고ListView의 페이지에 표시하는 것이다.
public class CallSafeActivity2 extends BaseActivity implements OnClickListener{

    private TextView tv_title;
    private ImageView iv_left;
    private ImageView iv_right;
    private ListView list_view;
    private List mBlackNumbers;
    //         
    private int pageSize=20;
    //      
    private int mCurrentPage=0;
    //     
    private int totalPage;
    private EditText et_page;
    private TextView current_count_page;
    private BlackNumberDao dao;

    /**
     *    UI
     */
    @Override
    protected void initUI() {
        setContentView(R.layout.activity_call_safe2);
        list_view = (ListView) findViewById(R.id.list_view);
        et_page = (EditText) findViewById(R.id.et_page);
        current_count_page = (TextView) findViewById(R.id.current_count_page);

    }


    /**
     *       
     */
    @Override
    protected void initTiltBar() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        iv_left = (ImageView) findViewById(R.id.iv_left);
        iv_right = (ImageView) findViewById(R.id.iv_right);
        tv_title.setText("     ");
        iv_left.setVisibility(View.INVISIBLE);
        iv_right.setVisibility(View.VISIBLE);
        iv_right.setOnClickListener(this);
    }

    /**
     *      
     */
    @Override
    protected void initData() {
        dao = new BlackNumberDao(this);
        //      listView       
        //mBlackNumbers = dao.findAll();
        //CallSafeAdapter adapter = new CallSafeAdapter(mBlackNumbers, this);
        //list_view.setAdapter(adapter);

        //    ,totalPage     ,mCurrentPage      
        totalPage = dao.getTotalNumber()/pageSize;
        current_count_page.setText(mCurrentPage+"/"+(totalPage-1));
        new Thread(){
            public void run(){
                //             
                mBlackNumbers= dao.findPar(pageSize, mCurrentPage);
                handler.sendEmptyMessage(0);
            }
        }.start();
    }
    Handler handler=new Handler(){
        public void handleMessage(Message msg) {
            CallSafeAdapter adapter=new CallSafeAdapter(mBlackNumbers, CallSafeActivity2.this);
            list_view.setAdapter(adapter);
        };
    };
    /**
     * listView      
     * @author dell
     *
     */
    private class CallSafeAdapter extends MyBaseAdapter<BlackNumber>{
        //MyBaseAdapter     
        public CallSafeAdapter(List mLists, Context mContext) {
            super(mLists, mContext);
        }

        private TextView tv_number;
        private TextView tv_mode;
        private ImageView iv_delete;
        private View view;
        private ViewHolder holder;

        //listView       
        public View getView(int position, View convertView, ViewGroup parent) {

            // convertView       200%,           findViewById,pull            
            if (convertView==null) {
                view = View.inflate(CallSafeActivity2.this, R.layout.item_call_safe, null);

                //viewHold    ,      50%,                 findViewById,      
                holder = new ViewHolder();

                holder.tv_number = (TextView) view.findViewById(R.id.tv_number);
                holder.tv_mode = (TextView) view.findViewById(R.id.tv_mode);
                holder.iv_delete = (ImageView) view.findViewById(R.id.iv_delete);

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

            holder.tv_number.setText(mLists.get(position).getNumber());
            String mode = mLists.get(position).getMode();
            if (mode.equals("1")) {
                holder.tv_mode.setText("    ");
            } else if (mode.equals("2")) {
                holder.tv_mode.setText("    ");
            } else if (mode.equals("3")) {
                holder.tv_mode.setText("    ");
            }
            return view;
        }

    }
    /**
     * listView   ,       50%。  findViewById   ,         
     * @author dell
     *
     */
    static class ViewHolder{
        TextView tv_number;
        TextView tv_mode;
        ImageView iv_delete;
    }


    public void onClick(View v) {

    }
    /**
     *    
     */
    public void pre(View view){
        if (mCurrentPage<=0) {
            ToastUtils.showSafeToast(CallSafeActivity2.this, "       ");
            return;
        }
        mCurrentPage--;
        initData();
    }
    /**
     *    
     */
    public void next(View view){
        if(mCurrentPage >= totalPage - 1 ){
            ToastUtils.showSafeToast(CallSafeActivity2.this, "       ");
            return ;
        }
        mCurrentPage++;
        initData();
    }
    /**
     *      
     * @param view
     */
    public void jump(View view){
        String str_page = et_page.getText().toString().trim();
        if(TextUtils.isEmpty(str_page)){
            ToastUtils.showSafeToast(CallSafeActivity2.this, "     ");
        }else{
            //     
            int number = Integer.parseInt(str_page);
            //          
            if(number < 0 || number > totalPage - 1){
                ToastUtils.showSafeToast(CallSafeActivity2.this, "       ");

            }else{
                mCurrentPage = number;
                initData();
            }
        }
    }


}

해당 DAO 클래스:
public class BlackNumberDao {

    private BlackNumberSQLiteOpenHelper helper;
    private SQLiteDatabase db;

    public BlackNumberDao(Context context) {
        helper = new BlackNumberSQLiteOpenHelper(context);
    }
    /**
     *         
     * @param number
     * @param mode
     * @return
     */
    public boolean add(String number,String mode){
        db = helper.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put("number",number);
        values.put("mode", mode);
        long rawId = db.insert("blacknumber", null, values);
        if (rawId==-1) {
            //    
            return false;
        }else {
            //    
            return true;
        }
    }
    /**
     *          
     * @param number
     * @return
     */
    public boolean delete(String number){
        db = helper.getWritableDatabase();
        int rowNumber = db.delete("blacknumber", "number=?", new String[]{number});
        if (rowNumber==0) {
            return false;
        }else {
            return true;
        }
    }
    /**
     *        
     * @param number
     * @param newmode
     * @return
     */
    public boolean changeNumberMode(String number,String newmode){
        db = helper.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put("mode", newmode);
        int rowNumber = db.update("blacknumber", values, "number=?", new String[]{number});
        if (rowNumber == 0) {
            return false;
        } else {
            return true;
        }
    }
    /**
     *               
     * 
     * @param number
     * @return
     */
    public String find(String number) {
        String mode = "";
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.query("blacknumber", new String[] { "mode" },
                "number=?", new String[] { number }, null, null, null);
        if (cursor.moveToNext()) {
            mode = cursor.getString(0);
        }
        cursor.close();
        db.close();
        return mode;
    }
    /**
     *       
     * @return
     */
    public List findAll(){
        List list=new ArrayList();
        db = helper.getWritableDatabase();
        Cursor cursor = db.query("blacknumber", new String[]{"number","mode"}, null , null, null, null, null);
        while (cursor.moveToNext()) {
            BlackNumber blackNumber = new BlackNumber();
            blackNumber.setNumber(cursor.getString(0));
            blackNumber.setMode(cursor.getString(1));
            list.add(blackNumber);
        }
        cursor.close();
        db.close();
        return list;
    }
    /**
     *     
     * @param pageSize          
     * @param startIndex        
     * @return
     */
    public List findPar(int pageSize,int startIndex){
        List list = new ArrayList();
        db = helper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select number,mode from blacknumber limit ? offset ?", new String[]{String.valueOf(pageSize),String.valueOf(startIndex*pageSize)});
        while (cursor.moveToNext()) {
            BlackNumber blackNumber = new BlackNumber();
            blackNumber.setNumber(cursor.getString(0));
            blackNumber.setMode(cursor.getString(1));
            list.add(blackNumber);
        }
        cursor.close();
        db.close();
        return list;
    }

    /**
     *     
     * @param pageSize          
     * @param startIndex        
     * @return
     */
    public List findPar2(int pageSize,int startIndex){
        List list = new ArrayList();
        db = helper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select number,mode from blacknumber limit ? offset ?", new String[]{String.valueOf(pageSize),String.valueOf(startIndex)});
        while (cursor.moveToNext()) {
            BlackNumber blackNumber = new BlackNumber();
            blackNumber.setNumber(cursor.getString(0));
            blackNumber.setMode(cursor.getString(1));
            list.add(blackNumber);
        }
        cursor.close();
        db.close();
        return list;
    }
    /**
     *      
     * @return
     */
    public int getTotalNumber(){
        db = helper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select count(*) from blacknumber", null);
        cursor.moveToNext();
        int count = cursor.getInt(0);
        cursor.close();
        db.close();
        return count;
    }
}

2. 배치 로딩의 원리는 페이지 로딩의 원리와 같다. ListView가 아래와 같이 아래로 내려가는지 판단한 다음에 데이터를 로딩하는 것과 달리 리셋 과정이 있다. 코드는 다음과 같다.
설명: 세분화 로딩, setOnScrollListener 감청기 추가,listview.getLastVisiblePosition() 방법
public class CallSafeActivity extends BaseActivity implements OnClickListener{

    private TextView tv_title;
    private ImageView iv_left;
    private ImageView iv_right;
    private ListView list_view;
    private List mBlackNumbers;
    //         
    private int maxCount=20;
    //      
    private int startIndex=0;
    //     
    private int totalNumber;
    private BlackNumberDao dao;

    /**
     *    UI
     */
    @Override
    protected void initUI() {
        setContentView(R.layout.activity_call_safe);
        list_view = (ListView) findViewById(R.id.list_view);
        list_view.setOnScrollListener(new OnScrollListener() {
            //            (     。。。)
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                //         
                case OnScrollListener.SCROLL_STATE_FLING:

                    break;
                //           
                case OnScrollListener.SCROLL_STATE_IDLE:
                    int lastVisiblePosition = list_view.getLastVisiblePosition();

                    //                          
                    if (lastVisiblePosition==mBlackNumbers.size()-1) {
                        //          
                        startIndex+=maxCount;
                        if (startIndex>=totalNumber) {
                            ToastUtils.showSafeToast(CallSafeActivity.this, "          ");
                            return;
                        }
                        initData();
                    }
                    break;
                //             
                case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:

                    break;
                default:
                    break;
                }
            }
            //        
            public void onScroll(AbsListView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {

            }
        });

    }


    /**
     *       
     */
    @Override
    protected void initTiltBar() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        iv_left = (ImageView) findViewById(R.id.iv_left);
        iv_right = (ImageView) findViewById(R.id.iv_right);
        tv_title.setText("     ");
        iv_left.setVisibility(View.INVISIBLE);
        iv_right.setVisibility(View.VISIBLE);

        //            
        iv_right.setOnClickListener(this);
    }

    /**
     *      
     */
    @Override
    protected void initData() {
        dao = new BlackNumberDao(this);

        //    ,totalPage     ,mCurrentPage      
        totalNumber = dao.getTotalNumber();

        new Thread(){
            public void run(){
                //             。              20       
                if (mBlackNumbers==null) {
                    mBlackNumbers= dao.findPar2(maxCount, startIndex);
                }else {
                    //        ,    
                    mBlackNumbers.addAll(dao.findPar2(maxCount, startIndex));
                }
                handler.sendEmptyMessage(0);
            }
        }.start();
    }
    private CallSafeAdapter adapter;
    Handler handler=new Handler(){
        public void handleMessage(Message msg) {
            if (adapter==null) {
                adapter = new CallSafeAdapter(mBlackNumbers, CallSafeActivity.this);
                list_view.setAdapter(adapter);
            }else {
                //         
                adapter.notifyDataSetChanged();
            }
        };

    };
    private AlertDialog dialog;
    /**
     * listView      
     * @author dell
     *
     */
    private class CallSafeAdapter extends MyBaseAdapter<BlackNumber>{
        //CallSafeAdapter     
        public CallSafeAdapter(List mLists, Context mContext) {
            super(mLists, mContext);
        }

        private TextView tv_number;
        private TextView tv_mode;
        private ImageView iv_delete;
        private View view;
        private ViewHolder holder;

        //listView       
        public View getView(final int position, View convertView, ViewGroup parent) {

            // convertView       200%,           findViewById,pull            
            if (convertView==null) {
                view = View.inflate(CallSafeActivity.this, R.layout.item_call_safe, null);

                //viewHold    ,      50%,                 findViewById,      
                holder = new ViewHolder();

                holder.tv_number = (TextView) view.findViewById(R.id.tv_number);
                holder.tv_mode = (TextView) view.findViewById(R.id.tv_mode);
                holder.iv_delete = (ImageView) view.findViewById(R.id.iv_delete);

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

            holder.tv_number.setText(mLists.get(position).getNumber());
            String mode = mLists.get(position).getMode();
            if (mode.equals("1")) {
                holder.tv_mode.setText("    ");
            } else if (mode.equals("2")) {
                holder.tv_mode.setText("    ");
            } else if (mode.equals("3")) {
                holder.tv_mode.setText("    ");
            }
            //           
            final String number = mLists.get(position).getNumber();
            //          
            holder.iv_delete.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    //          
                    boolean result = dao.delete(number);
                    //    true      
                    if (result) {
                        //             
                        mBlackNumbers.remove(position);
                        //    
                        adapter.notifyDataSetChanged();
                        ToastUtils.showSafeToast(CallSafeActivity.this, "    ");
                    }else {
                        ToastUtils.showSafeToast(CallSafeActivity.this, "    ");
                    }
                }
            });
            return view;
        }

    }
    /**
     * listView   ,       50%。  findViewById   ,         
     * @author dell
     *
     */
    static class ViewHolder{
        TextView tv_number;
        TextView tv_mode;
        ImageView iv_delete;
    }
    /**
     *    
     */
    @Override
    public void onBackPressed() {
        SystemInfo.startActivity(this, MainActivity.class);
        super.onBackPressed();
    }

    /**
     *      
     */
    public void onClick(View v) {
        AlertDialog.Builder builder = new Builder(this);
        final View view = View.inflate(this, R.layout.dialog_add_black_number, null);
        //     
        final TextView et_number = (TextView) view.findViewById(R.id.et_number);
        //  
        Button bt_ok = (Button) view.findViewById(R.id.bt_ok);
        //  
        Button bt_cancel = (Button) view.findViewById(R.id.bt_cancel);
        //    
        final CheckBox cb_phone = (CheckBox) view.findViewById(R.id.cb_phone);
        //    
        final CheckBox cb_sms = (CheckBox) view.findViewById(R.id.cb_sms);

        //       
        bt_cancel.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        //       
        bt_ok.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                //          
                String str_number = et_number.getText().toString().trim();
                //             ,           
                if (TextUtils.isEmpty(str_number)) {
                    ToastUtils.showSafeToast(CallSafeActivity.this, "       ");
                    return;
                }

                /**
                 * 1      +     (    ) 2      3    
                 */
                String mode;
                //                 
                if (cb_phone.isChecked()&&cb_sms.isChecked()) {
                    //    
                    mode="1";
                }else if (cb_phone.isChecked()) {
                    //    
                    mode="2";
                }else if (cb_sms.isChecked()) {
                    //    
                    mode="3";
                }else{
                    ToastUtils.showSafeToast(CallSafeActivity.this, "       ");
                    return;
                }
                BlackNumber blackNumber = new BlackNumber();    

                blackNumber.setNumber(str_number);
                blackNumber.setMode(mode);

                //          ——   
                boolean result = dao.add(str_number, mode);
                //  true      ,    
                if (result) {
                    mBlackNumbers.add(0, blackNumber);
                    adapter.notifyDataSetChanged();
                    ToastUtils.showSafeToast(CallSafeActivity.this, "    ");
                }else{
                    ToastUtils.showSafeToast(CallSafeActivity.this, "    ");
                }
                dialog.dismiss();
            }
        });
        builder.setView(view);
        dialog = builder.show();
    }

}

좋은 웹페이지 즐겨찾기