Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> listview實現左右滑動監聽

listview實現左右滑動監聽

編輯:關於Android編程

在android開發中會碰到有頂部導航並且下面顯示的內容是一個listview,此時要想實現左右滑動切換頂部導航的選項是不能實現的,因為listview自己消耗橫向滑動事件。因為我可以通過繼承listview,對左右滑動事件進行消耗,不在讓原生的listview處理。

效果圖:
這裡寫圖片描述

思路就是繼承listview,設置一個GestureDetector監聽滑動手勢,如果左右滑動進行處理調用一個自己寫的左右滑動的接口。

下面是我封裝的一個可以接受左右滑動的listview,其他用法跟普通的listview一樣,可以直接使用:

package com.yasin.libs;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
import android.widget.ListView;

/*
 * 該listview是對左右滑動進行了監聽,
 * 我也寫一個OnFlingListener接口,使用該listview的時候通過setOnFlingListener接口即可實現左右滑動時要實現的操作
 * */
public class HSlidableListView extends ListView {
    Context context;
    GestureDetector gestureDetector;
    OnFlingListener mListener;

    /*
     * 設置左右滑動監聽
     * */
    public void setOnFlingListener(OnFlingListener listener) {
        this.mListener = listener;
        gestureDetector = new GestureDetector(context, new Gesture(context,
                mListener));
    }

    public HSlidableListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;

    }

    public HSlidableListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
    }

    public HSlidableListView(Context context) {
        super(context);
        this.context = context;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        if (gestureDetector.onTouchEvent(ev))
            return true;//當左右滑動時自己處理
        return super.onTouchEvent(ev);
    }

    /*
     * 滑動監聽
     * */
    public class Gesture implements OnGestureListener {
        Context context;
        OnFlingListener mListener;

        public Gesture(Context context, OnFlingListener listener) {
            this.context = context;
            this.mListener = listener;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                float distanceX, float distanceY) {
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {

        }

        @Override
        /** 
         * 
         */
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
            if (Math.abs(e1.getX() - e2.getX()) > Math.abs(e1.getY()
                    - e2.getY())) {//當左右滑動距離大於上下滑動距離時才認為是左右滑
                // 左滑
                if (e1.getX() - e2.getX() > 100) {
                    mListener.onLeftFling();
                    return true;
                }
                // 右滑
                else if (e1.getX() - e2.getX() < -100) {
                    mListener.onRightFling();
                    return true;
                }
            }
            return true;
        }

    }

    /*
     * 左右滑動時調用的監聽接口
     * */
    public interface OnFlingListener {
        public void onLeftFling();
        public void onRightFling();
    }
}

使用舉例:
xml布局文件




    


        

    

    

    
        

        

        

    

    
    


MainActivity代碼:

package com.yasin.hslidablelistview;

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





