如何在片段中更改ListView的特定项? 我的问题是以下方法不起作用。 特别是:
getViewByPosition(highLightLastSee(), lvItems).setBackgroundColor(bgColor);
拥有一个实现ListView的Fragment。 我在Fragmentclass中有这个ListView的全局引用,我想更改ListView项的背景颜色
片段中的onCreateView方法
ListView lvItems;
View rootView;
FontsAdapter todoAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
DB_Helper = new DataBase(getActivity());
DB_Helper.open();
rootView = inflater.inflate(R.layout.fragment_layout_main, container, false);
lvItems = (ListView) rootView.findViewById(android.R.id.list);
text_portrait_width_300 = (TextView)
rootView.findViewById(R.id.text_portrait_width_300);
text_portrait_width_500_300 = (TextView)
rootView.findViewById(R.id.text_portrait_width_500_300);
text_portrait_width_500 = (TextView)
rootView.findViewById(R.id.text_portrait_width_500);
image_portrait_width_300 = (ImageView) rootView.findViewById(R.id.image_portrait_width_300);
image_portrait_width_500_300 = (ImageView) rootView.findViewById(R.id.image_portrait_width_500_300);
image_portrait_width_500 = (ImageView) rootView.findViewById(R.id.image_portrait_width_500);
image_portrait = (ImageView) rootView.findViewById(R.id.image_portrait);
text_portrait = (TextView) rootView.findViewById(R.id.text_portrait);
text_landscape = (TextView) rootView.findViewById(R.id.text_landscape);
image_landscape = (ImageView) rootView.findViewById(R.id.image_landscape);
return rootView;
}
方法getView
public View getViewByPosition(int pos, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition +
listView.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition ) {
return listView.getAdapter().getView(pos, null, listView);
} else {
final int childIndex = pos - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
public void updateBackgroundItem() {
if(lvItems != null){
int alpha = 14; //50% transparency
int color = 245; //Your color value
//int bgColor = Color.rgb(255,215,0);
int bgColor = Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
//ColorDrawable colorDrawable1 = new ColorDrawable(Color.parseColor("#A0A3A0"));
Toast.makeText(getActivity(), "The position item to change BackgroundColor on listView "+highLightLastSee()+"", Toast.LENGTH_SHORT).show();
getViewByPosition(highLightLastSee(), lvItems).setBackgroundColor(bgColor);
todoAdapter.notifyDataSetChanged();
}
else {
Toast.makeText(getActivity(), "Nothing lvItems ",
Toast.LENGTH_SHORT).show();
}
}
方法whereShowItems
public void whereShowItemsFromListView() {
lvItems.setAdapter(todoAdapter);
if(highLightLastSee() == -1){
Toast.makeText(getActivity(), "Item position is null",
Toast.LENGTH_SHORT).show();
}
else {
updateBackgroundItem();
}
}