是否可以更改ListView中所选项目的布局?
我使用自定义适配器使用ListView制作了简单的应用程序。它工作得很好,但我想将所选项目的布局更改为不同的布局。 实际上,单击的项目会扩展它的高度,并会出现一些新的按钮。一旦用户取消选择项目,它将返回到经典布局。
这是我的自定义适配器代码
public class ListAdapter extends ArrayAdapter<Polozka> {
// context mem variable
private Context mContext;
// Konstruktory
public ListAdapter(Context context,int textViewResourceId){
super(context,textViewResourceId);
}
public ListAdapter(Context context, int resource, List<Polozka> items){
super(context,resource,items);
this.mContext=context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
if (v == null){
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.polozkanakupniseznam,null);
}
final Polozka p = getItem(position);
if (p != null){
final TextView tt1 = (TextView) v.findViewById(R.id.seznam_nazevPolozky);
TextView tt2 = (TextView) v.findViewById(R.id.seznam_pocetPolozky);
CheckBox cb1 = (CheckBox) v.findViewById(R.id.checkBox_koupeno);
Button btnPridat = (Button) v.findViewById(R.id.buttonPridat);
Button btnOdebrat = (Button) v.findViewById(R.id.buttonOdebrat);
if (tt1 != null){
tt1.setText(p.getNazev());
}
if (tt2 != null){
tt2.setText(Integer.toString(p.getPocet()));
}
return v;
}}
这就是我将适配器设置为listview
的方法 lv = (ListView) findViewById(R.id.lv);
adapter = new ListAdapter(this,R.layout.polozkaseznam,list);
lv.setAdapter(adapter);
我想出了如何通过创建新的自定义适配器并将其放到ListView来更改每个项目的布局,但遗憾的是这不是我需要的。
非常感谢!
答案 0 :(得分:0)
适配器的getView()
方法用于创建原始视图。在那里,您可以使用视图的setOnTouchListener()
方法添加View.OnTouchListener实现。该类的onTouch()
处理程序接收所选视图。
要添加到OnTouchListener实现的有用成员是GestureDetector;这是使用OnGestureListener实现创建的,您可以将其传递给OnTouchListener的MotionEvent
回调中收到的onTouch()
。然后该听众用于区分各种事件(单击,双击等); GestureDetector.SimpleOnGestureListener是一个很好的实现,可以与许多回调一起使用来处理你可以覆盖的事件。
在某些时候(例如,在SimpleGestureListener的onDown()
回调中,当第一次触摸项时会触发),您可以修改传递给OnTouchListener的视图的布局。要将其更改回来,您可以使用处理程序进行手势的“on up”阶段,或者,如果您希望项目保持原样直到选择其他内容,请保留对最后一个选定视图的引用并更改它当选择另一个时。
如果最后一点不清楚,那么想法是SimpleGestureListener是视图的OnTouchListener实例的成员对象,因此它可以访问属于封闭的OnTouchListener的视图。