我有自定义BaseAdapter
。我在GridView
中使用过的。我试图按位置更改项目背景颜色(也是我更改Textview的文本颜色)
这是我的baseadapter
来源
public class ServiciesGridAdapter extends BaseAdapter {
private Context context;
private List<ServicesListItem> itemList;
public ServiciesGridAdapter(Context context, List<ServicesListItem> mobileValues) {
this.context = context;
this.itemList = mobileValues;
}
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
gridView = inflater.inflate(R.layout.view_servisies_gridview_items, null);
final LinearLayout mainLayout = (LinearLayout) gridView.findViewById(R.id.gridview_items_layout);
final TextView serviciesID = (TextView) gridView.findViewById(R.id.servicies_grid_id);
final TextView serviciesName = (TextView) gridView.findViewById(R.id.servicies_grid_name);
serviciesID.setText(itemList.get(position).getName());
serviciesName.setText(itemList.get(position).getIdentifier() + " EUR");
mainLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mainLayout.setBackgroundResource(R.drawable.rounded_corners_blue);
serviciesID.setTextColor(Color.parseColor("#ffffff"));
serviciesName.setTextColor(Color.parseColor("#ffffff"));
}
});
} else {
gridView = (View) convertView;
}
return gridView;
}
@Override
public int getCount() {
return itemList.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
}
当我在项目中运行我的应用程序时,我可以更改背景颜色,但是当我检查另一个项目时,第一个项目的背景是相同的。简单地说,我想每次点击只更改一个项目背景。
我如何解决我的问题?
答案 0 :(得分:1)
你必须重置所有其他视图文本的颜色和背景,所以做一个循环并做它..尝试下面的代码
mainLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(int i=0;i<parent.getChildCount();i++){
View c = parent.getChildAt(i);
c.findViewById(R.id.gridview_items_layout).setBackgroundResource(defaultResource);
(TextView) c.findViewById(R.id.servicies_grid_id).setTextColor(defaultColor);
((TextView) c.findViewById(R.id.servicies_grid_name)).setTextColor(defaultColor);
}
mainLayout.setBackgroundResource(R.drawable.rounded_corners_blue);
serviciesID.setTextColor(Color.parseColor("#ffffff"));
serviciesName.setTextColor(Color.parseColor("#ffffff"));
}
});
答案 1 :(得分:0)
使用listSelector按格构视图中的位置更改项目背景。
添加你color.xml
<resources>
<color name="onClickColor">#FFFFFF</color>
</resources>
将selecter.xml
添加到drawable
文件夹
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="@color/onClickColor">
</item>
</selector>
将listSelector
添加到您的GridView
<GridView
android:id="@+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:listSelector="@drawable/selecter">
</GridView>
看一下this帖子......