android ListView實現圓角(兩種解決方案)

來源:互聯網
上載者:User

首先呢,我們還是看幾個示圖:(這是360推出的一款天氣預報APP(墨跡),很不錯的一款哦,這裡為她們做一個免費廣告,哈哈.)


                

這種帶有圓角的listview' 看起來很棒吧,確實是這樣,其實也不能這麼說,主要方形太多了,斯通見慣就不值錢了,“物以稀為貴嘛”. 就好比學java都搞androd,很明顯嘛,為了多賺點錢,可是供過於求的話,就不這麼樂觀了,就好比現在這個圓角,如果太多太多的話,我想若干時間段,肯定會被新的視圖所代替.所以“跟隨潮流,放寬眼線”很重要.不扯了,(網上實現例子很多)下面簡單介紹下實現方法:(兩種方法)

第一種:我們通過設定檔也就是shape自己實現圓角的背景,以及selector選中某項的背景.

首先我們要實現一個完整的圓角背景,用於預設與listview的background.

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" >    <stroke        android:width="1dp"        android:color="@color/gray" />    <solid android:color="@color/white" />    <corners android:radius="8dp" /></shape>

接下來我們要實現也就是listview的第一項selector後背景的shape.

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" >    <stroke        android:width="1dp"        android:color="@color/gray" />    <solid android:color="@color/gray" />    <corners        android:topLeftRadius="8dp"        android:topRightRadius="8dp" /></shape>

下面呢,我們也要實現中間的shape,以及末尾的shape等等配置.這裡就不寫了.按照上面模仿就ok了.

第二種方法:我們用.9.png完全代替上面那些配置,(因為.9.png可以展開不毀容)

所以listview的第一項,中間項,最後一項,以及就一項,我們都可以通過圖片來實現.

這裡我運用第一種方法:(也鞏固下shape)

建立自訂的listview,用於實現setSelector及選中的效果.

   程式碼片段:

   

