Android开发之实现省市区三级联动

最近项目要做省市区三级联动效果,今天我来实现一下。先看效果图:
Android开发之实现省市区三级联动_第1张图片
1, 在project的build.gradle添加如下代码:

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

2,在app/build.gradle文件中添加如下代码:

compile 'com.github.open-android:CityPickerWebView:0.1.0'

3,简单的布局文件:


<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"
    tools:context="com.classical.example_citypicker.MainActivity">

    <TextView
        android:id="@+id/tv_show"
        android:text="请选择您所在的省市区"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn_selector"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="请选择"/>
LinearLayout>

4.在代码中使用:

package com.classical.example_citypicker;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import me.leefeng.citypicker.CityPicker;
import me.leefeng.citypicker.CityPickerListener;

public class MainActivity extends AppCompatActivity implements CityPickerListener {
    private TextView mShow;
    private Button mSelector;
    private CityPicker cityPicker;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        cityPicker = new CityPicker(MainActivity.this,this);

        mSelector = (Button)findViewById(R.id.btn_selector);
        mShow = (TextView)findViewById(R.id.tv_show);

        mSelector.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cityPicker.show();
            }
        });
    }

    @Override
    public void getCity(String s) {
        mShow.setText(s);
    }

    @Override
    public void onBackPressed() {
        if (cityPicker.isShow()) {
            cityPicker.close();
            return;
        }
        super.onBackPressed();
    }
}

好了,到此结束。如果你的项目中,正好有这么个需求功能,尽管拿去,不用谢!

你可能感兴趣的:(Android开源框架)