Android ListView xml配置


1 <ListView Android:id="@+id/locallist_lv" android:layout_width="fill_parent"

2         android:layout_height="fill_parent"  android:layout_above="@id/btm_menu" 
3         android:layout_below="@id/top_menu" 
4           android:divider="@drawable/song_item_line"  item之间的分割线
5         android:cacheColorHint="#00000000"系统切换item时的缓存色
6         android:scrollbars="none"不显示滚动条
7               android:listSelector="#00000000"/>选中时背景色

1. 将ListView的背景色设置为白色,ListIView控件上下滑动时,背景就会变为黑色,但是图片会正常显示,这怎么解决呢?网上搜了一下,

如果大家在非黑色背景下使用ListView控件时,Android默认可能在滚动ListView时这个列表控件的背景突然变成黑色。这样可能导致程序的黑色的背景和主程序的主题既不协调。解决的方法Google在设计Android时也考虑了,在Layout的ListView中加入 android:cacheColorHint="#00000000" 的属性即可,或者是调用ListView的setCacheColorHint(0);方法。

2. 在ListView的item项里使用CheckBox或者Button时,OnItemClickListener无响应的问题

在Android软件设计与实现中我们通常都会使用到ListView这个控件,系统有一些预置的Adapter可以使用,例如SimpleAdapter和ArrayAdapter,但是总是会有一些情况我们需要通过自定义ListView来实现一些效果,那么在这个时候,我们通常会碰到自定义ListView无法选中整个ListViewItem的情况,也就是无法响应ListView的onItemClickListener中的onItemClick()方法,之后自己查看了一下ViewGroup的源码,发现了以下的一段常量声明:

/**

* This view will get focus before any of its descendants.

*/

public static final int FOCUS_BEFORE_DESCENDANTS = 0×20000;

/**

* This view will get focus only if none of its descendants want it.

*/

public static final int FOCUS_AFTER_DESCENDANTS = 0×40000;

/**

* This view will block any of its descendants from getting focus, even

* if they are focusable.

*/

public static final int FOCUS_BLOCK_DESCENDANTS = 0×60000;

/**     * This view will get focus before any of its descendants.     */

public static final int FOCUS_BEFORE_DESCENDANTS = 0×20000;
/**     * This view will get focus only if none of its descendants want it.     */

public static final int FOCUS_AFTER_DESCENDANTS = 0×40000;
/**     * This view will block any of its descendants from getting focus, even     * if they are focusable.     */

public static final int FOCUS_BLOCK_DESCENDANTS = 0×60000;

我们看到了一行代码定义的变量的意思是“当前View将屏蔽他所有子控件的Focus状态,即便这些子控件是可以Focus的”,其实这段话的意思就是这个变量代表着当前的View将不顾其子控件是否可以Focus自身接管了所有的Focus,通常默认能获得focus的控件有Button,Checkable继承来的所有控件,这就意味着如果你的自定义ListViewItem中有Button或者Checkable的子类控件的话,那么默认focus是交给了子控件,而ListView的Item能被选中的基础是它能获取Focus,也就是说我们可以通过将ListView中Item中包含的所有控件的focusable属性设置为false,这样的话ListView的Item自动获得了Focus的权限,也就可以被选中了,也就会响应onItemClickListener中的onItemClick()方法,然而将ListView的Item Layout的子控件focusable属性设置为false有点繁琐,我们可以通过对Item Layout的根控件设置其android:descendantFocusability=”blocksDescendants”即可,这样Item Layout就屏蔽了所有子控件获取Focus的权限,不需要针对Item Layout中的每一个控件重新设置focusable属性了,如此就可以顺利的响应onItemClickListener中的onItenClick()方法了。例如我的ListViw的每个item项是RelativeLayout,那么我就可以设置RelativeLayout的android:descendantFocusability=”blocksDescendants”即可。注意:这个属性不能设置给ListView,设置了也不起作用。

第二种方法是将ListView子控件中的CheckBox或者ImageButton,Button的android:focusable="false"属性即可。

第三种方法是不适用CheckBox,或者Button,使用TextView,等等完全可以代替Button。

相关内容