select 上的 GridView 项目颜色更改和之前 selected 项目应显示正常颜色

GirdView Items color change on select and previously selected item should show normal color

我的 GridView 在任何项目的 select 上有一个 Image 和灰色文本 我需要将文本和图像的灰色更改为其他颜色(橙色) ,以及 select 的其他网格项目,我需要将之前 selected 的项目更改为默认灰色,并将 selected 的项目更改为橙色..

我尝试了一些解决方案,但没有得到正确的输出。请帮我解决这个问题 这是我试过的:

private int previousSelectedPosition = -1;

 gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            ImageView selectedImageView = (ImageView) gridView.findViewById(R.id.groupbyImage);
            TextView selectedTextView= (TextView) gridView.findViewById(R.id.groupbyHeader);
            if (previousSelectedPosition != position && previousSelectedPosition!=-1) {
                selectedImageView.setSelected(false);
                // Set the last selected View background color as deselected item
                selectedImageView.setColorFilter(getResources().getColor(R.color.gridsepration));
                // Set the last selected View text color as deselected item
                selectedTextView.setTextColor(getResources().getColor(R.color.gridsepration));
            } else {

                selectedTextView.setTextColor(getResources().getColor(R.color.violet));
                selectedImageView.setColorFilter(getResources().getColor(R.color.violet));
            }
            // Set the current selected view position as previousSelectedPosition
            previousSelectedPosition = position;

        }
    });

终于找到了解决方案..在下面找到解决方案。

尝试使用此代码,它是一个示例工作代码,在网格视图中选择和项目时,背景颜色随文本颜色一起更改。而且之前选择的项目也被取消选择,因为它是 before.In 我也使用了文本视图。

下面是网格视图的xml代码。

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#e8594c"
    >
    <TextView
        android:id="@+id/tv_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#f85d4f"
        android:layout_marginBottom="15dp"
        android:padding="10dp"
        />
    <GridView
        android:id="@+id/gv"
        android:layout_width="650dp"
        android:layout_height="wrap_content"
        android:padding="2dp"
        android:numColumns="3"
        android:background="#d84521"
        android:verticalSpacing="2dp"
        android:horizontalSpacing="2dp"
        android:stretchMode="columnWidth"
        android:gravity="left"
        android:layout_below="@id/tv_message"
        >
    </GridView>
</RelativeLayout>

现在 java 文件代码如下:

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.app.Activity;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.content.res.Resources;


public class MainActivity extends Activity {
    private int previousSelectedPosition = -1;

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

        // Get the widgets reference from XML layout
        final GridView gv = (GridView) findViewById(R.id.gv);
        final TextView tv_message = (TextView) findViewById(R.id.tv_message);

        // Initializing a new String Array
        String[] plants = new String[]{
                "Catalina ironwood",
                "Cabinet cherry",
                "Pale corydalis",
                "Pink corydalis",
                "Belle Isle cress",
                "Land cress",
                "Orange coneflower",
                "Coast polypody",
                "Water fern"
        };

        // Populate a List from Array elements
        final List<String> plantsList = new ArrayList<String>(Arrays.asList(plants));

        // Data bind GridView with ArrayAdapter (String Array elements)
        gv.setAdapter(new ArrayAdapter<String>(
                this, android.R.layout.simple_list_item_1, plantsList){
            public View getView(int position, View convertView, ViewGroup parent) {

                // Return the GridView current item as a View
                View view = super.getView(position,convertView,parent);

                // Convert the view as a TextView widget
                TextView tv = (TextView) view;

                // set the TextView text color (GridView item color)
                tv.setTextColor(Color.DKGRAY);

                // Set the layout parameters for TextView widget
                RelativeLayout.LayoutParams lp =  new RelativeLayout.LayoutParams(
                        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT
                );
                tv.setLayoutParams(lp);

                // Get the TextView LayoutParams
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)tv.getLayoutParams();

                // Set the width of TextView widget (item of GridView)
                params.width = getPixelsFromDPs(MainActivity.this,168);

                // Set the TextView layout parameters
                tv.setLayoutParams(params);

                // Display TextView text in center position
                tv.setGravity(Gravity.CENTER);

                // Set the TextView text font family and text size
                tv.setTypeface(Typeface.SANS_SERIF, Typeface.NORMAL);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);

                // Set the TextView text (GridView item text)
                tv.setText(plantsList.get(position));

                // Set the TextView background color
                tv.setBackgroundColor(Color.parseColor("#FFFF4F25"));

                // Return the TextView widget as GridView item
                return tv;
            }
        });

        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Get the selected item text
                String selectedItem = parent.getItemAtPosition(position).toString();

                // Display the selected item text to app interface
                tv_message.setText("Selected item : " + selectedItem);

                // Get the current selected view as a TextView
                TextView tv = (TextView) view;

                // Set the current selected item background color
                tv.setBackgroundColor(Color.parseColor("#FF9AD082"));

                // Set the current selected item text color
                tv.setTextColor(Color.BLUE);

                // Get the last selected View from GridView
                TextView previousSelectedView = (TextView) gv.getChildAt(previousSelectedPosition);

                // If there is a previous selected view exists
                if (previousSelectedPosition != -1)
                {
                    // Set the last selected View to deselect
                    previousSelectedView.setSelected(false);

                    // Set the last selected View background color as deselected item
                    previousSelectedView.setBackgroundColor(Color.parseColor("#FFFF4F25"));

                    // Set the last selected View text color as deselected item
                    previousSelectedView.setTextColor(Color.DKGRAY);
                }

                // Set the current selected view position as previousSelectedPosition
                previousSelectedPosition = position;
            }
        });
 }

    // Method for converting DP value to pixels
    public static int getPixelsFromDPs(Activity activity, int dps){
        Resources r = activity.getResources();
        int  px = (int) (TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, dps, r.getDisplayMetrics()));
        return px;
    }
}

