1. 程式人生 > >Android 自定義GridLayout實現頻道管理

Android 自定義GridLayout實現頻道管理

前言

以前總是在CSDN上看各位前輩的精彩部落格,從中也學習了很多東西。其實自己也一直想寫部落格,直到今天終於要踏出這一步了,有點小興奮,哈哈!不足之處,還請各位同仁不吝賜教,拜謝!!!

話不多說,工作中我們時常會遇到頻道管理的需求,不少部落格使用GridView實現這一功能,個人喜歡用自定義的GridLayout實現,蘿蔔白菜各有所愛,嘿嘿。

功能


要實現的功能如上圖所示(當然,左邊只是一個參考,這裡介面不是重點,我們要實現這個功能)

1.   分上下兩部分

2.我的頻道實現了長按拖拽排序功能;同時,點選某一子條目時,將該條目從“我的頻道”中刪除,新增到“更多頻道”中。

3.更多頻道

”實現了點選事件,當點選某一子條目時,該子條目從更多頻道中刪除,新增到我的頻道”中

實現程式碼

主程式程式碼:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private DragGridLayout showGridLayout;
    private DragGridLayout hideGridLayout;

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

    private void initCustom() {
        showGridLayout = (DragGridLayout) findViewById(R.id.dgl_main_show);
        showGridLayout.setResource(R.drawable.selector_textbg, 10, 5);
        showGridLayout.setEnableDrag(true);
        List<String> items = new ArrayList<>();
        items.add("推薦");
        items.add("本地事");
        items.add("本地人");
        items.add("社群");
        items.add("圖集");
        items.add("要聞");
        items.add("熱點");
        items.add("旅遊");
        items.add("健康");
        showGridLayout.setItems(items);
        hideGridLayout = (DragGridLayout) findViewById(R.id.dgl_main_bottom);
        hideGridLayout.setEnableDrag(false);
        hideGridLayout.setResource(R.drawable.selector_textbg, 10, 5);
        List<String> items1 = new ArrayList<>();
        items1.add("家居");
        items1.add("奇石");
        items1.add("螺螄粉");
        items1.add("情感");
        items1.add("文化");
        items1.add("體育");
        items1.add("汽車");
        items1.add("本地號");
        items1.add("爆料");
        items1.add("時政");
        items1.add("美女");
        items1.add("公益");
        items1.add("公民榜樣");
        items1.add("親子");
        items1.add("社會");
        items1.add("舌尖柳州");
        items1.add("開心一刻");
        items1.add("居柳州");
        hideGridLayout.setItems(items1);

        //設定點選事件
        showGridLayout.setOnItemClickListener(new DragGridLayout.OnItemClickListener() {
            @Override
            public void onItemClick(TextView tv) {
                //當點選時,將返回的TextView從showGridLayout容器中刪除,在新增到hideGridLayout中
                showGridLayout.removeView(tv);
                hideGridLayout.addItem(tv.getText().toString());
            }
        });

        hideGridLayout.setOnItemClickListener(new DragGridLayout.OnItemClickListener() {
            @Override
            public void onItemClick(TextView tv) {
                hideGridLayout.removeView(tv);
                showGridLayout.addItem(tv.getText().toString());
            }
        });


    }

}

佈局:

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

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

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPry"
            android:text="點選增刪頻道,長按拖拽排序"/>

        <com.example.customview.DragGridLayout
            android:id="@+id/dgl_main_show"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </com.example.customview.DragGridLayout>

    </LinearLayout>

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

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPry"
            android:text="頻道管理"/>

        <com.example.customview.DragGridLayout
            android:id="@+id/dgl_main_bottom"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </com.example.customview.DragGridLayout>
        
    </LinearLayout>

</LinearLayout>
自定義GridLayout:

註釋比較詳細了,直接上程式碼,其中的一些引數,例如margin和padding,可根據專案需求,具體定製。

import android.animation.LayoutTransition;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.View;
import android.widget.GridLayout;
import android.widget.TextView;

import java.util.List;

/**
 * Created by ZLM on 2017/4/3.
 */

public class DragGridLayout extends GridLayout {

    private boolean ableDrag;
    private Rect[] rects;
    private View dragView;
    private OnItemClickListener itemClickListener;

