【发布时间】:2012-01-13 17:10:34
【问题描述】:
我的最终目标是将this tutorial 中的信息来源从数组更改为游标。这是full code 的链接。它的要点是您单击列表中的一行,然后在列出的标题下方弹出主体,然后再次点击它,主体就消失了。我不想记住笔记是否打开,我也不想通过视图回收保持它打开,也不想在你打开一个或任何其他我能想到的花哨排列时关闭所有其他的。
一切正常,但是当 onListItemClick 事件处理程序触发,更改可见性和notifyDataSetChanged()s 时,列表会做一些奇怪的事情,包括单击两次以更改可见性,而不是重新测量自身,导致列表行每三次点击左右才为自己腾出空间。
之前的尝试导致了一个完美的工作列表,除了点击时,我想要隐藏和显示的每一行中的块会隐藏和显示,并且教程中的列表工作完美,但当然使用静态大小在所有方面,都只是一个模板。
我确信问题在于获取附加到列表行的可见性信息或在设置后更改它。
这里是onListItemClick:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
((NotesCursorAdapter) getListAdapter()).toggle(position, v);
}
用NotesCursorAdapter里面的toggle方法:
public void toggle(int position, View view) {
ViewHolder holder = (ViewHolder) view.getTag();
holder.mExpanded[position] = !holder.mExpanded[position];
notifyDataSetChanged();
}
NotesCursorAdapter之外的ViewHolder:
static class ViewHolder {
public TextView title;
public TextView body;
public boolean mExpanded[];
}
还有NotesCursorAdapter 本身:
class NotesCursorAdapter extends CursorAdapter {
private static final int VISIBLE = 0;
private static final int GONE = 8;
public NotesCursorAdapter(Context context, Cursor c) {
super(context, c);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.row, null, true);
ViewHolder holder = new ViewHolder();
holder.title = (TextView) rowView
.findViewById(R.id.title);
holder.body = (TextView) rowView
.findViewById(R.id.body);
holder.mExpanded = new boolean[cursor.getCount()];
rowView.setTag(holder);
return rowView;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
holder.title.setText(cursor.getString(cursor
.getColumnIndexOrThrow(DbAdapter.KEY_TITLE))
+ holder.mExpanded[cursor.getPosition()]);
holder.body.setText(cursor
.getString(cursor
.getColumnIndexOrThrow(DbAdapter.KEY_BODY)));
holder.body
.setVisibility(holder.mExpanded[cursor.getPosition()] ? VISIBLE : GONE);
}
public void toggle(int position, View view) {
ViewHolder holder = (ViewHolder) view.getTag();
holder.mExpanded[position] = !holder.mExpanded[position];
notifyDataSetChanged();
}
}
我不知道下一步该往哪里看。我需要制作自己的getView() 方法吗?我能从getItem() 中得到什么有用的东西吗?尝试像这样使用listview 我是不是完全疯了?
我进行了更多调查,代码正在运行,但点击事件似乎影响了相反的观点。我的意思是,当您单击顶部列表项时,它会影响底部列表项。当您单击顶部的第二个时,它会影响底部的第二个。如果列表项的数量为奇数,则中间的列表项可以正常工作。在某种程度上,无论我用什么方式来确定我正在影响的视图的 id 都是翻转的。 listview 是否从下往上对事物进行编号?
【问题讨论】:
标签: android listview visibility