Как реализовать держатель вида?
Я использую просмотрщик для отображения из динамического arrayadapter.it, но отображаемые данные меняются нерегулярно, когда я просматриваю список. Я хочу, чтобы мой список был заполнен только один раз, не все время, когда я прокручиваю мой список. Любое предложение?
Вот мой код
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no need
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.sample, null);
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.text);
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.
if(_first==true)
{
if(id<myElements.size())
{
holder.name.setText(myElements.get(id));
holder.icon.setImageBitmap( mIcon1 );
id++;
}
else
{
_first=false;
}
}
//holder.icon.setImageBitmap(mIcon2);
/*try{
if(id<myElements.size())
id++;
else
{
id--;
}
}
catch(Exception e)
{
android.util.Log.i("callRestService",e.getMessage());
}*/
return convertView;
}
static class ViewHolder {
TextView name;
ImageView icon;
}
когда список загружен, он выглядит так: http://i.stack.imgur.com/NrGhR.png
после прокрутки некоторых данных http://i.stack.imgur.com/sMbAD.png
он выглядит так, и снова, если я прокрутите до начала, он выглядит http://i.stack.imgur.com/0KjMa.png ![alt text]()
P.S: мой список должен быть в алфавитном порядке
Ответы
Ответ 1
Вам нужно будет написать собственную версию ListView
, чтобы сделать это (что плохо). Если ListView
работает неправильно, это, вероятно, означает, что вы делаете что-то неправильно.
Откуда берется элемент id
? Вы получаете позицию в своем методе getView()
, поэтому вам не нужно беспокоиться о превышении границ списка. Позиция привязана к позиции элемента в вашем списке, поэтому вы можете получить правильный элемент следующим образом:
myElements.get(position);
Когда данные в вашем списке изменяются, вы можете вызвать это:
yourAdapter.notifyDataSetChanged()
Это перестроит ваш список новыми данными (сохраняя прокрутку и прочее).
Ответ 2
Вы пробовали это?
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no need
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.sample, null);
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.text);
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.name.setText(myElements.get(id));
holder.icon.setImageBitmap( mIcon1 );
return convertView;
}
static class ViewHolder {
TextView name;
ImageView icon;
}
Если да, то что с ним не так?
Я не думаю, что загрузка всех строк сразу - хорошая идея. В итоге у вас будет много бесполезных представлений в памяти, которые будут замедлять приложение впустую.
Представления и операции над представлениями (например, inflate, findViewById, getChild..) являются дорогостоящими, вы должны попытаться использовать их как можно больше. Вот почему мы используем ViewHolders.