【问题标题】:How to change background colour in adapter list view in android?如何在android的适配器列表视图中更改背景颜色?
【发布时间】:2014-07-06 04:58:50
【问题描述】:

在适配器列表视图中,第一次单击行的列表视图,它不工作,但第二次工作,行背景颜色改变。请建议我如何正常工作。

productList.setOnItemClickListener(new OnItemClickListener() {

        //mOnDoubleTapListener = listener;

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

            Log.d("Row", "Row:= "+row);
            Log.d("View", "View:= "+view);

            if(row != null) {
                row.setBackgroundColor(Color.WHITE);
            }


            view.setBackgroundColor(Color.CYAN);

            row = view;
            }});

【问题讨论】:

    标签: android listview android-listview listadapter


    【解决方案1】:

    使用这种方式:-- 此代码将帮助您更改列表视图中选定项目的颜色

    只需在您的活动中使用一个名为 SELECTED_POSITION=-1 的变量;

    当您单击 ListView 中的任何项目时,您将通过此代码获得单击的位置

    productList.setOnItemClickListener(new OnItemClickListener() {
    
    
            @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
    
                SELECTED_POSITION =position;
            }
         });
    

    然后实现自定义适配器类,其中 @override 方法称为 getView(...)

    @Override
    public View getView(int position, View convertView, ViewGroup parent) 
    {
        ViewHolder holder = null;
        if (convertView == null) {
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.row_adptr, null);
            holder = new ViewHolder();
            holder.text = (TextView) convertView
                    .findViewById(R.id.adapterText1);
            holder.chkbox = (CheckBox) convertView
                    .findViewById(R.id.checkBox1);
            holder.imageview = (ImageView) convertView
                    .findViewById(R.id.imageView1);
            convertView.setTag(holder);          
    
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
    
           // this is the code when selected item stay at one position 
           if(position ==SELECTED_POSITION)
           {
                // set your selected Item Color
                 convertView.setBackgroundColor(Color.WHITE);
           }
            else
           {   // set your unselected Item Color
                   convertView.setBackgroundColor(Color.CYAN);
           } 
    
         ....Extra code of set value...
     }
    

    【讨论】:

    • 您是否忘记在 OnItemClickListener 上说 adapter.notifyDataSetChanged();
    猜你喜欢
    • 1970-01-01
    • 2019-08-07
    • 2016-07-17
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多