Android PickView high imitation ios time selector (city or multi-level selector), a variety of formats for you to choose

At present, based on design reasons, our android-side development mostly follows the path of ios in many UI design styles. One is that many UIs and designs are unified in order to achieve a unified effect. Second, it is very convenient to set up. After all, there are not many UIs designed by android. It is indeed simple and beautiful. Of course, I can see how powerful ios is to the customer's experience and senses. However, I believe that in this fast-developing era, with the efforts of all generations of android's predecessors, the theme style of android is bound to be self-contained and humanized. Let's talk about the time picker and the city picker.
Today , let's talk about the use of pickview. Pay attention to the description of other functions of the time picker. Readers can dig it out by themselves. Relatively speaking, it is very simple. You just set it up.
Add dependencies, one is pickview, the other is gson parsing

 compile 'com.contrarywind:Android-PickerView:3.2.4'
    compile 'com.google.code.gson:gson:2.7'

Okay, the above picture
write picture description here
shows 100-day event list, and the
write picture description here
three-level province and city selector.
write picture description here

code

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.sxm.okhttpdemo.R;
import com.sxm.okhttpdemo.bean.JsonBean;
import com.sxm.okhttpdemo.utils.JsonFileReader;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class TimeViewActivity extends Activity {
    private Context context;
    private TextView tv_time_view;
    ArrayList<JsonBean> options1Items = new ArrayList<>();
    ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private String city;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_view);
            initJsonData();

        context = this;
        tv_time_view = (TextView) findViewById(R.id.tv_time_view);
        tv_time_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // showIOSDate(tv_time_view,TimePickerView.Type.YEAR_MONTH_DAY,"选择时间",1);
                showPickerView();
            }
        });
    }

    /**
     * 时间选择器
     * @param textView 显示选择时间的控件
     * @param type 类型
     * @param title 选择器弹窗的标题
     * @param flag 返回时间的格式
     */
    public void showIOSDate(final TextView textView, TimePickerView.Type type, String title, final int flag){


        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH,+100);// 选择时间的间隔
        TimePickerView pvTime = new TimePickerView.Builder(context, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date2, View v) {//选中事件回调
                String time = getTime(date2,flag);// 返回的时间
                textView.setText(time);
            }
        })
                .setType(type)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(20)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText(title)//标题文字
                .setOutSideCancelable(true)//点击屏幕,点在控件外部范围时,是否取消显示
                .isCyclic(false)//是否循环滚动
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                .setTitleColor(getResources().getColor(R.color.textcolors))//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.textcolorh))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.textcolorh))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.colorbg))//标题背景颜色 Night mode
//                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
                // .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话,默认是系统时间
                //calendar.add(Calendar.DAY_OF_MONTH,-1);
                .setRangDate(Calendar.getInstance(),instance)//起始终止年月日设定
//                        .setLabel("年","月","日","时","分","秒")
                .isCenterLabel(false) //是否只显示中间选中项的label文字,false则每项item全部都带有label。
                .build();
        pvTime.setDate(Calendar.getInstance());//注:根据需求来决定是否使用该方法(一般是精确到秒的情况),此项可以在弹出选择器的时候重新设置当前时间,避免在初始化之后由于时间已经设定,导致选中时间与当前时间不匹配的问题。
        pvTime.show();

    }

    /**
     * 格式化时间
     * @param date 时间数据源
     * @param type 时间返回格式
     * @return
     */
    public String getTime(Date date ,int type) {//可根据需要自行截取数据显示
        SimpleDateFormat format = null;
        if (type==1){
            format = new SimpleDateFormat("yyyy-MM-dd");
        }else if (type==0){
            format = new SimpleDateFormat("HH:mm");
        }else {
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        }

        return format.format(date);
    }



    public void showPickerView() {
        OptionsPickerView pvOptions=new OptionsPickerView.Builder(TimeViewActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                city = options1Items.get(options1).getPickerViewText() +
                options2Items.get(options1).get(options2) +
                options3Items.get(options1).get(options2).get(options3);
                tv_time_view.setText(city);
            }
        }).setTitleText("")
                .setCancelText("取消")
                .setSubmitText("选定")
                .setTextColorCenter(Color.BLACK)
                .setDividerColor(Color.GRAY)
                .setOutSideCancelable(false)
                .setContentTextSize(25)
                .build();
        //  pvOptions.setPicker(options1Items);//一级选择器
       // pvOptions.setPicker(options1Items, options2Items);//二级选择器
         pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();

    }
    private void initJsonData() {   //解析数据

        /**
         * 注意:assets 目录下的Json文件仅供参考,实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        //  获取json数据
        String JsonData = JsonFileReader.getJson(TimeViewActivity.this, "province_data.json");
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意:如果是添加的JavaBean实体,则实体类需要实现 IPickerViewData 接口,
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表(第二级)
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表(第三极)

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据,建议添加空字符串,防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            org.json.JSONArray data = new org.json.JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

}

The city three-level selector requires you to find a city resource file. Later, I will upload one and you can download it if you need it. I will put all the code resources in it. You need to copy and paste it yourself, and you can use simple and practical functions.

Code and resource download https://download.csdn.net/download/naide_s/10343498

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325684947&siteId=291194637