您好我有一个列表视图,点击后我想要显示所选列表项的背景图像,如果选择更改,则更改背景。我一直试图实现这一点,但未能这样做。请帮助我,非常感激
请找到我正在使用的代码
@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View view = convertView;
final int getstartedItemPos = position;
Resources res = getResources();
if (convertView == null) {
view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.getting_starteditem, null);
}
synchronized (view) {
TextView textTopic = (TextView) view
.findViewById(R.id.indexItems);
textTopic.setText(getStartedItems[getstartedItemPos]);
textTopic.setTypeface(tf);
view.setBackgroundColor(Color.TRANSPARENT);
}
return view;
}
};
private OnItemClickListener getStartedListItem = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
Intent myintent = new Intent(getApplicationContext(),GetStartedWebview.class);
myintent.putExtra("SelectedItem", getStartedItems[position]);
startActivity(myintent);
}
};
答案 0 :(得分:3)
pinkcandy使用此View lastView;
public void onItemClick(AdapterView<?> arg0, View v, int pos, long arg3)
{
if(lastView==null){
v.setBackgroundColor(Color.BLACK);
lastView=v;
}
else{
lastView.setBackgroundColor(Color.WHITE);
v.setBackgroundColor(Color.BLACK);
lastView=v;
}
}
它可以帮到你
答案 1 :(得分:3)
在listview中试试这个: -
android:listSelector="@color/orange"
答案 2 :(得分:1)
如果您已将OnItemClickListener
附加到ListView,我无法从您的代码中看到,如果您没有,则应该这样做。在onItemClick
中,您可以获取点击的视图(arg1)并在其上使用.setBackgroundResource(int resID)
来更改其背景
编辑:您可以使用包含当前列表项的本地变量来显示背景,所以请执行以下操作:
private View pressedView = null;
private OnItemClickListener getStartedListItem = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
Intent myintent = new Intent(getApplicationContext(),GetStartedWebview.class);
myintent.putExtra("SelectedItem", getStartedItems[position]);
startActivity(myintent);
if(pressedView != null) {
pressedView.setBackgroundResource(..); // reset background of old item
pressedView = arg1; // Point pressedView to new item
}
}
};
答案 3 :(得分:1)
我不确定,但如果我理解你的话,你只需要设置一次视图的背景,但它应该是 selector drawable,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="*background for pressed state*" />
<item
android:state_focused="true"
android:drawable="*background for focused state*" />
<item
android:drawable="*default background*" />
</selector>