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

Android 動態加載布局:在 ListView 裡靈活拼裝頭像列表

編輯:關於 Android 程式設計

ListView 我們天天在用,但遇到結構比較複雜的 item 就開始頭疼。以資訊流為例,一條內容裡往往同時有頭像、暱稱、分類、正文、配圖、點讚、評論、分享,再加上一排「誰也讚過」的頭像。前面幾項都好辦,最後那排頭像反而最麻煩。

兩種思路

方案一:在 item 裡嵌套 GridView。GridView 用法和 ListView 幾乎一致,一行排幾張圖很合適。但 ListView 套 GridView 會遇到嵌套滑動與高度計算的問題,需要自己測量並固定 GridView 高度,寫起來並不輕鬆。

方案二:動態 addView。這也是本文要重點說的做法——先在 item 裡預留一個空的 LinearLayout 容器,再在 Adapter 裡根據數據動態往裡塞 ImageView。控制權完全在自己手上,也不涉及嵌套滾動。

布局:預留一個空容器

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:padding="@dimen/small_space"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.view.RoundedImageView
            android:id="@+id/iv_myspace_usericon"
            android:src="@drawable/usericon"
            android:layout_width="50dp"
            android:layout_height="50dp"/>

        <TextView
            android:id="@+id/tv_myspace_username"
            android:layout_marginLeft="@dimen/middle_space"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <TextView
            android:id="@+id/tv_myspace_time"
            android:layout_gravity="center_vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>

    <TextView
        android:id="@+id/tv_myspace_content"
        android:paddingLeft="@dimen/middle_space"
        android:paddingRight="@dimen/middle_space"
        android:paddingBottom="@dimen/middle_space"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <ImageView
        android:id="@+id/iv_myspace_image"
        android:scaleType="fitXY"
        android:paddingLeft="@dimen/middle_space"
        android:paddingRight="@dimen/middle_space"
        android:layout_width="match_parent"
        android:layout_height="140dp"/>

    <!-- 這個空容器就是頭像的落腳處 -->
    <LinearLayout
        android:id="@+id/ll_myspace_reply_icons"
        android:paddingTop="@dimen/small_space"
        android:paddingLeft="@dimen/middle_space"
        android:paddingRight="@dimen/middle_space"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </LinearLayout>

    <LinearLayout
        android:layout_marginTop="@dimen/small_space"
        android:paddingLeft="@dimen/middle_space"
        android:paddingRight="@dimen/middle_space"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/iv_myspace_like"
            android:src="@drawable/zan_icon"
            android:layout_width="20dp"
            android:layout_height="20dp"/>

        <TextView
            android:id="@+id/tv_myspace_zan_count"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="@dimen/small_space"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <ImageView
            android:id="@+id/iv_myspace_comment"
            android:layout_marginLeft="@dimen/middle_space"
            android:src="@drawable/pinglun_icon"
            android:layout_width="20dp"
            android:layout_height="20dp"/>

        <TextView
            android:id="@+id/tv_myspace_pinglun_count"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="@dimen/small_space"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</LinearLayout>

在 Adapter 中動態添加

核心只有幾行:new 一個 ImageView,設好 LayoutParams,加載圖片,最後 addView 進容器。

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100, 100);
params.setMargins(8, 0, 8, 0);
roundedImageView.setLayoutParams(params);
roundedImageView.setScaleType(ImageView.ScaleType.FIT_XY);

if (!"".equals(replyUrl.get(m)) && replyUrl.get(m) != null) {
    ImageLoader.getInstance().displayImage(replyUrl.get(m), roundedImageView);
} else {
    roundedImageView.setImageDrawable(context.getResources().getDrawable(R.drawable.usericon));
}

if (m == count) {
    // 超出顯示上限時,最後一格放省略圖
    roundedImageView.setImageDrawable(
            context.getResources().getDrawable(R.drawable.wozaixianchangxiangqing_shenglve));
} else {
    holder.llReplyIcons.addView(roundedImageView);
}

顯示幾個頭像不宜寫死,按屏幕寬度算更合理:

WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();
int count = width / 116; // 每個頭像約佔 116px

當循環走到 m == count 時,用一張省略號圖片收尾,視覺上表達「還有很多」。

順手解決頭像點擊

有人問過頭像點進個人主頁怎麼做。與其去判斷觸摸坐標落在第幾個頭像上,不如在添加子視圖時就把監聽掛好,代碼反而更短:

for (int m = 0; m < replyUrl.size(); m++) {
    RoundedImageView roundedImageView = new RoundedImageView(context);
    final int finalM = m;
    roundedImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (story.getReply_user_id().get(finalM) != null) {
                Intent intent = new Intent(context, MyStoryActivity.class);
                intent.putExtra("userid", story.getReply_user_id().get(finalM));
                intent.putExtra("user_iconurl", story.getReply_user_icon_url().get(finalM));
                intent.putExtra("username", story.getReply_user_name().get(finalM));
                intent.putExtra("flag", "others");
                context.startActivity(intent);
            } else {
                Intent intent = new Intent(context, StoryFavoriteAcitvity.class);
                intent.putExtra("storyId", story.getId());
                context.startActivity(intent);
            }
        }
    });

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100, 100);
    params.setMargins(8, 0, 8, 0);
    roundedImageView.setLayoutParams(params);
    roundedImageView.setScaleType(ImageView.ScaleType.FIT_XY);

    if (!"".equals(replyUrl.get(m)) && replyUrl.get(m) != null) {
        ImageLoader.getInstance().displayImage(replyUrl.get(m), roundedImageView);
    } else {
        roundedImageView.setImageDrawable(context.getResources().getDrawable(R.drawable.usericon));
    }

    if (m == count) {
        roundedImageView.setImageDrawable(
                context.getResources().getDrawable(R.drawable.wozaixianchangxiangqing_shenglve));
    } else {
        holder.llReplyIcons.addView(roundedImageView);
    }
}

因為 finalM 是每次循環新建的局部變量,匿名內部類捕獲後每個頭像各自持有自己的下標,點擊時不會串位——這一點在寫循環監聽時要格外小心。

看看最終效果:

整體結構和參考的那款 App 基本一致。相比嵌套 GridView,動態加載的代碼量更少,行為也更可控,適合 item 結構變化頻繁的場景。

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