    //拖拽監聽
    private View.OnDragListener odl = new View.OnDragListener() {
        @Override
        public boolean onDrag(View view, DragEvent dragEvent) {
            switch (dragEvent.getAction()) {
                case DragEvent.ACTION_DRAG_STARTED:
                    //當拖拽事件產生時,給每個子控制元件創建出對應的矩形
                    initRects();
                    break;
                case DragEvent.ACTION_DRAG_LOCATION:
                    //當手指移動時,判斷當前進入了哪一個子控制元件範圍內,並返回對應子控制元件的索引
                    int touchIndex = getTouchIndex(dragEvent);
                    if (touchIndex > -1 && dragView != null && dragView != DragGridLayout.this.getChildAt(touchIndex)) {
                        //先把拖拽的view從當前位置刪除,再新增到touchIndex上
                        DragGridLayout.this.removeView(dragView);
                        DragGridLayout.this.addView(dragView, touchIndex);
                    }
                    break;
                case DragEvent.ACTION_DRAG_ENDED:
                    if (dragView != null) {
                        dragView.setEnabled(true);
                    }
                    break;
                default:
                    break;
            }
            return true;
        }
    };
    //長按監聽
    private View.OnLongClickListener olcl = new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            //長按事件發生時,即給dragView賦值
            dragView = view;
            //拖拽事件
            view.startDrag(null, new View.DragShadowBuilder(view), null, 0);
            view.setEnabled(false);
            return false;
        }
    };


    private int getTouchIndex(DragEvent dragEvent) {
        for (int i = 0; i < rects.length; i++) {
            Rect rect = rects[i];
            if (rect.contains((int) dragEvent.getX(), (int) dragEvent.getY())) {
                return i;
            }
        }
        return -1;
    }

    //建立子控制元件對應的矩形
    private void initRects() {
        //給容器中的每一個子控制元件都新建一個矩形
        rects = new Rect[getChildCount()];
        for (int i = 0; i < getChildCount(); i++) {
            View childAt = getChildAt(i);
            rects[i] = new Rect(childAt.getLeft(), childAt.getTop(), childAt.getRight(), childAt.getBottom());
        }
    }

    public DragGridLayout(Context context) {
        this(context, null);
    }

    public DragGridLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setColumnCount(4);
        setLayoutTransition(new LayoutTransition());
    }

    //定義方法,由外部傳遞一個欄目的資料集合進來,在這裡根據資料集合動態建立表格介面
    public void setItems(List<String> items) {
        for (String item : items) {
            addItem(item);
        }
    }

    //定義方法,設定是否允許拖拽
    public void setEnableDrag(boolean EnableDrag) {
        ableDrag = EnableDrag;
        if (ableDrag) {
            setOnDragListener(odl);
        } else {
            setOnDragListener(null);
        }
    }

    //定義介面回撥
    public interface OnItemClickListener {
        public void onItemClick(TextView tv);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.itemClickListener = listener;
    }

    public void addItem(String item) {
        TextView tv = getNewTextView();
        tv.setText(item);
        this.addView(tv);
    }

    //定義方法,外部傳入子條目的背景資源Id,外邊距margin(px),tv內邊距padding(px)
    private final float scale = getContext().getResources().getDisplayMetrics().density;
    private int resId;
    private int margin;
    private int padding;

    public void setResource(int ResourceId, int margin, int padding) {
        this.resId = ResourceId;
        this.margin = (int) (margin * scale + 0.5f);
        this.padding = (int) (padding * scale + 0.5f);
    }


    public TextView getNewTextView() {

        GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels / 4 - 2 * margin;
        layoutParams.height = GridLayout.LayoutParams.WRAP_CONTENT;
        layoutParams.setMargins(margin, margin, margin, margin);

        TextView tv = new TextView(getContext());
        tv.setLayoutParams(layoutParams);
        tv.setGravity(Gravity.CENTER);
        tv.setBackgroundResource(resId);
        tv.setPadding(padding, padding, padding, padding);

        if (ableDrag) {
            tv.setOnLongClickListener(olcl);
        } else {
            tv.setOnLongClickListener(null);
        }

        tv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (itemClickListener != null) {
                    itemClickListener.onItemClick((TextView) view);
                }
            }
        });
        return tv;
    }
}
drawable/selector_textbg.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true" android:drawable="@drawable/shape_textbg_nomal"/>
    <item android:state_enabled="false" android:drawable="@drawable/shape_textbg_pressed"/>

</selector>
drawable/shape_textbg_nomal.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="1dp" android:color="@color/colorBlack"/>
    <corners android:radius="@dimen/dp8"/>
    <solid android:color="@color/colorWhite"/>
</shape>
drawable/shape_textbg_pressed.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="1dp"
            android:dashWidth="2dp"
            android:dashGap="3dp"
            android:color="@color/colorRed"/>
    <corners android:radius="@dimen/dp8"/>
    <solid android:color="@color/colorWhite"/>
</shape>