这段代码的输出是:

之前

之后

希望对您有所帮助!

我是你的模型(网格视图对象):

  1. 你应该输入一个布尔变量来知道哪个是 selected 或不是。
  2. 当您select其中一张时,您应该将 的布尔变量设置为 true,如果您想要另一张卡片 select,您应该将该网格视图的布尔变量设置为 false。
  3. 任何更改后(如 selecting 网格视图之一)你必须调用 mAdapter.notifyDataSetChanged();

您需要在模型中再添加一个字段以供选择class。 因此,您可以从适配器的 getView() 方法中设置选择。在您的适配器中使用 viewHolder。

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

    if (convertView == null) {

        convertView = LayoutInflater.from(context).inflate(
                R.layout.your_row_file, null);

        holder = new ViewHolder();

        holder.selectedImageView = (ImageView) convertView
                .findViewById(R.id.groupbyImage);
        holder.selectedTextView = (TextView) convertView
                .findViewById(R.id.groupbyHeader);

        convertView.setTag(holder);

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

    if (yourArrayList.get(position).getSelected()) {
            selectedTextView.setTextColor(getResources().getColor(R.color.violet));
            selectedImageView.setColorFilter(getResources().getColor(R.color.violet));
        } else {
     // Set the last selected View background color as deselected item 
            selectedImageView.setColorFilter(getResources().getColor(R.color.gridsepration));
            // Set the last selected View text color as deselected item 
            selectedTextView.setTextColor(getResources().getColor(R.color.gridsepration));
     }


    convertView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        //   =========== Update IsSelected Value in Day Array======

           boolean isSelected=yourArrayList.get(position).getSelected();
           yourArrayList.get(position).setSelected(!isSelected);

           notifyDataSetChanged();
        }
    });
    return convertView;
}

我得到了解决方案,感谢所有回复的人。

这是我做的。

在我的适配器中

 public HashMap<Integer, Boolean> hashMapSelected;

在我的适配器构造函数中

     hashMapSelected = new HashMap<>();
    for (int i = 0; i < headers.size(); i++) {
        hashMapSelected.put(i, false);
    }

在我的适配器 getView 中

 if (hashMapSelected.get(position) == true) {
        viewHolder.imageView.setColorFilter(ContextCompat.getColor(mContext, R.color.violet));
        viewHolder.textView.setTextColor(ContextCompat.getColor(mContext, R.color.violet));
    } else {
        viewHolder.imageView.setColorFilter(ContextCompat.getColor(mContext, R.color.gridsepration));
        viewHolder.textView.setTextColor(ContextCompat.getColor(mContext, R.color.gridsepration));
    }

一个额外的方法来清除适配器中的其他项目

 public void makeAllUnselect(int position) {
    hashMapSelected.put(position, true);
    for (int i = 0; i < hashMapSelected.size(); i++) {
        if (i != position)
            hashMapSelected.put(i, false);
    }
}

最后我的网格视图 setOnItemClickListener

adapter.makeAllUnselect(position);
adapter.notifyDataSetChanged();

最终我的适配器看起来像这样

public class DataAdapter extends BaseAdapter {
   private Context mContext;
   private TypedArray images;
   private List<String> headers;
   public HashMap<Integer, Boolean> hashMapSelected;

public DataAdapter(Context context, TypedArray images, List<String> headers) {
    this.mContext = context;
    this.images = images;
    this.headers = headers;
    hashMapSelected = new HashMap<>();
    for (int i = 0; i < headers.size(); i++) {
        hashMapSelected.put(i, false);
    }
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return images.length();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

public void makeAllUnselect(int position) {
    hashMapSelected.put(position, true);
    for (int i = 0; i < hashMapSelected.size(); i++) {
        if (i != position)
            hashMapSelected.put(i, false);
    }
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    final ViewHolder viewHolder;

    if (convertView == null) {
        convertView = LayoutInflater.from(mContext).inflate(R.layout.groupby_grid_item, parent, false);
        viewHolder = new ViewHolder(convertView);
        convertView.setTag(viewHolder);

    } else
        viewHolder = (ViewHolder) convertView.getTag();
    viewHolder.textView.setText(headers.get(position));
    viewHolder.imageView.setImageResource(images.getResourceId(position, -1));


    if (hashMapSelected.get(position) == true) {
        viewHolder.imageView.setColorFilter(ContextCompat.getColor(mContext, R.color.violet));
        viewHolder.textView.setTextColor(ContextCompat.getColor(mContext, R.color.violet));
    } else {
        viewHolder.imageView.setColorFilter(ContextCompat.getColor(mContext, R.color.gridsepration));
        viewHolder.textView.setTextColor(ContextCompat.getColor(mContext, R.color.gridsepration));
    }
    return convertView;
}


private class ViewHolder {
    TextView textView;
    ImageView imageView;

    public ViewHolder(View view) {
        textView = (TextView) view.findViewById(R.id.groupbyHeader);
        imageView = (ImageView) view.findViewById(R.id.groupbyImage);
    }
}
}

还有我的 GridView OnItemClick

 gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            selectedGroupBy = getHeaders().get(position);
            adapter.makeAllUnselect(position);
            adapter.notifyDataSetChanged();
        }
    });