jsonadapter动态修改listview 背景色
时间: 2023-09-21 21:01:07 浏览: 86
要动态修改ListView的背景色,可以使用JsonAdapter来实现。以下是一种实现方法:
首先,需要在布局文件中定义一个ListView,如下所示:
```xml
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
然后,在Java代码中定义一个自定义的JsonAdapter类,继承自BaseAdapter,并实现getView方法,如下所示:
```java
public class MyJsonAdapter extends BaseAdapter {
private Context mContext;
private List<String> mDataList;
private int mColor;
public MyJsonAdapter(Context context, List<String> dataList, int color) {
mContext = context;
mDataList = dataList;
mColor = color;
}
@Override
public int getCount() {
return mDataList.size();
}
@Override
public Object getItem(int position) {
return mDataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
ViewHolder viewHolder;
if (convertView == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.item_layout, null);
viewHolder = new ViewHolder();
viewHolder.textView = view.findViewById(R.id.textview);
view.setTag(viewHolder);
} else {
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
String data = mDataList.get(position);
viewHolder.textView.setText(data);
view.setBackgroundColor(mColor);
return view;
}
private static class ViewHolder {
private TextView textView;
}
}
```
接下来,在Activity中使用JsonAdapter来动态修改ListView的背景色,如下所示:
```java
ListView listView = findViewById(R.id.listview);
List<String> dataList = new ArrayList<>();
dataList.add("Item 1");
dataList.add("Item 2");
dataList.add("Item 3");
int color = Color.parseColor("#FF0000"); // 设置为红色背景
MyJsonAdapter adapter = new MyJsonAdapter(this, dataList, color);
listView.setAdapter(adapter);
```
以上代码完成了JsonAdapter的定义和使用,通过自定义的JsonAdapter,可以动态修改ListView的背景色。
阅读全文