Android 时间城市——选择器

本文介绍了一款用于Android项目的日期和城市选择器组件的封装方法,通过使用Android-PickerView库,实现了自定义日期选择器和城市选择器的功能。文章详细展示了如何配置和使用这些选择器,并提供了代码示例。
这个使用还是挺简单的,如果项目中多次使用的话,感觉还是比较麻烦的,我给封装起来了

    Guthub上官网地址:
    https://github.com/Bigkoo/Android-PickerView

   依赖

api 'com.contrarywind:Android-PickerView:3.2.7'//选择器
/*===========日期选择器=================*/
TimePicker类
public class TimePicker {
    /*
     * 时间选择器
     * */
    public static void initTimePicker(Context context, TextView textview) {//选择出生年月日

        //控制时间范围(如果不设置范围,则使用默认时间1900-2100年,此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Date curDate = new Date(2025,1,1);//获取当前时间
        SimpleDateFormat formatter_year = new SimpleDateFormat("yyyy ");
        String year_str = formatter_year.format(curDate);
        int year_int = (int) Double.parseDouble(year_str);


        SimpleDateFormat formatter_mouth = new SimpleDateFormat("MM ");
        String mouth_str = formatter_mouth.format(curDate);
        int mouth_int = (int) Double.parseDouble(mouth_str);

        SimpleDateFormat formatter_day = new SimpleDateFormat("dd ");
        String day_str = formatter_day.format(curDate);
        int day_int = (int) Double.parseDouble(day_str);

        SimpleDateFormat xiaoshi = new SimpleDateFormat("HH ");
        String day_h = xiaoshi.format(curDate);
        int h_int = (int) Double.parseDouble(day_h);
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(1900, 0, 0);
        Calendar endDate = Calendar.getInstance();
        endDate.set(year_int, mouth_int - 1, day_int,h_int,0);
        //时间选择器
        TimePickerView pvTime1 = new TimePickerView.Builder(context, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数,如果show的时候没有添加参数,v则为null
                textview.setText(getTime(date));
            }
        })
                .setType(new boolean[]{true, true, true, true, false, false}) //年月日时分秒 的显示与否,不设置则默认全部显示
                .setLabel("年", "月", "日", "时", "分", "")//默认设置为年月日时分秒
                .isCenterLabel(false)
                .setDividerColor(context.getResources().getColor(R.color.black3))//black3 颜色值 #333333
                .setTextColorCenter(context.getResources().getColor(R.color.black3))//设置选中项的颜色  black3 颜色值 #333333
                .setTextColorOut(context.getResources().getColor(R.color.grey9))//设置没有被选中项的颜色 grey9  颜色值 #999999
                .setContentSize(21)
                .setDate(selectedDate)
                .setLineSpacingMultiplier(1.2f)
                .setTextXOffset(0, 0,0, 0, 0, 0)//设置X轴倾斜角度[ -90 , 90°]
                .setRangDate(startDate, endDate)
                .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                .setDecorView(null)
                .build();
        pvTime1.show();
    }
    public static String getTime(Date date) {//可根据需要自行截取数据显示
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return format.format(date);
    }
}

调用方式:

TimePicker.initTimePicker(context,holder.text_time);

/*===========城市选择器=================*/

CityUtils类
public class CityUtils {
    //  省
    private static List<ShengBean> options1Items = new ArrayList<ShengBean>();
    //  市
    private static ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    //  区
    private static ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    /**
     * 解析数据并组装成自己想要的list
     */
    public static void parseData(Context context, TextView textView){
        String jsonStr = new GetJsonDataUtil().getJson(context, "province.json");//获取assets目录下的json文件数据
//     数据解析
        Gson gson =new Gson();
        java.lang.reflect.Type type =new TypeToken<List<ShengBean>>(){}.getType();
        List<ShengBean>shengList=gson.fromJson(jsonStr, type);
//     把解析后的数据组装成想要的list
        options1Items = shengList;
//     遍历省
        for(int i = 0; i <shengList.size() ; i++) {
//         存放城市
            ArrayList<String> cityList = new ArrayList<>();
//         存放区
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();
//         遍历市
            for(int c = 0; c <shengList.get(i).city.size() ; c++) {
//        拿到城市名称
                String cityName = shengList.get(i).city.get(c).name;
                cityList.add(cityName);
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表
                if (shengList.get(i).city.get(c).area == null || shengList.get(i).city.get(c).area.size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(shengList.get(i).city.get(c).area);
                }
                province_AreaList.add(city_AreaList);
            }
            /**
             * 添加城市数据
             */
            options2Items.add(cityList);
            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }

        OptionsPickerView pvOptions =new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3 , View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).name +
                        options2Items.get(options1).get(option2) +
                        options3Items.get(options1).get(option2).get(options3);
                textView.setText(tx);
            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();

    }
}
读取Json文件的工具类 GetJsonDataUtil:
/**
 * <读取Json文件的工具类>
 *
 */

public class GetJsonDataUtil {


    public String getJson(Context context,String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}
ShengBean类:
public class ShengBean implements IPickerViewData {
    public String name;
    public List<Shi> city;
    public static class Shi{
        public String name;
        public List<String>area;

    }
    //  这个要返回省的名字
    @Override
    public String getPickerViewText() {
        return this.name;
    }
}
//新建assets目录 然后去github拷贝 province.json文件
使用方式:
 CityUtils.parseData(this,occupation) //上下文,控件ID

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值