1. 程式人生 > >組裝原有控制元件實現橫向滾動的時間選擇器,可滑動 點選,初始狀態在指定位置

組裝原有控制元件實現橫向滾動的時間選擇器,可滑動 點選,初始狀態在指定位置

簡介

前段時間,產品設計了一個橫向的滾動的時間選擇器,由於工作很急,也沒時間來自定義view,而且目前開發的專案很老了,不支援V7的包,所以我不能用recyclerview。我就將就之前的GridView和HorizontalScrollView,組裝了一哈就可以了。本來想在網上找一個,都沒有找到合適的。最後就自己寫的。程式碼有點粗糙,有些地方沒有優化,比如:日期篩選那裡用for迴圈獲取了很多日曆的物件。如果有時間,我會再優化一哈。不用說了直接上程式碼。 程式碼很簡單,我就不註釋了。

1.自定義GridView

自定義GridView為了禁止滑動,因為巢狀在HorizontalScrollView,HorizontalScrollView起到滾動作用。

import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;

public class MyGridView extends GridView{
    
    public boolean hasScrollBar = true;
    public MyGridView(Context context) {
        super(context);
    }

    public MyGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        
        int expandSpec = heightMeasureSpec;
        if (hasScrollBar) {
            expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);//根據子控制元件的高度設定高度
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}

2.佈局檔案activity_attendance.xml

<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" >


    <HorizontalScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#ffffff"
        android:fadingEdgeLength="0dp"
        android:scrollbars="none" >

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

            <com.mx.study.view.MyGridView
                android:id="@+id/grid_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#ffffff"
                android:divider="@null"
                android:dividerHeight="@null"
                android:fadingEdgeLength="0dp"
                android:listSelector="@android:color/transparent"
                android:numColumns="auto_fit"
                android:scrollbars="none"
                android:stretchMode="spacingWidthUniform" />
        </LinearLayout>
    </HorizontalScrollView>
    
</LinearLayout>

3.在Activity裡面的呼叫

public class AttendanceActivity extends Activity{

private HorizontalScrollView scrollView;
private MyGridView gridView;
private float mdensity;
private List<DateInfo> lists;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_attendance);
        initView();
    }
    @SuppressLint("NewApi") 
    private void initView(){
        gridView = (MyGridView) findViewById(R.id.grid_view);
        scrollView = (HorizontalScrollView) findViewById(R.id.scroll_view);
        lists = Utils.getDate();
        horizontalLayout(lists.size());
        adapter = new TimeAdapter(this,lists);
        adapter.setDate(dateFormat.format(new Date()));
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(onItemClickListener);
        scrollView.post(new Runnable() {  
            @Override  
            public void run() {  
                scrollView.smoothScrollTo((int) (60 * 12* mdensity), 0); 
            }  
        });
    }
      //gridview橫向佈局方法
    private void horizontalLayout(int size ){
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mdensity = dm.density;
        int allWidth = (int) (60 * size * mdensity);
        int itemWidth = (int) (60 * mdensity);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(allWidth, LinearLayout.LayoutParams.MATCH_PARENT);
        gridView.setLayoutParams(params);// 設定GirdView佈局引數
        gridView.setColumnWidth(itemWidth);// 列表項寬
        gridView.setHorizontalSpacing(Utils.dip2px(this, 1));// 列表項水平間距
        gridView.setStretchMode(GridView.NO_STRETCH);
        gridView.setNumColumns(size);//總長度
    private OnItemClickListener onItemClickListener = new OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
      adapter.setDate(lists.get( arg2).getDate());
      adapter.notifyDataSetChanged();
      }
    };

}

4.介面卡TimeAdapter

public class TimeAdapter extends BaseAdapter{
    
        private List<DateInfo> lists;
        private Context mContext;
        private String date;
        
        public String getDate() {
            return date;
        }

        public void setDate(String date) {
            this.date = date;
        }

        public TimeAdapter(Context context,List<DateInfo> lists){
            mContext = context;
            this.lists = lists;
        }
        