import com.yasin.libs.HSlidableListView;
import com.yasin.libs.HSlidableListView.OnFlingListener;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class MainActivity extends Activity {

    RadioGroup radioGroup;
    RadioButton maintainRB,warmRB;
    HSlidableListView listview;
    List mData=new ArrayList();
    List wData=new ArrayList();
    MAdapter mAdapter;
    WAdapter wAdapter;
    int flag =0 ;//0表示左邊選中,1表示右邊選中

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

    private void initView() {
        maintainRB = (RadioButton) findViewById(R.id.maintain);
        warmRB = (RadioButton) findViewById(R.id.warm);
        listview = (HSlidableListView) findViewById(R.id.msg_list);
        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView parent, View view,
                    int position, long id) {
                Log.e("yasin","click");
            }

        });
        /*
         * 給該listview設置監聽,做出相應操作
         * */
        listview.setOnFlingListener(new OnFlingListener(){

            @Override
            public void onLeftFling() {
                if(flag == 0){
                    warmRB.performClick();
                    flag = 1;
                }

            }

            @Override
            public void onRightFling() {
                Log.e("y-p","right");
                if(flag == 1){
                    maintainRB.performClick();
                    flag = 0;
                }

            }


        });
        getDataT(1);

        radioGroup = (RadioGroup) findViewById(R.id.type);
        radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId==R.id.maintain){
                    maintainRB.setTextColor(Color.parseColor("#000000"));
                    warmRB.setTextColor(Color.parseColor("#ffffff"));
                    flag = 0;
                    getDataT(1);
                }else if(checkedId==R.id.warm){
                    maintainRB.setTextColor(Color.parseColor("#ffffff"));
                    warmRB.setTextColor(Color.parseColor("#000000"));
                    flag = 1;
                    getDataT(2);
                }
            }
        });

    }

    public void getDataT(int flag){
        if(flag == 1){
            mData.clear();
            for(int i=0;i<7;i++){
                MaintainSensor m = new MaintainSensor();
                m.id = i+"";
                m.fname = "養殖"+i+"廠";
                m.sname = i+"設備";
                m.snum = i+"";
                m.desc = "1藥劑更換,包含廢液袋更換和純淨水更換 2.進樣口過濾頭更換 3.傳感器清理 4.太陽板清理";
                m.isMaintain = (i%2==0)?"0":"1";
                mData.add(m);
            }
            mAdapter = new MAdapter(MainActivity.this,mData);
            listview.setAdapter(mAdapter);
        }else{
            wData.clear();
            for(int i=0;i<7;i++){
                WarmMessage w = new WarmMessage();
                w.id = i+"";
                w.title = "養殖"+i+"廠";
                w.content = i+"設備";
                w.time = i+"";
                wData.add(w);
            }
            wAdapter = new WAdapter(MainActivity.this,wData);
            listview.setAdapter(wAdapter);
        }
    }

    private class MaintainSensor{
        String id,fname,snum,sname,desc,isMaintain;
    }

    private class WarmMessage{
        String id,title,content,time;
    }

    private class MAdapter extends BaseAdapter{

        Context mContext;
        List data;

        public MAdapter(Context c,List m){
            this.mContext = c;
            this.data = m;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return data.size();
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return data.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup arg2) {
            ViewHolder holder;
            if(convertView==null){
                convertView = LayoutInflater.from(mContext).inflate(R.layout.maintain_item, null);
                holder = new ViewHolder();
                holder.changName = (TextView) convertView.findViewById(R.id.chang_name);
                holder.sensorName = (TextView) convertView.findViewById(R.id.sensor_name);
                holder.desc = (TextView) convertView.findViewById(R.id.maintain_desc);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            MaintainSensor maint = data.get(i);
            holder.changName.setText(maint.fname);
            holder.sensorName.setText(maint.sname);
            holder.desc.setText(maint.desc);
            return convertView;
        }

        private class ViewHolder{
            TextView changName,sensorName,desc;
        }

    }

    private class WAdapter extends BaseAdapter{

        Context mC;
        List data;

        public WAdapter(Context c,List d){
            this.mC = c;
            this.data = d;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if(convertView==null){
                holder = new ViewHolder();
                convertView = LayoutInflater.from(mC).inflate(R.layout.item_warm_msg, null);
                holder.title = (TextView) convertView.findViewById(R.id.msg_title);
                holder.time = (TextView) convertView.findViewById(R.id.msg_time);
                holder.content = (TextView) convertView.findViewById(R.id.msg_content);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }

            WarmMessage warm = data.get(i);
            holder.title.setText(warm.title);
            holder.time.setText(warm.time);
            holder.content.setText(warm.content);
            return convertView;
        }

        private class ViewHolder{
            TextView title,time,content;
        }

    }

}

以上就是一個使用范例,有些資源文件我沒有貼出。

PS:左右滑動的事件是由自定義的Listview監聽的,如果你滑動的地方不在該listview上是無法滑動的。(例如你listview中的item只有一條,下面時候空白,你滑動空白時是無法監聽到滑動事件,你需要在該activity或fragment中監聽左右滑動事件)
github全部源碼:https://github.com/yangzhenkun/HSlidableListView

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved