【问题标题】:Pre-fill the CheckedTextViews in a ListView在 ListView 中预填充 CheckedTextViews
【发布时间】:2013-05-18 19:10:23
【问题描述】:

这是我在 StackOverFlow 上的第一个问题,我通常总是自己找到答案,但我真的被困在一个奇怪的问题上,我将在这里解释:

我在片段活动中实现了一个 ListView,这个 listview 包含一个与我从 SQLLite 数据库获取的当前记录相关的类别列表。

一切正常,我创建了一个 SimpleCursorAdapter 来从数据库中检索数据,并在 ListView 中正确显示类别。 问题与复选框的预填充有关(它是一个多选列表),取决于我如何尝试预先检查复选框,我得到 2 种情况:

首先,复选框已预先选中,但我无法再通过单击它们来切换复选框。其次,单击可以很好地切换复选框,但它们不再被预先选中......

这是我遇到问题的代码部分:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //super.onCreate(savedInstanceState);
    View v = inflater.inflate(R.layout.rate_fragment, container,false);

    dbCategories = "";
    displayCategories = resources.getText(R.string.no_categories).toString();


    /** INITIALIZATION */
    mViewSwitcher = (ViewSwitcher)v.findViewById(R.id.profileSwitcher);

    /** Edition view */
    rateGroup = (RadioGroup)v.findViewById(R.id.rate_group);
    rateOne = (RadioButton)v.findViewById(R.id.one_button);
    rateOne.setTag(1);
    rateTwo = (RadioButton)v.findViewById(R.id.two_button);
    rateTwo.setTag(2);
    rateThree = (RadioButton)v.findViewById(R.id.three_button);
    rateThree.setTag(3);
    rateFour = (RadioButton)v.findViewById(R.id.four_button);
    rateFour.setTag(4);
    rateFive = (RadioButton)v.findViewById(R.id.five_button);
    rateFive.setTag(5);

    descET = (EditText)v.findViewById(R.id.editdescription);
    descTextSize = descET.getTextSize();
    descET.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    categoriesTV_edit = (TextView)v.findViewById(R.id.edit_categories);
    categoriesBT = (Button) v.findViewById(R.id.select_categories);
    categoriesBT.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            View categoriesListTitle = getActivity().getLayoutInflater().inflate(R.layout.category_list_title, null);
            AlertDialog.Builder alt_bld = new AlertDialog.Builder(v.getContext()).setCustomTitle(categoriesListTitle);

            categories = db.getAllCategoriesByRate(currentRate);
            categoriesList = new ListView(getActivity());
            categoriesList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);                
            categoriesList.setClickable(true);

            String[] fromColumns = new String[] {
                    DatabaseHandler.CATEGORY_NAME
            };
            int[] toViews = new int[]{
                    R.id.cat_checked
            };

            //mAdapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_multiple_choice, categories, fromColumns, toViews, 0);
            mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.category_item, categories, fromColumns, toViews, 0);

            mAdapter.setViewBinder(new ViewBinder() {
                public boolean setViewValue(View view, Cursor cursor, int columnIndex) {

                    if (columnIndex == 1) {                     

                        CheckedTextView categRow = (CheckedTextView) view;

                        String catName = cursor.getString(1);
                        mAdapter.setViewText((TextView) view, catName);

                        int catChecked = cursor.getInt(2);
                        //boolean checkedCat = catChecked==1;
                        //categoriesList.setItemChecked(cursor.getPosition(),checkedCat);
                        categRow.setChecked(catChecked==1);

                        int catID = cursor.getInt(0);
                        categRow.setTag(catID);
                        return true;
                    }
                    else {
                        return false;
                    }
                }
            });

            categoriesList.setAdapter(mAdapter);

            alt_bld.setView(categoriesList);

有一种情况或另一种情况,都取决于这两行:

//boolean checkedCat = catChecked==1;
//categoriesList.setItemChecked(cursor.getPosition(),checkedCat);

如果它们被评论,复选框不会被预先选中,但点击的切换是有效的。但是,如果我将这些行注释掉,切换将不再起作用,但类别已被预先检查。

我也不明白的是这条线不起作用:

 categRow.setChecked(catChecked==1);

但是这个运行良好(我成功检索到标签):

 categRow.setTag(catID);

所以我希望有人能成功地向我解释我做错了什么,我想我在这里误解了一些东西......

注意:我从光标“类别”中得到 3 列,第一列是类别的 ID,第二列是名称,第三列是状态:检查与否(1或 0)。

提前感谢您的宝贵时间。

