多布局之RecyclerView與Json數(shù)據(jù)(GridLayoutManager實(shí)現(xiàn))+多選

昨天一哥們熊sir要早睡早起用到了RecyclerView說要達(dá)到多布局的效果,然后他提到了GridLayoutManager來實(shí)現(xiàn),發(fā)現(xiàn)跟以往的常規(guī)的多布局有一點(diǎn)點(diǎn)不同,還是蠻有意思的。

ToolBar+DrawerLayout使用
Android 自定義側(cè)滑菜單效果(ViewDragHelper)
一站式CoordinatorLayout+ToolBar聯(lián)動(dòng)使用


1、進(jìn)入正文

  • LinearLayoutManager 線性布局管理器,支持橫向、縱向(效果相當(dāng)于ListView的效果)。
  • GridLayoutManager 網(wǎng)格布局管理器。
  • StaggeredGridLayoutManager 瀑布流式布局管理器。

現(xiàn)在就是準(zhǔn)備用GridLayoutManager來協(xié)助完成多布局。

2、舊事重提

老規(guī)矩還是在AS的build.gradle中添加依賴,然后同步一下就可以引入依賴包:

 compile 'com.android.support:recyclerview-v7:24.1.0'

效果展示

演示.gif

3、搞布局

把需要的布局羅列一下:

  • 一個(gè)主界面Activity的布局文件命名為activity_rvmoretype.xml
  • 兩種item樣式,分成兩個(gè)布局文件,標(biāo)題的布局item_rvmoretype_title.xml,內(nèi)容的布局item_rvmoretype_content.xml。
    activity_rvmoretype.xml如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_rvmoretype"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical"
    android:fitsSystemWindows="true"
    tools:context="com.sobergh.soberghalltest.widget.recyclerview.RVMoretypeActivity">

    <include layout="@layout/top_bar"
        android:id="@+id/toolbar"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_moretype"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:padding="20dp"
        android:overScrollMode="never"/>

    <!--style為去掉陰影效果-->
    <Button
        android:id="@+id/btn_moretype_submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/selector_rvmoretype_btn"
        android:layout_margin="5dp"
        style="?android:attr/borderlessButtonStyle"
        android:text="提交"/>
</LinearLayout>

item_rvmoretype_title.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="50dp"
              android:gravity="center"
              android:minHeight="50dp"
              android:orientation="vertical">

    <TextView
        android:id="@+id/tv_moretype_title"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:text="title"
        android:textSize="20sp"/>

</LinearLayout>

item_rvmoretype_content.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="30dp"
              android:gravity="center"
              android:minHeight="30dp"
              android:orientation="vertical">

    <TextView
        android:id="@+id/tv_moretype_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="content"
        android:background="@drawable/shape_homelist_location_normal"
        android:textSize="18sp"
        android:clickable="true"/>

</LinearLayout>

上面每個(gè)item都用到了選中與不選中背景也貼一下代碼:
非選中shape_homelist_location_normal.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners android:radius="15dp"/>
    <stroke android:width="1dp" android:color="#E5E5E5"/>
    <solid android:color="@android:color/white"/>

</shape>

選中shape_homelist_location_normal.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners android:radius="15dp"/>
    <solid android:color="@android:color/white"/>
    <stroke android:width="1dp" android:color="#5783EE"/>

</shape>

最后還有提交按鈕的背景selector_rvmoretype_btn.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true" android:drawable="@drawable/shape_homelist_location_pressed"/>
    <item android:drawable="@drawable/shape_homelist_location_normal"/>

</selector>

布局都有了接下來就是常規(guī)的使用Recyclerview了。

4、擼代碼

用到了Json數(shù)據(jù)就要來一串Json數(shù)據(jù)和一個(gè)實(shí)體類。

