Android XPopup弹窗

XPopup

Android 开发过程中会遇到各种各样的需求,那么,如果当你拥有一个产品经理非常喜欢各种小提示的时候(没错,我的上个产品就是这样,美其名曰用户体验),你就会用到弹窗,各种弹窗,哪里都有弹窗!!!一开始我封装了一个小型弹窗来实现他的需求,到后来,变本加厉,我的小弹窗根本不够用。

然后,直到我遇见了她!XPopup,是她拯救我于水火之中,让我感受到了人间冷暖。接下来,就让我们一起来康康简单的入门使用吧。

XPopup

食用方法

一如既往的添加Gradle依赖:

implementation 'com.lxj:xpopup:1.9.0' //就是androidx版本
//从1.8.12开始,包变为androidx版本,且只提供androidx版本。
//从1.8.12开始,包变为androidx版本,且只提供androidx版本。
//从1.8.12开始,包变为androidx版本,且只提供androidx版本。

//for androidx.
//implementation 'com.lxj:xpopup:1.8.10-x'  //从1.8.12开始,没有-x版本了

必须添加的依赖库:

//版本号在26以及以上即可
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'

以上导入,build完成就可以使用了,更详细的使用方法建议去他的GitHub官网查看,接下来我说说我在使用过程中总结的一些心得和一些常用的弹窗编写分享。

最普通的弹窗 (确认,取消)

这种弹窗是最普通,也是最好用的,他的组成就四个部分,title(标题)、content(文案)、confirm(确认)、cancel(取消),对应的布局里面,必须包含的TextView以及id有:tv_title,tv_content,tv_cancel,tv_confirm

R.layout.my_confim_popup

<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
    android:background="@drawable/dialog_confirm"
    android:orientation="vertical">


    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:textColor="#ff333333"
        android:textSize="14sp"
        tools:text="测试标题" />

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="35dp"
        android:layout_marginTop="15dp"
        android:layout_marginRight="35dp"
        android:layout_marginBottom="15dp"
        android:gravity="center"
        android:padding="10dp"
        android:textColor="#ff333333"
        android:minHeight="100dp"
        android:textSize="14sp"
        tools:text="测试内容" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#F7F7F7" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp">

        <TextView
            android:id="@+id/tv_cancel"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="取消"
            android:textSize="14sp" />

        <View
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:background="#F7F7F7" />

        <TextView
            android:id="@+id/tv_confirm"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="确认"
            android:textColor="#f00"
            android:textSize="14sp" />
    </LinearLayout>

</LinearLayout>
new XPopup.Builder(getActivity())
                        .maxWidth((int) (ScreenUtils.getScreenWidth() * 0.7))
                        .asConfirm("title", "content",
                                "confirmBtnText",
                                "cancelBtnText",
                                new OnConfirmListener() {
                                    @Override
                                    public void onConfirm() {
                                        ToastUtils.showShort("confirmListener");
                                    }
                                },
                                new OnCancelListener() {
                                    @Override
                                    public void onCancel() {
                                        ToastUtils.showShort("cancelListener");
                                    }
                                }, false)
                        .bindLayout(R.layout.my_confim_popup)
                        .show();

 效果图

上面呢是最简单的使用方法,其中maxWidth表示的是弹窗所在屏幕宽度占比,下面贴一段他项目里面的源码,相关的数据参数一眼就能看懂啦!

/**
         * 显示确认和取消对话框
         *
         * @param title           对话框标题,传空串会隐藏标题
         * @param content         对话框内容
         * @param cancelBtnText   取消按钮的文字内容
         * @param confirmBtnText  确认按钮的文字内容
         * @param confirmListener 点击确认的监听器
         * @param cancelListener  点击取消的监听器
         * @param isHideCancel    是否隐藏取消按钮
         * @return
         */
        public ConfirmPopupView asConfirm(CharSequence title, CharSequence content, CharSequence cancelBtnText, CharSequence confirmBtnText, OnConfirmListener confirmListener, OnCancelListener cancelListener, boolean isHideCancel) {
            popupType(PopupType.Center);
            ConfirmPopupView popupView = new ConfirmPopupView(this.context);
            popupView.setTitleContent(title, content, null);
            popupView.setCancelText(cancelBtnText);
            popupView.setConfirmText(confirmBtnText);
            popupView.setListener(confirmListener, cancelListener);
            if (isHideCancel) popupView.hideCancelBtn();
            popupView.popupInfo = this.popupInfo;
            return popupView;
        }

        public ConfirmPopupView asConfirm(CharSequence title, CharSequence content, OnConfirmListener confirmListener, OnCancelListener cancelListener) {
            return asConfirm(title, content, null, null, confirmListener, cancelListener, false);
        }

        public ConfirmPopupView asConfirm(CharSequence title, CharSequence content, OnConfirmListener confirmListener) {
            return asConfirm(title, content, null, null, confirmListener, null, false);
        }