package com.jj.listview;import android.content.Context;import android.util.AttributeSet;import android.view.MotionEvent;import android.widget.AdapterView;import android.widget.ListView;/*** * 自訂listview *  * @author Administrator *  */public class MyListView extends ListView {public MyListView(Context context) {super(context);}public MyListView(Context context, AttributeSet attrs) {super(context, attrs);}/**** * 攔截觸摸事件 */@Overridepublic boolean onInterceptTouchEvent(MotionEvent ev) {switch (ev.getAction()) {case MotionEvent.ACTION_DOWN:int x = (int) ev.getX();int y = (int) ev.getY();int itemnum = pointToPosition(x, y);if (itemnum == AdapterView.INVALID_POSITION)break;else {if (itemnum == 0) {if (itemnum == (getAdapter().getCount() - 1)) {// 只有一項setSelector(R.drawable.list_round);} else {// 第一項setSelector(R.drawable.list_top_round);}} else if (itemnum == (getAdapter().getCount() - 1))// 最後一項setSelector(R.drawable.list_bottom_round);else {// 中間項setSelector(R.drawable.list_center_round);}}break;case MotionEvent.ACTION_UP:break;}return super.onInterceptTouchEvent(ev);}}

這段代碼網上很多,幾乎全部都是這麼實現的,這裡我簡單介紹,如果說錯了,請大家指出,

首先我們是實現了onInterceptTouchEvent這個方法,在這裡我們也可以用onTouchEvent事件,都可以實現我們想要的效果.

onInterceptTouchEvent和onTouchEvent的區別:簡單的來說前者可以攔截後者.

詳細的請大家參考http://blog.csdn.net/jj120522/article/details/7944916  強烈建議大家看看.

下面一些邏輯雖說沒有見過,我想大家都看得懂,(就是擷取座標(x,y),然後根據座標擷取listview相應的position值,沒有返回-1,然後根據相應的position設定相應的setSelector ).有時間得好好研究下listview.對靈活運用很有協助.


在這裡我還要在說名一點,上面那個圖形很顯然不是一個listview,是三個listview,另外重要的是我們一個螢幕顯示不完全,這時我們就用到了ScrollView,一提到這個我想大家都知道ScrollView和listview是冤家,不可能同時存在,不過網上有解決辦法,原理就是我們動態show 我們的listview,

實現方法:

/*** * 動態設定listview的高度 *  * @param listView */public void setListViewHeightBasedOnChildren(ListView listView) {ListAdapter listAdapter = listView.getAdapter();if (listAdapter == null) {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));// params.height += 5;// if without this statement,the listview will be// a// little short// listView.getDividerHeight()擷取子項間分隔字元佔用的高度// params.height最後得到整個ListView完整顯示需要的高度listView.setLayoutParams(params);}

我們在Listview的setAdapter後,在調用下這個方法就OK了,代碼內容,我想大家都看的明白,就不多介紹了.

:

         

樣子雖醜陋了點,但是實現效果就行了,如果在項目中就另當別論了。

哈哈,實現起來簡單吧,睡覺去.


下面介紹另外一種解決方案:(TableLayout)

/************************************************************************************************************************************/

對於簡短的listview,加上如上面這些比較死的資料,我們完全沒有必要用listview來實現,TableLout完全夠了.主要是我們怎麼實現帶有弧度的邊罷了,不過這也完全得力於shape的功勞,至於點擊效果效果嘛,我們有selector,哈哈,下面介紹下實現:

 設定檔部分代碼:

    <ScrollView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:scrollbars="none" >        <LinearLayout            android:id="@+id/ll_main"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:layout_weight="1"            android:gravity="center"            android:orientation="vertical"            android:paddingLeft="10dp"            android:paddingRight="10dp" >        </LinearLayout>    </ScrollView>

很簡單,我們主要用這個Linerlayout來呈放我們的Table.

實現代碼:

package com.jj.corner;import java.util.ArrayList;import java.util.HashMap;import java.util.Map;import android.R.color;import android.app.Activity;import android.graphics.drawable.BitmapDrawable;import android.graphics.drawable.Drawable;import android.os.Bundle;import android.view.Gravity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.ViewGroup.LayoutParams;import android.view.Window;import android.widget.ArrayAdapter;import android.widget.LinearLayout;import android.widget.ListAdapter;import android.widget.ListView;import android.widget.RelativeLayout;import android.widget.SimpleAdapter;import android.widget.TableLayout;import android.widget.TableRow;import android.widget.TextView;public class MainActivity2 extends Activity {private LinearLayout ll_main;private TableLayout tableLayout;private LinearLayout.LayoutParams layoutParams;private static final String MSG_0[] = { "jjhappyforever" };private static final String MSG_1[] = { "天氣動畫", "通知欄天氣" };private static final String MSG_2[] = { "案頭外掛程式", "綁定微博", "天氣分享", "通知與提示","定時播報" };private static final String MSG_3[] = { "檢查新版本", "發送建議", "協助", "關於" };@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.main2);ll_main = (LinearLayout) findViewById(R.id.ll_main);showTable();}/*** * 顯示table */public void showTable() {layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);layoutParams.bottomMargin = 30;layoutParams.topMargin = 10;ll_main.addView(getTable(MSG_0), layoutParams);ll_main.addView(getTable(MSG_1), layoutParams);ll_main.addView(getTable(MSG_2), layoutParams);ll_main.addView(getTable(MSG_3), layoutParams);}/*** * 擷取Table *  * @param array * @return */public TableLayout getTable(String[] array) {tableLayout = new TableLayout(this);tableLayout.setLayoutParams(layoutParams);tableLayout.setStretchAllColumns(true);for (int i = 0; i < array.length; i++) {TableRow tableRow = new TableRow(this);View view = getView(array[i], i, array.length);tableRow.addView(view);tableLayout.addView(tableRow);}return tableLayout;}/**** *  * @param msg *            顯示資訊 * @param current_Id *            當前個數 * @param totle_Num *            總個數 * @return */public View getView(String msg, int current_Id, int totle_Num) {LinearLayout linearLayout = new LinearLayout(this);LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);layoutParams1.height = 1;linearLayout.setOrientation(1);// 建立分割線View line = new View(this);line.setLayoutParams(layoutParams1);line.setBackgroundColor(getResources().getColor(R.color.black));View view = LayoutInflater.from(MainActivity2.this).inflate(R.layout.item, null);view.setBackgroundDrawable(new BitmapDrawable());view.setFocusable(true);view.setClickable(true);TextView textView = (TextView) view.findViewById(R.id.tv_list_item);textView.setText(msg);textView.setTextSize(20);// 只有一項if (totle_Num == 1) {view.setBackgroundResource(R.drawable.default_selector);return view;}// 第一項else if (current_Id == 0) {view.setBackgroundResource(R.drawable.list_top_selector);}// 最後一項else if (current_Id == totle_Num - 1) {view.setBackgroundResource(R.drawable.list_bottom_selector);line.setVisibility(View.GONE);} elseview.setBackgroundResource(R.drawable.list_center_selector);linearLayout.addView(view);linearLayout.addView(line);return linearLayout;}}

主要是getView有些複雜,不過都很好理解,相信大家都可以明白,只是沒有動手做而已,小弟我只是想用這個練練手.

不過不要忘記我們的背景實現

這個是只有一項的背景,

default_selector.xml

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_pressed="true"><shape>            <stroke android:width="1dp" android:color="@color/gray" />            <solid android:color="@color/gray" />            <corners android:radius="8dp" />        </shape></item>    <item><shape>            <stroke android:width="1dp" android:color="@color/gray" />            <solid android:color="@color/white" />            <corners android:radius="8dp" />        </shape></item></selector>

list_top_selector.xml

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_pressed="true"><shape>            <stroke android:width="1dp" android:color="@color/gray" />            <solid android:color="@color/gray" />            <corners android:topLeftRadius="8dp" android:topRightRadius="8dp" />        </shape></item>    <item><shape>            <solid android:color="@color/white" />            <corners android:topLeftRadius="8dp" android:topRightRadius="8dp" />        </shape></item></selector>

list_bottom_selector.xml

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_pressed="true"><shape>            <stroke android:width="1dp" android:color="@color/gray" />            <solid android:color="@color/gray" />            <corners android:bottomLeftRadius="8dp" android:bottomRightRadius="8dp" />        </shape></item>    <item><shape>            <solid android:color="@color/white" />            <corners android:bottomLeftRadius="8dp" android:bottomRightRadius="8dp" />        </shape></item></selector>

list_center_selector.xml

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_pressed="true"><shape>            <stroke android:width="1dp" android:color="@color/gray" />            <solid android:color="@color/gray" />        </shape></item>    <item><shape>            <solid android:color="@color/white" />        </shape></item></selector>

主要就這麼多了,下面我們來看下實現效果:

          

怎麼樣,效果和上面一樣吧,自我感覺這樣實現比上面方面點,不過最重要的是因人而異,達成目的就OK了.

有不足的地方請留言指出.

 源碼下載


    由於比較忙碌,顧不得大家一一發送,現將代碼上傳網上,如有需要,你可以下載查看.

     對你如有協助,記得贊一個!

     Thranks for you !

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.