【问题讨论】:

    标签: android android-listview android-cursor checkedtextview


    【解决方案1】:

    最后我创建了自己的自定义适配器,这样我至少可以更容易地理解发生了什么。

    实际上,我必须创建几个多选列表,其中一些填充了来自数据库的数据,另一些则来自共享首选项。

    为了显示来自数据库的数据,我创建了以下适配器(我注释掉了有关图标的行,因为我还没有设置它们):

    public class CategoriesLVAdapter extends BaseAdapter {
    private Context mContext;
    private LayoutInflater mInflater;
    private List<Category> categoriesList;
    
    // Constructor
    public CategoriesLVAdapter(Context c, List<Category> categories_list){
        mContext = c;
        mInflater = LayoutInflater.from(c);
        categoriesList = categories_list;
    }
    
    public List<Category> getCategoriesList(){
        return categoriesList;
    }
    
    @Override
    public int getCount() {
        return categoriesList.size();
    }
    
    @Override
    public Object getItem(int position) {
        return categoriesList.get(position);
    }
    
    @Override
    public long getItemId(int position) {
        return categoriesList.get(position).getID();
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.categories_list_row, null);
            //convertView.setLayoutParams(new ListView.LayoutParams(200, 90));
            holder = new ViewHolder();
            holder.title = (TextView) convertView.findViewById(R.id.categories_list_row_tv);
            //holder.icon = (ImageView) convertView.findViewById(R.id.categories_list_row_iv);
    
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();         
        }
    
        //holder.icon.setImageResource(categoriesList.get(position).getDrawableID());
        //holder.icon.setAdjustViewBounds(true);  
        //holder.icon.setScaleType(ImageView.ScaleType.CENTER_CROP);        
        holder.title.setText(categoriesList.get(position).getName());
    
        return convertView;
    }
    
    static class ViewHolder {
        TextView title;
        //ImageView icon;
    }
    

    }

    在我的活动中,当调用 AlertDialog 来填充 ListView 时,我使用此适配器,然后我使用共享首选项中保存的最后一个类别预先选择类别:

    private void categoriesFilter(){
        AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
        alt_bld.setTitle(resources.getText(R.string.select_categories).toString());
    
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);   
        View layout = inflater.inflate(R.layout.categories_list,(ViewGroup) findViewById(R.id.categories_layout_root));
        categoriesLV = (ListView) layout.findViewById(R.id.categories_list);
    
        alt_bld.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                String selectedCategoriesString = getSelectedValues(categoriesLV);
    
                //Update the shared preferences
                prefs.edit().putString(RateDayApplication.PREF_KEY_CATEGORIES, selectedCategoriesString).commit();
    
                updateFilterDisplay(resources.getText(R.string.cat_title).toString(), selectedCategoriesString, searchedCategoriesTV, "Category");
            }
        });
    
        alt_bld.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.cancel();
            }
        });
    
        String selectedCategoriesString = prefs.getString(RateDayApplication.PREF_KEY_CATEGORIES, new String());
        categoriesLV.setAdapter(new CategoriesLVAdapter(this, categoriesList));
    
        String[] selectedCategoriesArray = selectedCategoriesString.split(",");
    
        int categoriesLVLength = categoriesLV.getCount();
        for(int i = 0; i < categoriesLVLength; i++){
            int categoryID = ((Category) categoriesLV.getItemAtPosition(i)).getID();
            if(Arrays.asList(selectedCategoriesArray).contains(String.valueOf(categoryID))){
                categoriesLV.setItemChecked(i, true);
            }
        }
    
        alt_bld.setView(layout);
    
        AlertDialog alert = alt_bld.create();   
        alert.show();
    }
    

    最后,这是我从我的数据库处理程序中调用的函数以获取类别列表:

    // Getting All Categories By ID desc
        public List<Category> getCategoriesList() {
            String selectQuery = "SELECT " + CATEGORY_ID + ", " + CATEGORY_NAME + " FROM " + CATEGORY_TABLE + " ORDER BY " + CATEGORY_ID + " ASC";
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null); 
    
            List<Category> categoriesList = new ArrayList<Category>();//String[] categoriesList = {};
    
            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    Category category = new Category(cursor.getInt(0), cursor.getString(1), false);
                    categoriesList.add(category);
                } while (cursor.moveToNext());
            }
    
            cursor.close();
            db.close();
            return categoriesList;
        }
    

    我认为我之前的问题是因为“setItemChecked”函数有点误导,因为它并不意味着一定要检查任何东西。 当您使用“setItemChecked”函数时,列表视图中的项目会被选中,有或没有复选框(我的行只包含文本视图)。

    在我的列表中选择的行以不同的颜色显示,我认为这对于简单的多选列表来说已经足够了。

    我使用的布局很简单,“categories_list”在LinearLayout中包含一个ListView,“categories_list_row”在LinearLayout中包含一个TextView。

    希望它可以指导某人!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多