{
    "data":[
        {
            "isTitle":"1",
            "content":"標(biāo)題一取啥名",
            "price":""
        },
        {
            "isTitle":"0",
            "content":"內(nèi)容1",
            "price":"100"
        },
        {
            "isTitle":"0",
            "content":"內(nèi)容2",
            "price":"100"
        },
        {
            "isTitle":"0",
            "content":"內(nèi)容3",
            "price":"100"
        },
        {
            "isTitle":"0",
            "content":"內(nèi)容4",
            "price":"100"
        },
        {
            "isTitle":"0",
            "content":"內(nèi)容5",
            "price":"100"
        },
        {
            "isTitle":"0",
            "content":"內(nèi)容6",
            "price":"100"
        },
        {
            "isTitle":"0",
            "content":"內(nèi)容7",
            "price":"100"
        },
        {
            "isTitle":"1",
            "content":"標(biāo)題二取啥名",
            "price":""
        },
        {
            "isTitle":"0",
            "content":"內(nèi)容1",
            "price":"100"
        },
        {
            "isTitle":"0",
            "content":"內(nèi)容2",
            "price":"100"
        },
        {
            "isTitle":"0",
            "content":"內(nèi)容3",
            "price":"100"
        },
        {
            "isTitle":"0",
            "content":"內(nèi)容4",
            "price":"100"
        },
        {
            "isTitle":"0",
            "content":"內(nèi)容5",
            "price":"100"
        },
        {
            "isTitle":"0",
            "content":"內(nèi)容6",
            "price":"100"
        },
        {
            "isTitle":"0",
            "content":"內(nèi)容7",
            "price":"100"
        }
    ]
}

字符串有了可以整個(gè)實(shí)體類了命名ContentModel

/**
 * Created by Leogh on 2017/9/7.
 */

public class ContentModel {

    /**
     * isTitle : 1
     * content : 標(biāo)題一取啥名
     * price :
     */

    private List<DataBean> data;

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
        private String isTitle;
        private String content;
        private String price;

        public String getIsTitle() {
            return isTitle;
        }

        public void setIsTitle(String isTitle) {
            this.isTitle = isTitle;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public String getPrice() {
            return price;
        }

        public void setPrice(String price) {
            this.price = price;
        }
    }
}

既然用到了RecyclerView那Adapter是少不了的了,解釋什么的一般就放在代碼里。

/**
 * Created by Leogh on 2017/9/7.
 */