CenterPopupView

当最原始的弹窗满足不了你的需求时,这时候你就需要自定义弹窗啦,使用方法也很简单,新建一个类继承CenterPopupView就行了,同样的还有BottomPopupView,AttachPopupView/HorizontalAttachPopupView,DrawerPopupView,PartShadowPopupView,FullScreenPopupView

这里我就贴一段我在开发过程中使用到最多的支付密码弹窗(简陋不堪。。。):

R.layout.dialog_pay_password

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@drawable/shape2">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@drawable/shape2"
        android:orientation="vertical"
        >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:orientation="horizontal">

            <View
                android:layout_width="50dp"
                android:layout_height="1dp"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:background="@color/line" />

            <TextView
                android:id="@+id/tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="请输入支付密码"
                android:textColor="@color/gray_9191"
                android:textSize="14sp" />

            <View
                android:layout_width="50dp"
                android:layout_height="1dp"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:background="@color/line" />

        </LinearLayout>

        <TextView
            android:id="@+id/tv_money"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="15dp"
            android:textStyle="bold"
            tools:text="¥ 1234元"
            android:textColor="@color/normal_text"
            android:textSize="20sp" />

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_marginTop="15dp"
            android:layout_height="50dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            app:cardCornerRadius="5dp"
            >
            <EditText
                android:id="@+id/et_pwd"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:hint="请输入支付密码"
                android:inputType="textPassword"
                android:background="@null"
                android:textColorHint="@color/gray_9191"
                android:textSize="14sp" />

        </androidx.cardview.widget.CardView>



        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:layout_marginTop="10dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/tv_cancel"
                android:layout_width="0dp"
                android:layout_height="40dp"
                android:layout_weight="1"
                android:background="@color/white"
                android:gravity="center"
                android:text="取消"
                android:textColor="@color/normal_text"
                android:textSize="14sp" />

            <View
                android:layout_width="1dp"
                android:layout_height="30dp"
                android:layout_marginTop="1dp"
                android:layout_marginBottom="1dp"
                android:background="@color/line" />

            <TextView
                android:id="@+id/tv_confirm"
                android:layout_width="0dp"
                android:layout_height="40dp"
                android:layout_weight="1"
                android:background="@color/white"
                android:gravity="center"
                android:text="确认"
                android:textColor="@color/red"
                android:textSize="14sp" />
        </LinearLayout>


    </LinearLayout>


</FrameLayout>

PayPasswordDialog

import android.content.Context;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.lxj.xpopup.core.CenterPopupView;

import cn.sunsapp.owner.R;


public class PayPasswordDialog extends CenterPopupView {


    private String mMoney = "";
    private String mTitle = "";
    private EditText etPwd;

    public PayPasswordDialog(@NonNull Context context, String money, String title) {
        super(context);
        mTitle = title;
        mMoney = money;
    }


    @Override
    protected int getImplLayoutId() {
        return R.layout.dialog_pay_password;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        ((TextView) findViewById(R.id.tv_title)).setText(mTitle);
        ((TextView) findViewById(R.id.tv_money)).setText("¥ "+mMoney);

        findViewById(R.id.tv_cancel).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                PayPasswordDialog.this.dismiss();
            }
        });

        etPwd = (EditText) findViewById(R.id.et_pwd);
        findViewById(R.id.tv_confirm).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mListener != null) {
                    mListener.onConfirm(etPwd.getText().toString());
                }
            }
        });
    }

    private OnConfirnListener mListener = null;

    public PayPasswordDialog setOnConfirmListener(OnConfirmListener listener){

        mListener = listener;
        return this;
    }

    public interface OnConfirmListener{
        void onConfirm(String pwd);
    }
}

