Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義自動換行列表控件 CustomListView:使用方式與完整範例

編輯:關於 Android 程式設計

之前曾經寫過一篇關於自動換行與多種自定義效果的文章,但當時功力不足,jar 包裡的程式碼只能用「慘不忍睹」來形容。忙完手邊工作後重看舊碼,決定重新封裝。重寫後的 android-custom-vg 經過多次改版,目前定版在 2.6.0,並刻意模擬 ListView 的資料載入流程,讓遷移成本降到最低。

需要說明的是,目前只實作了最基礎的效果——ListView 中定位到某個特定 View 顯示的屬性尚未實作。

效果預覽

對外 API

setDividerWidth(int dividerWidth);   // 兩個 Item 的水平間距,第一個 Item 距左邊框為 0
setDividerHeight(int dividerHeight); // 兩個 Item 的垂直間距,第一行 Item 距頂部邊框為 0
setOnItemClickListener(OnItemClickListener listener);         // Item 點擊事件
setOnItemLongClickListener(OnItemLongClickListener listener); // Item 長按事件

1. 版面配置 activity_main.xml

為了讓整個換行列表可以捲動,把自定義控件放進 ScrollView 中:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFF"
        android:fadingEdge="none"
        android:fillViewport="true"
        android:scrollbars="none">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="top|left"
            android:orientation="vertical">

            <com.custom.vg.list.CustomListView
                android:id="@+id/sexangleView"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp" />

        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:orientation="vertical">

        <Button
            android:id="@+id/btn_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="+" />

        <Button
            android:id="@+id/btn_remove"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="-" />

    </LinearLayout>
</RelativeLayout>

2. MainActivity

import com.custom.vg.list.CustomListView;
import com.custom.vg.list.OnItemClickListener;
import com.custom.vg.list.OnItemLongClickListener;

public class MainActivity extends Activity implements OnClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final String SHOW_SEXANGLE_LISTVIEW = "showSexangleListView";

    private CustomListView lv;
    private List<String> list = null;
    private MainSexangleAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lv = (CustomListView) findViewById(R.id.sexangleView);
        findViewById(R.id.btn_add).setOnClickListener(this);
        findViewById(R.id.btn_remove).setOnClickListener(this);

        new Thread(new MyFormatListThread()).start();
    }

    private void showSexangleListView() {
        adapter = new MainSexangleAdapter(this, list);

        lv.setDividerHeight(10);
        lv.setDividerWidth(10);
        lv.setAdapter(adapter);

        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Toast.makeText(MainActivity.this, "點擊了:" + arg2, 300).show();
            }
        });

        lv.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Toast.makeText(MainActivity.this, "Long點擊了:" + arg2, 300).show();
                return true;
            }
        });
    }

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            try {
                if (msg.getData().containsKey(SHOW_SEXANGLE_LISTVIEW)) {
                    showSexangleListView();
                }
            } catch (Exception e) {
                Log.w(TAG, e);
            }
        }
    };

    /** 模擬背景取得資料 */
    public class MyFormatListThread implements Runnable {
        @Override
        public void run() {
            Bundle b = new Bundle();
            try {
                list = new ArrayList<String>();
                list.add("宇宙");
                list.add("宙即我心");
                list.add("心我心即宇");
                list.add("宇宙即我心我心即");
                list.add("心即宇宙細");
                list.add("即");
                list.add("宇宙細微");
                list.add("祥淵源");
                list.add("之發祥淵源實為");
                list.add("文明之");
                list.add("發祥");
                list.add("源實為諸人種");
                b.putBoolean(SHOW_SEXANGLE_LISTVIEW, true);
            } catch (Exception e) {
                Log.w(TAG, e);
            } finally {
                sendMsgHandler(handler, b);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_add:
                list.add("Button添加" + list.size());
                adapter.notifyDataSetChanged();
                break;
            case R.id.btn_remove:
                if (!list.isEmpty()) {
                    list.remove(0);
                }
                adapter.notifyDataSetChanged();
                break;
        }
    }

    private void sendMsgHandler(Handler handler, Bundle bundle) {
        Message msg = handler.obtainMessage();
        msg.setData(bundle);
        handler.sendMessage(msg);
    }
}

3. MainSexangleAdapter

繼承自 CustomAdapter,寫法與一般 Adapter 幾乎一致:

import com.custom.vg.list.CustomAdapter;

public class MainSexangleAdapter extends CustomAdapter {

    private List<String> list;
    private Context con;
    private LayoutInflater inflater;

    public MainSexangleAdapter(Context context, List<String> list) {
        this.con = context;
        this.list = list;
        inflater = LayoutInflater.from(con);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh;
        if (convertView == null) {
            vh = new ViewHolder();
            convertView = inflater.inflate(R.layout.adapter_sexangle_item_style, null);
            vh.tv = (TextView) convertView.findViewById(R.id.adapter_text);
            convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }
        vh.tv.setText(list.get(position));
        return convertView;
    }

    public static class ViewHolder {
        public TextView tv;
    }
}

使用心得

基本調用方式與 ListView 幾乎相同,Item 可以放任意版面,不侷限於範例中的樣式。若要對 Item 做不同效果的呈現,直接在 Adapter 裡處理即可——修改 List 集合中的資料後呼叫 notifyDataSetChanged() 刷新。

唯一要留意的是:由於控件被包在 ScrollView 中,它不具備 ListView 的 View 回收機制。也就是說所有 Item 會一次全部 inflate 出來,資料量很大時記憶體與效能都會吃緊。若你的清單可能超過數百項,建議改用 RecyclerView 搭配 GridLayoutManager——這是官方自 Lollipop 起提供的方案,具備完整的回收與自動換行能力,能直接取代這個自定義控件的大部分使用情境。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved