我正在制作一个listview,并希望高亮显示,例如,列表视图中的第3行到第7行。
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_list);
lv = (ListView) findViewById(R.id.sample_listview);
String[] Sample_List = getResources().getStringArray(R.array.Sample_List);
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < Sample_List.length; ++i)
{
list.add(Sample_List[i]);
}
final StableArrayAdapter adapter = new StableArrayAdapter(this, R.layout.list_item, list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
...
}
});
}
我更新了以下代码:
lv.setAdapter(myAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
...
}
});
}
public class MyCustomArrayAdapter extends ArrayAdapter<String>
{
private final Context context;
private final String[] values;
public MyCustomArrayAdapter(Context context, String[] values)
{
super(context, R.layout.list_item, values);
this.context = context;
this.values = values;
}
@Override
public View getView (int position, View convertView, ViewGroup parent)
{
View view = super.getView(position, convertView, parent);
if(position>=3&&position<=7)
{
view.setBackgroundResource(R.drawable.green_btn);
}
else
{
view.setBackgroundResource(R.drawable.white_btn);
}
return view;
}
}
我已经在网上进行了很多研究,但我仍然无法弄清楚如何实现getView
...以这种方式如何改变上述内容,例如,背景行3到7是设置为红色?
实施更新的代码,列表视图无法正确展开以显示每个项目,只能显示项目的边框(绿色按钮有一些黑色边框),可能是因为没有链接列表。
如何将列表与MyCustomArrayAdapter连接?
答案 0 :(得分:3)
如何将突出显示的位置存储在List
中,以便您可以执行此类操作.-
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (highlightedPositions.contains(position)) {
view.setBackgroundColor(yourColor);
}
return view;
}
修改强>
现在您已拥有自己的自定义适配器,请替换您设置StableArrayAdapter
的代码.-
final StableArrayAdapter adapter = new StableArrayAdapter(this, R.layout.list_item, list);
lv.setAdapter(adapter);
用这个.-
final MyCustomArrayAdapter adapter = new MyCustomArrayAdapter(this, list);
lv.setAdapter(adapter);
答案 1 :(得分:2)
这是一个简单的解决方案
public View getCustomView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View mySpinner = inflater.inflate(R.layout.custom_spinner, parent,
false);
TextView main_text = (TextView) mySpinner
.findViewById(R.id.text_main_seen);
if(position==1)
main_text.setBackgroundColor(Color.GREEN);
main_text.setText(spinnerValues[position]);
return mySpinner;
}
位置1的项目将为绿色