使用过程中可能会遇到一些弹窗在屏幕里面占比或大或小的局面,这时候你可以重写一下他里面的一个getMaxWidth()方法,效果和上面的那个maxWidth一样

@Override
    protected int getMaxWidth() {
        return (int) (XPopupUtils.getWindowWidth(getContext()) * 0.8f);
    }

使用:

PayPasswordDialog payPasswordDialog = new PayPasswordDialog(mContext, payNumEditTextValue, "余额提现").setOnConfirmListener(new PayPasswordDialog.OnConfirmListener() {
            @Override
            public void onConfirm(String pwd) {
                dismiss();
                ToastUtils.showShort("提现密码"+pwd);
            }
        });

        new XPopup.Builder(mContext)
                .asCustom(payPasswordDialog)
                .show();

重磅登场

MapDialog

这是一个基于FullScreenPopupView的全屏地图选择弹窗,因为我是做物流软件的,所以很多地方都会用到地图选择器,无论是地图选点还是三级联动选择地址,如果你单独另起一个界面的话,数据回传还有复用等功能处理起来都很麻烦,这时候就轮到弹窗登场了。将地图选择器封装成一个弹窗的话,不仅能降低成本,在处理回传数据的时候利用回调,还不是想怎么样就怎么样!使用起来也不用每次新开一个界面了,只需new 一个弹窗就好啦,还不是美滋滋。

只不过美中不足的就是,这个弹窗不能在一级页面,也就是app启动之后进入的首页使用,不然的话,在用户使用手势返回的时候,很容易导致退出app。还有一点就是它消失的动画是从上往下消失的,这一点我暂时还没做改动。好了,废话不多说,上代码:

R.layout.dialog_map

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:background="@color/red"/>

    <include layout="@layout/toolbar" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:background="@color/white"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/et_search_city_poi"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="15dp"
            android:layout_marginTop="8dp"
            android:layout_marginRight="15dp"
            android:layout_marginBottom="8dp"
            android:layout_weight="1"
            android:background="#FFF6F6F6"
            android:drawableLeft="@drawable/search"
            android:drawablePadding="11dp"
            android:ellipsize="end"
            android:hint="请输入网点地址"
            android:paddingLeft="10dp"
            android:singleLine="true"
            android:textColor="@color/normal_text"
            android:textColorHint="#FFC2C2C2"
            android:textSize="14sp" />

        <TextView
            android:id="@+id/tv_ensure_commit_btn"
            style="@style/style_tv_no_font_padding"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginTop="8dp"
            android:layout_marginRight="15dp"
            android:layout_marginBottom="8dp"
            android:background="@drawable/shaper_radius5_red_bg"
            android:gravity="center"
            android:paddingLeft="8dp"
            android:paddingRight="8dp"
            android:text="确认"
            android:textColor="@color/white"
            android:textSize="14sp" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_map_and_poi_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="gone">

        <com.amap.api.maps.MapView
            android:id="@+id/mv_branch_address_choose"
            android:layout_width="match_parent"
            android:layout_height="250dp" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv_branch_address_choose"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/white" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_search_place"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv_search_by_input_text"
            android:layout_width="match_parent"
            android:background="@color/white"
            android:layout_height="match_parent" />
    </LinearLayout>

</LinearLayout>

MapDialog

import android.content.Context;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.basic.lattercore.activities.BaseActivity;
import com.basic.lattercore.app.Suns;
import com.basic.lattercore.util.SunsToastUtils;
import com.basic.lattercore.util.click.AntiShakeUtils;
import com.basic.lattercore.util.event.EventBusUtils;
import com.basic.lattercore.util.event.EventMessage;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.appbar.MaterialToolbar;
import com.lxj.xpopup.impl.FullScreenPopupView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import cn.sunsapp.owner.EventCode;
import cn.sunsapp.owner.R;
import cn.sunsapp.owner.adapter.PoiListAdapter;
import cn.sunsapp.owner.adapter.SearchPlaceListAdapter;


