listview的一些属性

    xiaoxiao2021-12-14  84

    1.listview 去除分割线: 法一:设置android:divider:="@null"  法二:android:divider="#00000000" #00000000后面两个零表示透明 法三代码中:.setDividerHeight(0) 高度设为0 2.改变背景cacheColorHint属性: 改变背景背很简单只需要准备一张图片然后指定属性android:background="@drawable/bg",如果你只是换背景的颜色的话,可以直接指定android:cacheColorHint为你所要的颜色,如果你是用图片做背景的话,那也只要将android: cacheColorHint指定为透明(#00000000) 就可以了 3.fadingEdge属性: 上边和下边有黑色的阴影 android:fadingEdge="none"设置后没有阴影了 4.scrollbars属性 作用是隐藏l istView的滚动条,android:scrollbars="none" android:footerDividersEnabled//当设为false时,ListView将不会在各个footer之间绘制divider.默认为true。   5.listSelector属性 设置列表项选中或点击后的颜色,可以设置android:listSelector=“@null”,选中或点击列表项时无背景颜色变化。 6..fastScrollEnabled属性: 很多开发者不知道ListView列表控件的快速滚动滑块是如何启用的,Android开发网告诉大家,辅助滚动滑块只需要一行代 listview 点击后的背景: 1)设置listSelector   2)在布局文件中设置item的background   3)在adapter的getview中设置 3)在adapter的getView方法中设置 if (convertView == null ) { convertView = LayoutInflater.from(context).inflate(R.layout.listitem, null ); } convertView.setBackgroundResource(R.drawable.selector); ListView获取高度,然后设置高度,解决嵌套不显示问题 public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { // pre-condition return; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, listView); // listItem.measure(0, 0); listItem.measure( MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } 使用这个代码来获取listview的高度,需要注意一下几个问题: 1、listview的item的根布局一定要是LinearLayout; 因为其他的Layout(如RelativeLayout)没有重写onMeasure(),所以会在onMeasure()时抛出异常。 2、调用这个方法需要在适配器数据加载更新之后; 代码如下:  mAdapter.notifyDataSetChanged();  Function.getTotalHeightofListView(mListView); 3、获取item的高度也可以用注释掉的代码,效果一样的

    法二、 自定义ListView,重载onMeasure()方法,设置全部显示

    public class ExpandListView extends ListView { public ExpandListView(Context context) { super(context); } public ExpandListView(Context context, AttributeSet attrs) { super(context, attrs); } public ExpandListView(Context context, AttributeSet attrs, int defStyle){ super(context, attrs, defStyle); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } } 对listview中每个item高度的设置 ListView.LayoutParams params = new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT,70);//设置宽度和高度 convertView.setLayoutParams(params); Android关于ListView中item与控件抢夺焦点的那些事

    Button控件抢夺了item的焦点事件,使得item不能触发相应的点击事件,那么,如果我们既想点击触发Button的点击事件,又想点击触发item的点击事件,我们应该怎么做呢?

    这里有三种解决方案

    1.将ListView中的Item布局中的子控件focusable属性设置为false 2.在getView方法中设置button.setFocusable(false)

    3.设置item的根布局的属性Android:descendantFocusability="blocksDescendant"

    我们可以发现,其实这三种方法都是为了让Button等控件不能获取焦点,从而使得item可以响应点击事件。

    第三种方法使用起来相对方便,因为它是将item布局中的其他所有控件都设置为不能获取焦点。

    android:descendantFocusability属性共有三个取值,分别为

    beforeDescendants:viewgroup会优先其子类控件而获取到焦点 afterDescendants:viewgroup 只有当其子类控件不需要获取焦点时才获取焦点 blocksDescendants:viewgroup 会覆盖子类控件而直接获得焦点

    ListView监听:

    ListView的主要有两种滑动事件监听方法,OnTouchListener和OnScrollListener

    1.OnTouchListener

    OnTouchListener方法来自View中的监听事件,可以在监听三个Action事件发生时通过MotionEvent的getX()方法或getY()方法获取到当前触摸的坐标值,来对用户的滑动方向进行判断,并可在不同的Action状态中做出相应的处理

    mListView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // 触摸按下时的操作 break; case MotionEvent.ACTION_MOVE: // 触摸移动时的操作 break; case MotionEvent.ACTION_UP: // 触摸抬起时的操作 break; } return false; } }); 1234567891011121314151617181920 1234567891011121314151617181920

    不仅仅只有上面的三种Action状态,MotionEvent类中还定义了很多其它状态,我们可以灵活的使用这些状态

    MotionEvent.ACTION_DOWN:开始触摸MotionEvent.ACTION_MOVE:触摸移动MotionEvent.ACTION_UP:触摸抬起MotionEvent.ACTION_OUTSIDE:触摸范围超过了UI边界MotionEvent.ACTION_CANCEL:触摸被取消时(详见:http://stackoverflow.com/questions/11960861/what-causes-a-motionevent-action-cancel-in-android)MotionEvent.ACTION_POINTER_DOWN:当有另外一个触摸按下时(多点触摸)MotionEvent.ACTION_POINTER_UP:当另一个触摸抬起时(多点触摸)

    2.OnScrollListener

    OnScrollListener来自AbsListView中的监听事件,因为ListView直接继承自AbsListView,所以在AbsListView中有很多ListView相关信息  OnScrollListener中有两个回调方法

    public void onScrollStateChanged(AbsListView view, int scrollState):监听滑动状态的改变public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount):监听滑动

    在源码中有其详细的解释

    /** * Interface definition for a callback to be invoked when the list or grid * has been scrolled. */ public interface OnScrollListener { /** * The view is not scrolling. Note navigating the list using the trackball counts as * being in the idle state since these transitions are not animated. */ public static int SCROLL_STATE_IDLE = 0; /** * The user is scrolling using touch, and their finger is still on the screen */ public static int SCROLL_STATE_TOUCH_SCROLL = 1; /** * The user had previously been scrolling using touch and had performed a fling. The * animation is now coasting to a stop */ public static int SCROLL_STATE_FLING = 2; /** * Callback method to be invoked while the list view or grid view is being scrolled. If the * view is being scrolled, this method will be called before the next frame of the scroll is * rendered. In particular, it will be called before any calls to * {@link Adapter#getView(int, View, ViewGroup)}. * * @param view The view whose scroll state is being reported * * @param scrollState The current scroll state. One of * {@link #SCROLL_STATE_TOUCH_SCROLL} or {@link #SCROLL_STATE_IDLE}. */ public void onScrollStateChanged(AbsListView view, int scrollState); /** * Callback method to be invoked when the list or grid has been scrolled. This will be * called after the scroll has completed * @param view The view whose scroll state is being reported * @param firstVisibleItem the index of the first visible cell (ignore if * visibleItemCount == 0) * @param visibleItemCount the number of visible cells * @param totalItemCount the number of items in the list adaptor */ public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount); } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748

    2.1 OnScrollSateChanged方法

    OnScrollSateChanged根据scrollState来决定其回调的次数,它有三种模式:

    OnScrollListener.SCROLL_STATE_IDLE:滚动停止时的状态OnScrollListener.SCROLL_STATE_STOUCH_SCROLL:触摸正在滚动,手指还没离开界面时的状态OnScrollListener.SCROLL_STATE_FLING:用户在用力滑动后,ListView由于惯性将继续滑动时的状态

    当用户没有用力滑动时,OnScrollSateChanged方法只会回调2次,否则回调三次,我们在使用时通常会以设置Flag标志,来区分不同的滑动状态,从而进行相应的处理

    2.2 OnScroll方法

    在ListView滚动时会一直被回调,它通过里面有三个参数来显示当前ListView的滚动状态

    firstVisibleItem:当前能看见的第一个item的ID(从0开始)visibleItemCount:当前可见的item总数totalItemCount:列表中适配器总数量,也就是整个ListView中item总数

    注意:当前可见的item总数,包括屏幕中没有显示完整的item,如显示一半的item也会算在可见范围内

    通过这三个参数,我么可以实现很多事件判断,如:  (1)判断当前是否滑动到最后一行  当前视图中第一个item的ID加上当前屏幕中可见item的总数如果等于ListView中所有item总数时,就表示移动到了最后一行

    if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount > 0) { // 滚动到最后一行了 //滚动到最后一行,在这里可以处理ListView上拉加载更多  } 123 123

    (2)判断滑动的方向  通过oldVisibleItem 记录上一次firstVisibleItem的位置,再与滑动后的firstVisibleItem进行比较,就可得知滑动的方向

    if (firstVisibleItem > oldVisibleItem) { // 向上滑动 } if (firstVisibleItem < oldVisibleItem) { // 向下滑动 } oldVisibleItem = firstVisibleItem; 1234567 1234567

    ListView也为我们提供了一些封装好了的方法,来获取item的位置信息

    // 获取当前可见区域内第一个item的id mListView.getFirstVisiblePosition(); // 获取当前可见区域内最后一个item的id mListView.getLastVisiblePosition(); ScrollView嵌套ListView默认位置不是最顶部的解决方案

    描述:

    Scrollview里面嵌套了一个listview ,这是开发中最寻常的一种布局,遇到的问题是:在这个Scrollview页面默认的起始位置不是最顶部,而是listview的底部。


    原因:

    在Activity计算窗口的高度时,是在listview没有填充数据时候就完成的,由于ScrollView嵌套listview时没有指定高度,所以ScrollView就会按照layout中定义的默认高度计算。

    因为listview获取了焦点。


    解决:

    myScrollView.smoothScrollTo(0,20);

    需在listview数据加载完成后调用

    在代码里去掉listview的焦点

    lv.setFocusable(false);

    Listview外套一层LinearLayout

    跟EditText一样,在父元素的属性下面下下面这两行即可

    Android:focusableInTouchMode=”true”  android:focusable=”true”

    最开始的时候让最上面其中一个控件获得焦点,滚动条自然就到顶部去了,如下:

    txtBaseMsg.setFocusable(true);  txtBaseMsg.setFocusableInTouchMode(true);  txtBaseMsg.requestFocus();

    转载:四种方案解决ScrollView嵌套ListView问题

    一、 为什么要使用ScrollView嵌套ListView的奇怪的结构         ScrollView和ListView都是滚动结构,按理说,这两个控件在UI上的功能是一样的,但是看看下面这个设计:            这是天猫商城的确认订单的页面,ScrollView中嵌套了ExpandableListView,ExpandableListView上面有固定的一些控件,下面也有固定的一些控件,整体又要能够滚动。     列表数据要嵌在固定数据中间,并且作为整体一起滚动,有了这样的设计需求,于是就有了ScrollView嵌套ListView的奇怪结构。 二、 ScrollView、ListView嵌套结构碰到的问题     不多说,直接看失败例子:         <ScrollView     android:id="@+id/act_solution_1_sv"     android:layout_width="fill_parent"     android:layout_height="fill_parent">     <LinearLayout          android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:orientation="vertical">         <TextView             android:layout_width="fill_parent"             android:layout_height="wrap_content"             android:text="\nListView上方数据\n" />                        <ListView              android:id="@+id/act_solution_1_lv"             android:layout_width="fill_parent"             android:layout_height="wrap_content">                          </ListView>                      <TextView             android:layout_width="fill_parent"             android:layout_height="wrap_content"             android:text="\nListView下方数据\n" />     </LinearLayout>     </ScrollView> 复制代码     ScrollView中只能放一个控件,一般都放LinearLayout,orientation属性值为vertical。在LinearLayout中放需要呈现的内容。ListView也在其中,ListView的高度设为适应自身内容(wrap_content)。粗略一看,应该没有什么问题。但是看下面的实际效果图:                图中黑框的部分就是ListView,里面放了20条数据,但是却只显示了1条。     控件的属性设置上没有问题,但是为什么没有按照我的想法走呢?     看看下面这个图:            是否有点明白了呢?原因就是scroll事件的消费处理以及ListView控件的高度设定问题。     虽然我看源码也看了不少,但是要说出来却不知到该怎么下手,我是大概知道原因,但是不知道怎么整理完全。求高手赐教… 三、问题解决方案 1、手动设置ListView高度     经过测试发现,在xml中直接指定ListView的高度,是可以解决这个问题的,但是ListView中的数据是可变的,实际高度还需要实际测量。于是手动代码设置ListView高度的方法就诞生了。 /** * 动态设置ListView的高度 * @param listView */ public static void setListViewHeightBasedOnChildren(ListView listView) {      if(listView == null) return;     ListAdapter listAdapter = listView.getAdapter();      if (listAdapter == null) {          // pre-condition          return;      }      int totalHeight = 0;      for (int i = 0; i < listAdapter.getCount(); i++) {          View listItem = listAdapter.getView(i, null, listView);          listItem.measure(0, 0);          totalHeight += listItem.getMeasuredHeight();      }      ViewGroup.LayoutParams params = listView.getLayoutParams();      params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));      listView.setLayoutParams(params);  } 复制代码     上面这个方法就是设定ListView的高度了,在为ListView设置了Adapter之后使用,就可以解决问题了。     但是这个方法有个两个细节需要注意:         一是Adapter中getView方法返回的View的必须由LinearLayout组成,因为只有LinearLayout才有measure()方法,如果使用其他的布局如RelativeLayout,在调用listItem.measure(0, 0);时就会抛异常,因为除LinearLayout外的其他布局的这个方法就是直接抛异常的,没理由…。我最初使用的就是这个方法,但是因为子控件的顶层布局是RelativeLayout,所以一直报错,不得不放弃这个方法。         二是需要手动把ScrollView滚动至最顶端,因为使用这个方法的话,默认在ScrollView顶端的项是ListView,具体原因不了解,求大神解答…可以在Activity中设置: sv = (ScrollView) findViewById(R.id.act_solution_1_sv); 复制代码 2、使用单个ListView取代ScrollView中所有内容     这个方法是我在试了几个方法都失败的情况下自己琢磨出来的。     用一张图来解释这个方法的思想:           就是说,把整个需要放在ScrollView中的内容,统统放在ListView中,原ListView上方的数据和下方数据,都作为现ListView的一个itemView,和原ListView中的单条数据是平级的关系。     xml布局方面十分简单: <ListView      android:id="@+id/act_solution_2_lv"     android:layout_width="fill_parent"     android:layout_height="wrap_content">          </ListView> 复制代码    一个单独的ListView就可以了。     原ListView上方数据和下方数据,都写进两个xml布局文件中:            Java代码方面,需要自定义一个Adapter,在Adapter中的getView方法中进行position值的判断,根据position值来决定inflate哪个布局: public View getView(int position, View convertView, ViewGroup parent) {             //列表第一项     if(position == 0){        convertView = inflater.inflate(R.layout.item_solution2_top, null);         return convertView;     }             //列表最后一项     else if(position == 21){         convertView = inflater.inflate(R.layout.item_solution2_bottom, null);         return convertView;     }                          //普通列表项     ViewHolder h = null;     if(convertView == null || convertView.getTag() == null){         convertView = inflater.inflate(R.layout.item_listview_data, null);         h = new ViewHolder();         h.tv = (TextView) convertView.findViewById(R.id.item_listview_data_tv);         convertView.setTag(h);     }else{         h = (ViewHolder) convertView.getTag();     }                  h.tv.setText("第"+ position + "条数据");     return convertView; } 复制代码     在Activty中,只需要直接为ListView设置自定义的Adapter就行了。 lv = (ListView) findViewById(R.id.act_solution_2_lv); adapter = new AdapterForListView2(this); lv.setAdapter(adapter); 复制代码 3、使用LinearLayout取代ListView     既然ListView不能适应ScrollView,那就换一个可以适应ScrollView的控件,干嘛非要吊死在ListView这一棵树上呢?而LinearLayout是最好的选择。但如果我仍想继续使用已经定义好的Adater呢?我们只需要自定义一个类继承自LinearLayout,为其加上对BaseAdapter的适配。 import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.BaseAdapter; import android.widget.LinearLayout; /** * 取代ListView的LinearLayout,使之能够成功嵌套在ScrollView中 * @author terry_龙 */ public class LinearLayoutForListView extends LinearLayout {     private BaseAdapter adapter;     private OnClickListener onClickListener = null;     /**      * 绑定布局      */     public void bindLinearLayout() {         int count = adapter.getCount();         this.removeAllViews();         for (int i = 0; i < count; i++) {             View v = adapter.getView(i, null, null);             v.setOnClickListener(this.onClickListener);             addView(v, i);         }        Log.v("countTAG", "" + count);     }     public LinearLayoutForListView(Context context) {         super(context); 复制代码     上面的代码拷贝保存为LinearLayoutForListView.class,或者直接拷贝Demo中的这个类在自己的工程里。我们只需要把原来xml布局文件中的ListView替换为这个类就行了: <pm.nestificationbetweenscrollviewandabslistview.mywidgets.LinearLayoutForListView     android:id="@+id/act_solution_3_mylinearlayout"     android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:orientation="vertical" > </pm.nestificationbetweenscrollviewandabslistview.mywidgets.LinearLayoutForListView> 复制代码     在Activity中也把ListView改成LinearLayoutForListView,就能成功运行了。 mylinearlayout = (LinearLayoutForListView) findViewById(R.id.act_solution_3_mylinearlayout); adapter = new AdapterForListView(this); mylinearlayout.setAdapter(adapter); 复制代码 4、自定义可适应ScrollView的ListView     这个方法和上面的方法是异曲同工,方法3是自定义了LinearLayout以取代ListView的功能,但如果我脾气就是倔,就是要用ListView怎么办?那就只好自定义一个类继承自ListView,通过重写其onMeasure方法,达到对ScrollView适配的效果。     下面是继承了ListView的自定义类: import android.content.Context; import android.util.AttributeSet; import android.widget.ListView; public class ListViewForScrollView extends ListView {     public ListViewForScrollView(Context context) {         super(context);     }     public ListViewForScrollView(Context context, AttributeSet attrs) {         super(context, attrs);     }     public ListViewForScrollView(Context context, AttributeSet attrs,         int defStyle) {         super(context, attrs, defStyle);     }              @Override     /**      * 重写该方法,达到使ListView适应ScrollView的效果      */     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {         int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,         MeasureSpec.AT_MOST);         super.onMeasure(widthMeasureSpec, expandSpec);     } } 复制代码     三个构造方法完全不用动,只要重写onMeasure方法,需要改动的地方比起方法3少了不是一点半点…     在xml布局中和Activty中使用的ListView改成这个自定义ListView就行了。代码就省了吧…     这个方法和方法1有一个同样的毛病,就是默认显示的首项是ListView,需要手动把ScrollView滚动至最顶端。 sv = (ScrollView) findViewById(R.id.act_solution_4_sv); sv.smoothScrollTo(0, 0); 复制代码 5、设置ScrollView的属性,使ListView能够成功嵌套(无法达到预定效果)     这个方法是我在写Demo的时候找到的,第一反应是有这个方法我还写这个Demo干嘛,只要在布局文件中添加一个属性就搞定了。不过结果确实是ListView的大小把ScrollView的剩余部分填满了,但却不能滚动,真是个致命的问题…     不废话了,布局文件中: <ScrollView     android:id="@+id/act_solution_5_sv"     android:layout_width="fill_parent"     android:layout_height="fill_parent"     android:layout_below="@+id/act_solution_5_vg_top"     android:fillViewport="true"> 复制代码     设置fillViewport的属性为true即可。简单吧?     但是不能滚动这个致命的问题我却不知道该怎么解决了,继续求大神解答… 四、几种种方法的优缺点比较     上面一共给出了4中亲测可用的方法,各自有使用条件,复杂程度也各不相同。     下面我来从几个方面来分析几种方法的优势和劣势。     方法1的优点是不用对使用的控件做任何修改,只需要使用一个现成的方法就好了,而最大的限制是ListView的item只能由LinearLayout这一个布局组成,对于一些复杂的布局就不适用了。如果你的工程急需解决这个问题,而且满足方法的使用条件,即ListView的item布局简单,完全有LinearLayout组成,你就只需要把setListViewHeightBasedOnChildren方法拿过去就行了。     方法2的优点是布局文件设计简单、Activity中的代码也很少,而缺点却是自定义Adapter变得十分复杂,而且执行效率会变低,因为findViewById是十分费时的操作,而使用ViewHolder结构可以解决费时的问题(有兴趣的童鞋可以去搜一艘ViewHolder结构),然而使用了方法2的话,会破坏这种结构。如果你的工程设计上偏简单,ListView子项相对少、ListView上下方数据少、子项间交互少的话,可以尝试一下。     方法3的优点是完全解决了ScrollView嵌套ListView的问题,同时代码较少,你甚至可以直接使用LinearLayout,而在Activity中手动为LinearLayout添加子项控件,不过需要注意的是,在添加前需要调用其removeAllViews的方法,否则可能会出现预想不到的事情,那时你会想念天国的ListView的。缺点不是很明显,但还是有两个:一是使用的不是系统控件,不能在xml布局的Graphical Layout视图中直接看到效果;二是不能向ListView那样可以使用ViewHolder结构,在加载大量子项时会费很多时间在findViewById中。如果你的列表数据比较少的话,不妨试试这个方法,除了不能使用ViewHolder结构,使用方法几乎和ListView一样。     方法4…比方法3更简单,代码更少,同时保留了ListView原有的所有方法,包括notifyDataSetChanged方法,相比其他方法是最趋近于完美的方法,只是需要在Activity中设定ScrollView滚动至顶端。如果你还在犹豫不决的话就选这个方法吧,我想我以后是只会用这个方法了… 转载Demo下载地址:http://download.csdn.net/detail/lygscg123/7776719

    转载请注明原文地址: https://ju.6miu.com/read-964722.html

    最新回复(0)