public class MoreTypeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

    private ContentModel mDatas = null;
    private Context mContext;
    private int TITLE_VIEW = 1;//標(biāo)題標(biāo)識(shí)
    private int CONTENT_VIEW = 2;//內(nèi)容標(biāo)識(shí)
    private SparseBooleanArray sparseBooleanArray = null;//緩存選中過的position

    public MoreTypeAdapter(ContentModel mDatas, Context mContext) {
        this.mDatas = mDatas;
        this.mContext = mContext;
        sparseBooleanArray = new SparseBooleanArray();
    }

    /**
     * 根據(jù)getItemViewType中返回的布局標(biāo)識(shí)確定布局
     * @param parent
     * @param viewType
     * @return
     */
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder holder = null;
        LayoutInflater inflater = LayoutInflater.from(mContext);
        if (viewType == TITLE_VIEW) {
            View view = inflater.inflate(R.layout.item_rvmoretype_title, parent, false);
            holder = new TitleViewHolder(view);
        } else {
            View view = inflater.inflate(R.layout.item_rvmoretype_content, parent, false);
            holder = new ContentViewHolder(view);
        }
        return holder;
    }

    /**
     * 綁定數(shù)據(jù)
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof TitleViewHolder) {
            ((TitleViewHolder) holder).tv_title.setText(mDatas.getData().get(position).getContent());
        } else if (holder instanceof ContentViewHolder){
            ((ContentViewHolder) holder).tv_content.setBackgroundResource(R.drawable.shape_homelist_location_normal);
            ((ContentViewHolder) holder).tv_content.setText(mDatas.getData().get(position).getContent());
            ((ContentViewHolder) holder).tv_content.setOnClickListener(new ClickItemListener(position));
        }
    }

    @Override
    public int getItemCount() {
        return mDatas.getData().size();
    }

    /**
     * 根據(jù)數(shù)據(jù)判斷使用什么樣的布局
     * @param position
     * @return 布局標(biāo)識(shí)
     */
    @Override
    public int getItemViewType(int position) {
        if ("1".equals(mDatas.getData().get(position).getIsTitle())) {//標(biāo)題
            return TITLE_VIEW;
        } else if ("0".equals(mDatas.getData().get(position).getIsTitle())) {//內(nèi)容
            return CONTENT_VIEW;
        }
        return super.getItemViewType(position);
    }

    public SparseBooleanArray getSelectedItemArray() {
        return sparseBooleanArray;
    }

    class ClickItemListener implements View.OnClickListener{
        private int currentPosition = -1;

        public ClickItemListener(int currentPosition) {
            this.currentPosition = currentPosition;
        }

        @Override
        public void onClick(View v) {
            if (currentPosition == -1) return;
            if (sparseBooleanArray.get(currentPosition)) {
                sparseBooleanArray.put(currentPosition, false);
                v.setBackgroundResource(R.drawable.shape_homelist_location_normal);
            } else {
                sparseBooleanArray.put(currentPosition, true);
                v.setBackgroundResource(R.drawable.shape_homelist_location_pressed);
            }
        }
    }

    class TitleViewHolder extends RecyclerView.ViewHolder {
        TextView tv_title;

        public TitleViewHolder(View itemView) {
            super(itemView);
            tv_title = (TextView) itemView.findViewById(R.id.tv_moretype_title);
        }
    }

    class ContentViewHolder extends RecyclerView.ViewHolder {
        TextView tv_content;
        public ContentViewHolder(View itemView) {
            super(itemView);
            tv_content = (TextView) itemView.findViewById(R.id.tv_moretype_content);
        }
    }
}

接下來就是Activity了:

public class RVMoretypeActivity extends BaseActivity implements View.OnClickListener{

    private RecyclerView rv_moretype = null;
    private Button btn_moretype_submit = null;

    private String jsonData = "";
    private ContentModel bean = null;
    private MoreTypeAdapter adapter = null;

    //這是繼承了自己封裝的BaseActivity重寫的方法 直接改成OnCreate就能用了 在繼承一下Activity就行了
    @Override
    public void init() {
        setContentView(R.layout.activity_rvmoretype);
        initView();
        initData();
        operRecyclerView();
    }

    private void initData() {
        String jsonStr = "{\"data\":[{\"isTitle\":\"1\",\"content\":\"標(biāo)題一取啥名\",\"price\":\"\"},{\"isTitle\":\"0\",\"content\":\"內(nèi)容1\",\"price\":\"100\"},{\"isTitle\":\"0\",\"content\":\"內(nèi)容2\",\"price\":\"100\"},{\"isTitle\":\"0\",\"content\":\"內(nèi)容3\",\"price\":\"100\"},{\"isTitle\":\"0\",\"content\":\"內(nèi)容4\",\"price\":\"100\"},{\"isTitle\":\"0\",\"content\":\"內(nèi)容5\",\"price\":\"100\"},{\"isTitle\":\"0\",\"content\":\"內(nèi)容6\",\"price\":\"100\"},{\"isTitle\":\"0\",\"content\":\"內(nèi)容7\",\"price\":\"100\"},{\"isTitle\":\"1\",\"content\":\"標(biāo)題二取啥名\",\"price\":\"\"},{\"isTitle\":\"0\",\"content\":\"內(nèi)容1\",\"price\":\"100\"},{\"isTitle\":\"0\",\"content\":\"內(nèi)容2\",\"price\":\"100\"},{\"isTitle\":\"0\",\"content\":\"內(nèi)容3\",\"price\":\"100\"},{\"isTitle\":\"0\",\"content\":\"內(nèi)容4\",\"price\":\"100\"},{\"isTitle\":\"0\",\"content\":\"內(nèi)容5\",\"price\":\"100\"},{\"isTitle\":\"0\",\"content\":\"內(nèi)容6\",\"price\":\"100\"},{\"isTitle\":\"0\",\"content\":\"內(nèi)容7\",\"price\":\"100\"}]}";
        Gson gson = new Gson();
        bean = gson.fromJson(jsonStr, ContentModel.class);
    }