        @Override
        public int getCount() {
            return lists.size();
        }

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

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

        @SuppressLint("NewApi") 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder = new Holder();
            if(convertView == null){
                convertView = View.inflate(mContext, R.layout.item_date, null);
                holder.day = (TextView) convertView.findViewById(R.id.tv_day);
                holder.week = (TextView) convertView.findViewById(R.id.tv_week);
                convertView.setTag(holder);
            }else {
                holder = (Holder)convertView.getTag();
            }
            DateInfo dateInfo = lists.get(position);
            if(dateInfo!=null){
                holder.day.setText(dateInfo.getDay());
                holder.week.setText(dateInfo.getWeek());
                if(date.equals(dateInfo.getDate())){
                    holder.week.setTextColor(0xff1885d8);
                    holder.day.setBackgroundResource(R.drawable.round_bg);
                    holder.day.setTextColor(0xffffffff);
                }else{
                    holder.week.setTextColor(0xff999999);
                    holder.day.setTextColor(0xff999999);
                    holder.day.setBackground(null);
                }
            }
            return convertView;
        }
        
        public class Holder{
            TextView  week;
            TextView  day;
        }
        
    }

5.介面卡佈局item_date.xml

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

    <LinearLayout
        android:layout_width="60dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="#ffffff"
        android:gravity="center_horizontal"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tv_week"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:ellipsize="end"
            android:singleLine="true"
            android:text="星期三"
            android:textColor="#999999"
            android:textSize="@dimen/textsize_12sp" />

        <TextView
            android:id="@+id/tv_day"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:ellipsize="end"
            android:singleLine="true"
            android:gravity="center"
            android:text="2"
            android:textColor="#999999"
            android:textSize="@dimen/textsize_14sp" />
    </LinearLayout>

</RelativeLayout>

6.資料模型DateInfo

public class DateInfo {

    private String date;
    private String year;
    private String month;
    private String week;
    private String day;
    
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }

    public String getYear() {
        return year;
    }
    public void setYear(String year) {
        this.year = year;
    }
    public String getMonth() {
        return month;
    }
    public void setMonth(String month) {
        this.month = month;
    }
    public String getWeek() {
        return week;
    }
    public void setWeek(String week) {
        this.week = week;
    }
    public String getDay() {
        return day;
    }
    public void setDay(String day) {
        this.day = day;
    }
    
}

7.時間輔助方法Utils

public class Utils {

    @SuppressLint("SimpleDateFormat")
    public static List<DateInfo> getDate() {
        List<DateInfo> list = new ArrayList<DateInfo>();
        SimpleDateFormat dayFormat = new SimpleDateFormat("d");
        SimpleDateFormat weekFormat = new SimpleDateFormat("E");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = -15; i <= 15; i++) {
            DateInfo dateInfo = new DateInfo();
            Calendar mCalendar = Calendar.getInstance(); // 建立 Calendar 物件
            mCalendar.set(Calendar.DATE, mCalendar.get(Calendar.DATE) + i);// 當前日期的七天前的日期
            String day = dayFormat.format(mCalendar.getTime());
            String week = weekFormat.format(mCalendar.getTime());
            String date =dateFormat.format(mCalendar.getTime());
            dateInfo.setDay(day);
            dateInfo.setWeek(week);
            dateInfo.setDate(date);
            list.add(dateInfo);
        }
        return list;
    }

    public static void main(String[] args) {
        List<DateInfo> list = getDate();
        for (DateInfo dateInfo : list) {
            System.out.println(dateInfo.getDay());
            System.out.println(dateInfo.getWeek());
        }
    }

public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}

public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}

public static int px2sp(Context context, float pxValue) { 
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; 
return (int) (pxValue / fontScale + 0.5f); 
} 

public static int sp2px(Context context, float spValue) { 
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; 
return (int) (spValue * fontScale + 0.5f); 
}
}

8.最後效果圖

就這樣的,原始碼改天放上來。