and*_*poo 8 icons android android-arrayadapter android-listview
我有一个ListView
使用动态的动态ArrayAdapter
.当从微调器中选择一个名称时,该名称以及一个显示它们是男性还是女性的图标会被添加到ListView
.
一切都很好(名称正确地添加到列表中,与图标一起).但是显示性别的图标被添加到了错误的项目中ListView
.名称将添加到列表的底部,但图标将放置在列表顶部的名称处.我不知道这是否是我使用的方式,ViewHolder
但Android网站上没有文档.
// Listview inflater
inflater = (LayoutInflater) (this).getSystemService(LAYOUT_INFLATER_SERVICE);
// List Array.
mAdapter = new ArrayAdapter<String>(this, R.layout.player_simple_list,
R.id.label, mStrings) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.i("ANDY","View getView Called");
// A ViewHolder keeps references to children views to
// avoid unneccessary calls to findViewById() on each row.
ViewHolder holder;
if (null == convertView) {
Log.i("ANDY","Position not previously used, so inflating");
convertView = inflater.inflate(R.layout.player_simple_list, null);
// Creates a ViewHolder and store references to the
// two children views we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.label);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
if (sexmale == true) {
holder.icon.setImageBitmap(maleicon);
}
else {
holder.icon.setImageBitmap(femaleicon);
}
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.text.setText(getItem(position));
// Change icon depending is the sexmale variable is true or false.
Log.i("ANDY","getCount = "+mAdapter.getCount());
return convertView;
}
};
setListAdapter(mAdapter);
Run Code Online (Sandbox Code Playgroud)
更新: ViewHolder
仅用于保存对项目布局内组件视图的引用。这有助于避免调用findViewById
在具有多个组件的复杂项目布局中渲染每个组件的开销(如本例中的TextView
, 和ImageView
)。
我通过使用例程(称为getSex
)来检索性别数据并设置所有视图数据(包括if-else
块外的图标)来修复此问题。
现在的工作代码如下所示:
if (null == convertView) {
Log.i("ANDY","Position not previously used, so inflating");
convertView = inflater.inflate(R.layout.player_simple_list, null);
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.label);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.text.setText(getItem(position));
// Change icon depending is the sexmale variable is true or false.
if (getSex (getItem(position)) == true) {
holder.icon.setImageBitmap(maleicon);
}
else {
holder.icon.setImageBitmap(femaleicon);
}
return convertView;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15270 次 |
最近记录: |