public class MapDialog extends FullScreenPopupView {

    private EditText etSearchCityPoi;
    private TextView tvEnsureCommitBtn;
    private LinearLayout llMapAndPoiList;
    private LinearLayout llSearchPlace;
    private MapView mapView;
    private RecyclerView rvSearchByInputText;
    private RecyclerView rvBranchAddressChoose;

    private AMap aMap = null;

    // 定位adapter
    private PoiListAdapter poiListAdapter;

    private SearchPlaceListAdapter searchAdapter;

    private Double mLat = 0.0;

    private Double mLng = 0.0;

    private WeakHashMap<String, Object> eventMap = new WeakHashMap<>();


    public MapDialog(@NonNull Context context) {
        super(context);
    }

    public MapDialog(@NonNull Context context, Double lat, Double lng) {
        super(context);
        this.mLat = lat;
        this.mLng = lng;

    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.dialog_map;
    }

    @Override
    protected void onCreate() {
        super.onCreate();

        // id绑定
        bindView();

        // 初始化recycleview
        initView();

        // 输入框字符变化
        searchRange();

        // 初始化mapview
        initMap(new Bundle());

        // 确认按钮
        clickEnsure();

        KeyboardUtils.hideSoftInput(this);
    }

    private void bindView() {
        TextView toolbarTitle = (TextView) findViewById(R.id.toolbar_title);
        MaterialToolbar toolbar = (MaterialToolbar) findViewById(R.id.toolbar);

        toolbarTitle.setText("地图选择");

        toolbar.setNavigationIcon(com.basic.core.R.drawable.icon_back_white);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MapDialog.this.dismiss();
            }
        });

        etSearchCityPoi = (EditText) findViewById(R.id.et_search_city_poi);
        tvEnsureCommitBtn = (TextView) findViewById(R.id.tv_ensure_commit_btn);
        llMapAndPoiList = (LinearLayout) findViewById(R.id.ll_map_and_poi_list);
        llSearchPlace = (LinearLayout) findViewById(R.id.ll_search_place);
        mapView = (MapView) findViewById(R.id.mv_branch_address_choose);
        rvSearchByInputText = (RecyclerView) findViewById(R.id.rv_search_by_input_text);
        rvBranchAddressChoose = (RecyclerView) findViewById(R.id.rv_branch_address_choose);


        // 进入页面时隐藏搜索recycleview,显示地图和对应的poi recycleview
        llMapAndPoiList.setVisibility(View.VISIBLE);
        llSearchPlace.setVisibility(View.GONE);
    }

    /**
     * 实例化mapview,显示地图
     *
     * @param savedInstanceState
     */
    private void initMap(Bundle savedInstanceState) {

        mapView = (MapView) findViewById(R.id.mv_branch_address_choose);
        mapView.onCreate(savedInstanceState);

        if (aMap == null) {
            aMap = mapView.getMap();
        }
        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点,定位点依照设备方向旋转,并且会跟随设备移动。(1秒1次定位)如果不设置myLocationType,默认也会执行此种模式。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
        myLocationStyle.showMyLocation(false);
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));

        mapView.getMap().setMyLocationEnabled(true);
        mapView.getMap().setMyLocationStyle(myLocationStyle);
        mapView.getMap().getUiSettings().setMyLocationButtonEnabled(true);
        mapView.getMap().getUiSettings().setZoomControlsEnabled(false);
        mapView.getMap().getUiSettings().setScaleControlsEnabled(true);//显示比例尺
        mapView.getMap().getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);//设置地图logo的显示位置为右下角(隐藏不了)
        mapView.getMap().moveCamera(CameraUpdateFactory.zoomTo(18f));

        mapView.getMap().setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                if (location == null) {
                    return;
                }
                Marker marker;
                MarkerOptions markerOptions;
                markerOptions = new MarkerOptions();
                marker = mapView.getMap().addMarker(markerOptions);

                int width = mapView.getRight() / 2;
                int height = mapView.getBottom() / 2;
                marker.setPositionByPixels(width, height);

                LatLng latLng = null;
                if (mLat == 0.0) {
                    latLng = new LatLng(location.getLatitude(), location.getLongitude());
                } else {
                    latLng = new LatLng(Double.valueOf(mLat), Double.valueOf(mLng));
                }
                moveCameraUpdate(mapView, latLng, 18f);
                mapView.getMap().setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
                    @Override
                    public void onCameraChange(CameraPosition cameraPosition) {

                    }

                    @Override
                    public void onCameraChangeFinish(CameraPosition cameraPosition) {
                        if (cameraPosition == null) {
                            return;
                        }
                        LatLng target = cameraPosition.target;
                        getCircumInfo(getContext(), target.latitude, target.longitude);

                    }
                });
            }
        });
    }

    /**
     * 搜索功能:在edittext中字符串发生变化的时候,自动提示相对应的poi信息,并显示在对应的recycleview上
     */
    private void searchRange() {
        etSearchCityPoi.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                llMapAndPoiList.setVisibility(View.GONE);
                llSearchPlace.setVisibility(View.VISIBLE);

                //第二个参数传入null或者“”代表在全国进行检索,否则按照传入的city进行检索
                InputtipsQuery inputquery = new InputtipsQuery(s.toString(), "");
                inputquery.setCityLimit(true);//限制在当前城市
                Inputtips inputTips = new Inputtips(getContext(), inputquery);
                inputTips.setInputtipsListener(new Inputtips.InputtipsListener() {
                    @Override
                    public void onGetInputtips(List<Tip> list, int i) {

                        searchAdapter.setNewData(list);
                    }
                });
                inputTips.requestInputtipsAsyn();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


    }

    /**
     * mapview下面的recycleview实例化和数据的显示和对应的item点击事件
     */
    private void initView() {
        rvBranchAddressChoose.setLayoutManager(new LinearLayoutManager(getContext()));
        poiListAdapter = new PoiListAdapter(R.layout.item_branch_poi_list);
        poiListAdapter.bindToRecyclerView(rvBranchAddressChoose);
        poiListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //防抖
                if (AntiShakeUtils.isInvalidClick(view)) {

                    return;
                }

                poiListAdapter.changeCheckedPositon(poiListAdapter.getItem(position).getTitle());
                rvBranchAddressChoose.scrollToPosition(0);


                double latlonPointLat = poiListAdapter.getItem(position).getLatLonPoint().getLatitude();
                double latlngPointLng = poiListAdapter.getItem(position).getLatLonPoint().getLongitude();
                LatLng latLngPoint = new LatLng(latlonPointLat, latlngPointLng);
                moveCameraUpdate(mapView, latLngPoint, 18f);

                eventMap = new WeakHashMap<>();

                eventMap.put("prov", poiListAdapter.getItem(position).getProvinceName());
                eventMap.put("city", poiListAdapter.getItem(position).getCityName());
                eventMap.put("county", poiListAdapter.getItem(position).getAdName());
                eventMap.put("detail", poiListAdapter.getItem(position).getSnippet());
                eventMap.put("lat", poiListAdapter.getItem(position).getLatLonPoint().getLatitude());
                eventMap.put("lng", poiListAdapter.getItem(position).getLatLonPoint().getLongitude());
            }
        });


        rvSearchByInputText.setLayoutManager(new LinearLayoutManager(getContext()));
        searchAdapter = new SearchPlaceListAdapter(R.layout.item_branch_poi_list);
        searchAdapter.bindToRecyclerView(rvSearchByInputText);
        searchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //防抖
                if (AntiShakeUtils.isInvalidClick(view)) {

                    return;
                }

                double selectLat;
                double selectLng;

                if (searchAdapter.getItem(position).getPoint() == null || "".equals(searchAdapter.getItem(position).getPoint())) {
                    SunsToastUtils.showCenterShortToast("获取不到该点的经纬度,请重新选择");
                    return;
                } else {
                    selectLat = searchAdapter.getItem(position).getPoint().getLatitude();
                    selectLng = searchAdapter.getItem(position).getPoint().getLongitude();

                    LatLng selectPoint = new LatLng(selectLat, selectLng);
                    moveCameraUpdate(mapView, selectPoint, 18f);
                    getCircumInfo(getContext(), selectLat, selectLng);
                    llMapAndPoiList.setVisibility(View.VISIBLE);
                    llSearchPlace.setVisibility(View.GONE);

                    eventMap = new WeakHashMap<>();
                    eventMap.put("detail", searchAdapter.getItem(position).getAddress());
                    eventMap.put("lat", searchAdapter.getItem(position).getPoint().getLatitude());
                    eventMap.put("lng", searchAdapter.getItem(position).getPoint().getLongitude());
                    getDetailByTip(getContext(), searchAdapter.getItem(position).getDistrict(), searchAdapter.getItem(position).getAdcode());
                    KeyboardUtils.hideSoftInput(MapDialog.this);
                }
            }

        });

    }

    /**
     * 根据tip返回的详细地址获取具体的省市县名称
     * @param context
     * @param address
     * @param adCode
     */
    private void getDetailByTip(Context context, String address, String adCode) {
        GeocodeSearch geocoderSearch = new GeocodeSearch(context);

        // name表示地址,第二个参数表示查询城市,中文或者中文全拼,citycode、adcode
        GeocodeQuery query = new GeocodeQuery(address, adCode);

        geocoderSearch.getFromLocationNameAsyn(query);

        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
                if (i == 1000) {
                    eventMap.put("prov", geocodeResult.getGeocodeAddressList().get(0).getProvince());
                    eventMap.put("city", geocodeResult.getGeocodeAddressList().get(0).getCity());
                    eventMap.put("county", geocodeResult.getGeocodeAddressList().get(0).getDistrict());

                }
            }
        });
    }

    /**
     * 点击获取到的联想数据poi item时,地图中心点蓝点移动到对应的位置
     *
     * @param mv
     * @param ll
     * @param zoom
     */
    private void moveCameraUpdate(MapView mv, LatLng ll, Float zoom) {
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(ll, zoom);
        mv.getMap().animateCamera(cameraUpdate);
    }

    @Override
    protected void onDismiss() {
        super.onDismiss();
        mapView.onDestroy();
    }


    /**
     * 根据传入的经纬度,获取相对应的poi联想数据
     *
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onGetMessage(EventMessage message) {
        switch (message.getCode()) {
            case EventCode.BRANCH_ADDRESS_LOCATION_POI:

                EventBusUtils.removeSticky(message);
                break;
        }

    }

    /**
     * 根据经纬度获取周边的地址列表
     *
     * @param context
     * @param lat
     * @param lng
     */
    private void getCircumInfo(Context context, Double lat, Double lng) {
        PoiSearch.Query query = new PoiSearch.Query("", "", "");
        query.setPageSize(100);// 设置每页返回多少条数据
        query.setPageNum(1);// 设置查询页码

        PoiSearch poiSearch = new PoiSearch(context, query);

        poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(lat, lng), 1000));
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int i) {
                if (i != 1000) {
                    SunsToastUtils.showCenterShortToast("无法查询周边信息" + i);
                } else {
                    if (poiResult != null) {
                        poiListAdapter.setNewData(poiResult.getPois());
                    }
                }
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {

            }
        });
        poiSearch.searchPOIAsyn();
    }

    private OnConfirmListener mListener = null;

    public MapDialog setOnConfirmListener(OnConfirmListener listener) {
        mListener = listener;
        return this;
    }

    public interface OnConfirmListener {
        void onConfirm(WeakHashMap map);
    }


    /**
     * 点击确认带参返回
     */
    private void clickEnsure() {
        tvEnsureCommitBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AntiShakeUtils.isInvalidClick(v)) {
                    return;
                }
                dismiss();
                if (mListener != null) {
                    dismiss();
                    if (!eventMap.isEmpty()) {
                        mListener.onConfirm(eventMap);

                    }
                }
                KeyboardUtils.hideSoftInput(MapDialog.this);
            }
        });
    }
}

使用方法的话就跟之前的CenterPopupView一样使用就好了,有啥不懂得,或者我代码哪里有问题,或者你觉得哪里我还可以优化的,热烈欢迎在评论区留言啊,谢谢您嘞。那么,这期就到这,告辞!

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45065275/article/details/106441714