组装原有控件实现横向滚动的时间选择器,可滑动 点击,初始状态在指定位置

简介

前段时间,产品设计了一个横向的滚动的时间选择器,由于工作很急,也没时间来自定义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




    

        

            
        
    
    

3.在Activity里面的调用

public class AttendanceActivity extends Activity{

private HorizontalScrollView scrollView;
private MyGridView gridView;
private float mdensity;
private List 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 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 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




    

        

        
    

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 getDate() {
        List list = new ArrayList();
        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 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.最后效果图组装原有控件实现横向滚动的时间选择器,可滑动 点击,初始状态在指定位置_第1张图片


就这样的,源码改天放上来。









你可能感兴趣的:(Android)