    private void operRecyclerView() {
        adapter = new MoreTypeAdapter(bean, this);
        rv_moretype.addItemDecoration(new ItemDistanceDecoration(this));
        GridLayoutManager manager = new GridLayoutManager(this, 2);//兩列
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (adapter.getItemViewType(position) == 1) {
                    return 2;//title占兩列
                } else {
                    return 1;//內(nèi)容占一列
                }
            }
        });
        rv_moretype.setLayoutManager(manager);
        rv_moretype.setAdapter(adapter);
    }

    private void initView() {
        rv_moretype = (RecyclerView) findViewById(R.id.rv_moretype);
        btn_moretype_submit = (Button) findViewById(R.id.btn_moretype_submit);
        btn_moretype_submit.setOnClickListener(this);
    }

    @Override
    public String setTitle() {
        return "Recyclerview多布局";
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == btn_moretype_submit.getId()) {
            if (adapter != null && adapter.getSelectedItemArray().size() > 0) {
                String selectedItem = "";
                SparseBooleanArray selectedItemArray = adapter.getSelectedItemArray();
                for (int i = 0; i < bean.getData().size(); i++) {
                    if (selectedItemArray.get(i)) {
                        selectedItem += "第" + i;
                    }
                }
                Toast.makeText(mActivity, selectedItem, Toast.LENGTH_SHORT).show();
                adapter.getSelectedItemArray().clear();
                adapter.notifyDataSetChanged();
            } else {
                Toast.makeText(mActivity, "你都沒有選 也想點(diǎn)我?", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

注意了:(看黑板 這個(gè)是重點(diǎn)要考
相對(duì)于正常的多布局,GridLayoutManager多布局這個(gè)時(shí)候就用了不一樣的方式,在setSpanSizeLookup來決定你的item要跨幾列顯示,標(biāo)題當(dāng)然是跨兩列,內(nèi)容只占一個(gè)位置。

manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (adapter.getItemViewType(position) == 1) {
                    return 2;//title占兩列
                } else {
                    return 1;//內(nèi)容占一列
                }
            }
        });

等一下,忘記貼分割線的東西了:

/**
 * Created by Leogh on 2017/9/7.
 */

public class ItemDistanceDecoration extends RecyclerView.ItemDecoration {
    private Context context;
    private int mDistance = 20;

    public ItemDistanceDecoration(Context context) {
        this.context = context;
        mDistance = dp2px(context, mDistance);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int s = parent.getChildAdapterPosition(view);
        int sss = parent.getAdapter().getItemViewType(parent.getChildAdapterPosition(view));
        if (parent.getAdapter().getItemViewType(parent.getChildAdapterPosition(view)) == 2) {//內(nèi)容item才加底部邊距
            outRect.bottom = mDistance;
        }
        outRect.right = mDistance;
        outRect.left = mDistance;

    }

    /**
     * dp轉(zhuǎn)px
     */
    private int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}

記錄完了,收工

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,606評(píng)論 6 533
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,582評(píng)論 3 418
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 176,540評(píng)論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,028評(píng)論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,801評(píng)論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,223評(píng)論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,294評(píng)論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,442評(píng)論 0 289
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,976評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,800評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,996評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,543評(píng)論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,233評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,662評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,926評(píng)論 1 286
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,702評(píng)論 3 392
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,991評(píng)論 2 374

推薦閱讀更多精彩內(nèi)容