关于Android一个画了6个小时的Dialog

前言

这是设计稿

OK,拿到设计稿的时候。我是轻蔑一笑的,这算什么难度....分分钟就可以搞掂了,不就是一个dialog,里面我放上一个viewpager,viewpager里面我再放上一个RecyclerView,顶了天我需要写2个适配器,半小时就可以搞掂!!

OK,开撸,Dialog自定义出来,放ViewPager,写FragmentPagerAdapter适配器,丢进去RecyclerView,再写一个RecyclerView适配器。

OK, 跑项目...焦急的等待以及电脑风扇的疯狂躁动中...跑起来了,点击一看!纳尼,我的RecyclerView呢???跑哪里了???!!!!

地狱

第一次跑完失败...代码有问题!再修改!!!

下面是让我一直很苦恼的一个bug:

适配器布局文件
适配器加载文件

然而报的错误---->

报错

看到这里我是懵逼的! 我在Dialog的layout文件里面找控件,然而你给你索引到了子Fragment里面去找!为啥!??

划重点 : 要使用getchildfragmentmanager()而不是getsupportfragmentmanager()

ok,改完后不报错了...
然而没卵用...我的viewpager彻底跟我分手了,我可以改viewpager的颜色,可以改viewpager的LayoutParams,但是我就是找不到里面的子Fragment....彻彻底底,跟我分手了。

方法(失败的)

ok,dialog我们用不了的,AlertDialog我们也是没办法使用的...那我们用什么,是不是有人说用popwindow,呵呵...用那个更麻烦。我们用FragmentDialog,这个东西其实我没有用过。

介绍!

该方法需要我们实现一个默认的构造函数,把我们的dailog从本质上变成了Fragment。


/**
 * Created by Ly on 2017/4/21.
 * 送礼的dialog
 */

public class GiftDialog extends DialogFragment implements PagingScrollHelper.onPageChangeListener {
    public GiftDialog() {
    }

    public static GiftDialog newInstance() {
        Bundle args = new Bundle();
        GiftDialog fragment = new GiftDialog();
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 礼物列表
     */
    private RecyclerView recyclerViewText;
    /**
     * viewpager的指示器
     */
    private LinearLayout llGiftIndicator;
    /**
     * 账户余额
     */
    private TextView tvGiftBalance;
    /**
     * 发送
     */
    private CardView cvGiftSend;

    protected Dialog dialog;
    /**
     * 加载的适配器
     */
    private GiftListAdapter giftListAdapter;

    /**
     * 滑动监听控制器
     */
    PagingScrollHelper scrollHelper = new PagingScrollHelper();
    /**
     * 配置常量  使用2行4列的方式进行布局
     */
    private static final int ROWS = 2, COLUMNS = 4;
    /**
     * 就是一个标志位,我想写“The most handsome LingYu”
     * 但是想想还是不要那么骚包好了
     */
    private static final String TAG = "BottomDialogFragment";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return LayoutInflater.from(getActivity()).inflate(R.layout.bottom_anim_dialog_layout, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }


    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.dialog);
        View view = View.inflate(getActivity(), R.layout.bottom_anim_dialog_layout, null);
        builder.setView(view);
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);
        // 设置宽度为屏宽、靠近屏幕底部。
        Window window = dialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.BOTTOM;
        //设置没有效果
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(wlp);
        initView(view);
        return dialog;
    }

    private void initView(View view) {
        recyclerViewText = (RecyclerView) view.findViewById(R.id.rlv_gift_list);
        llGiftIndicator = (LinearLayout) view.findViewById(R.id.ll_gift_indicator);
        recyclerViewText.setLayoutManager(new HorizontalPageLayoutManager(ROWS, COLUMNS));
        giftListAdapter = new GiftListAdapter(getActivity());
        recyclerViewText.setAdapter(giftListAdapter);
        giftListAdapter.setRecItemClick(new RecyclerItemCallback<String, GiftListAdapter.GiftListViewHolder>() {
            @Override
            public void onItemClick(int position, String model, int tag, GiftListAdapter.GiftListViewHolder holder) {
                super.onItemClick(position, model, tag, holder);
                Toast.makeText(getActivity(), position + "", Toast.LENGTH_SHORT).show();
            }
        });
        scrollHelper.setUpRecycleView(recyclerViewText);
        scrollHelper.setOnPageChangeListener(this);
        for (int i = 0; i < 2; i++) {
            ImageView imageView = new ImageView(getActivity());
            LinearLayout.LayoutParams layoutParams =
                    new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(DeviceUtils.px2dip(getActivity(), 12),
                    DeviceUtils.px2dip(getActivity(), 2),
                    DeviceUtils.px2dip(getActivity(), 12),
                    DeviceUtils.px2dip(getActivity(), 2));
            imageView.setLayoutParams(layoutParams);
            if (i == 0) {
                imageView.setImageResource(R.mipmap.live_gift_in_red);
            } else {
                imageView.setImageResource(live_gift_noin_gray);
            }
            llGiftIndicator.addView(imageView);
        }
    }

    /**
     * 更新状态
     *
     * @param position
     */
    private void updateIndicator(int position) {
        if (position < 0 || position > llGiftIndicator.getChildCount()) {
            return;
        } else {
            for (int i = 0; i < llGiftIndicator.getChildCount(); i++) {
                ((ImageView) llGiftIndicator.getChildAt(i)).setImageResource(R.mipmap.live_gift_noin_gray);
            }
            ((ImageView) llGiftIndicator.getChildAt(position)).setImageResource(R.mipmap.live_gift_in_red);
        }
    }

    //防止重复弹出
    public static GiftDialog showDialog(AppCompatActivity appCompatActivity) {
        FragmentManager fragmentManager = appCompatActivity.getSupportFragmentManager();
        GiftDialog bottomDialogFragment =
                (GiftDialog) fragmentManager.findFragmentByTag(TAG);
        if (null == bottomDialogFragment) {
            bottomDialogFragment = newInstance();
        }

        if (!appCompatActivity.isFinishing()
                && null != bottomDialogFragment
                && !bottomDialogFragment.isAdded()) {
            fragmentManager.beginTransaction()
                    .add(bottomDialogFragment, TAG)
                    .commitAllowingStateLoss();
        }
        return bottomDialogFragment;
    }

    @Override
    public void onPageChange(int index) {
        updateIndicator(index);
    }
}



如果是按照我一开始的思路来实现的话,是无法实现的,依然会出现ViewPager无法显示子内容的bug。好吧,索性心一横,我们把ViewPager,砍掉!!!!直接使用RecyclerView。
由此布局文件变成了:

<?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"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white_font_color"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rlv_gift_list"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:scrollbars="none" />

    <LinearLayout
        android:id="@+id/ll_gift_indicator"
        android:layout_width="match_parent"
        android:layout_height="25dp"
        android:gravity="center"
        android:orientation="horizontal">

    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/title_bar">

        <TextView
            android:id="@+id/tv_gift_balance"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="@dimen/margin_16dp"
            android:drawableLeft="@mipmap/live_gift_dodo"
            android:drawablePadding="@dimen/padding_10dp"
            android:drawableRight="@mipmap/live_gift_next"
            android:gravity="center"
            android:text="15"
            android:textColor="@color/orange_font_color"
            android:textSize="@dimen/text_size_14sp" />

        <android.support.v7.widget.CardView
            android:id="@+id/cv_gift_send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="@dimen/margin_26dp"
            app:cardCornerRadius="10px"
            app:cardElevation="5dp">

            <TextView
                android:layout_width="75dp"
                android:layout_height="30dp"
                android:background="@drawable/fillet_red_bg"
                android:gravity="center"
                android:text="@string/text_gift"
                android:textColor="@color/white_font_color"
                android:textSize="@dimen/text_size_14sp" />
        </android.support.v7.widget.CardView>
    </RelativeLayout>
</LinearLayout>

那有人问了,RecyclerView如何做为ViewPager,答案是,我们可以自定义LayoutManager,如下:


/**
 * Created by Ly on 2017/4/22.
 */

public class HorizontalPageLayoutManager extends RecyclerView.LayoutManager implements PageDecorationLastJudge {
    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return null;
    }

    int totalHeight = 0;
    int totalWidth = 0;
    int offsetY = 0;
    int offsetX = 0;

    public HorizontalPageLayoutManager(int rows, int columns) {
        this.rows = rows;
        this.columns = columns;
        this.onePageSize = rows * columns;
    }

    @Override
    public boolean canScrollHorizontally() {
        return true;
    }




    @Override
    public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
        detachAndScrapAttachedViews(recycler);
        int newX = offsetX + dx;
        int result = dx;
        if (newX > totalWidth) {
            result = totalWidth - offsetX;
        } else if (newX < 0) {
            result = 0 - offsetX;
        }
        offsetX += result;
        offsetChildrenHorizontal(-result);
        recycleAndFillItems(recycler, state);
        return result;
    }

    private SparseArray<Rect> allItemFrames = new SparseArray<>();

    private int getUsableWidth() {
        return getWidth() - getPaddingLeft() - getPaddingRight();
    }

    private int getUsableHeight() {
        return getHeight() - getPaddingTop() - getPaddingBottom();
    }

    int rows = 0;
    int columns = 0;
    int pageSize = 0;
    int itemWidth = 0;
    int itemHeight = 0;
    int onePageSize = 0;
    int itemWidthUsed;
    int itemHeightUsed;


    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {

        if (getItemCount() == 0) {
            removeAndRecycleAllViews(recycler);
            return;
        }
        if (state.isPreLayout()) {
            return;
        }
        //获取每个Item的平均宽高
        itemWidth = getUsableWidth() / columns;
        itemHeight = getUsableHeight() / rows;

        //计算宽高已经使用的量,主要用于后期测量
        itemWidthUsed = (columns - 1) * itemWidth;
        itemHeightUsed = (rows - 1) * itemHeight;

        //计算总的页数
        pageSize = getItemCount() / onePageSize + (getItemCount() % onePageSize == 0 ? 0 : 1);

        //计算可以横向滚动的最大值
        totalWidth = (pageSize - 1) * getWidth();

        //分离view
        detachAndScrapAttachedViews(recycler);

        int count = getItemCount();
        for (int p = 0; p < pageSize; p++) {
            for (int r = 0; r < rows; r++) {
                for (int c = 0; c < columns; c++) {
                    int index = p * onePageSize + r * columns + c;
                    if (index == count) {
                        //跳出多重循环
                        c = columns;
                        r = rows;
                        p = pageSize;
                        break;
                    }

                    View view = recycler.getViewForPosition(index);
                    addView(view);
                    //测量item
                    measureChildWithMargins(view, itemWidthUsed, itemHeightUsed);

                    int width = getDecoratedMeasuredWidth(view);
                    int height = getDecoratedMeasuredHeight(view);
                    //记录显示范围
                    Rect rect = allItemFrames.get(index);
                    if (rect == null) {
                        rect = new Rect();
                    }
                    int x = p * getUsableWidth() + c * itemWidth;
                    int y = r * itemHeight;
                    rect.set(x, y, width + x, height + y);
                    allItemFrames.put(index, rect);


                }
            }
            //每一页循环以后就回收一页的View用于下一页的使用
            removeAndRecycleAllViews(recycler);
        }

        recycleAndFillItems(recycler, state);
    }

    @Override
    public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) {
        super.onDetachedFromWindow(view, recycler);
        offsetX = 0;
        offsetY = 0;
    }

    private void recycleAndFillItems(RecyclerView.Recycler recycler, RecyclerView.State state) {
        if (state.isPreLayout()) {
            return;
        }

        Rect displayRect = new Rect(getPaddingLeft() + offsetX, getPaddingTop(), getWidth() - getPaddingLeft() - getPaddingRight() + offsetX, getHeight() - getPaddingTop() - getPaddingBottom());
        Rect childRect = new Rect();
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            childRect.left = getDecoratedLeft(child);
            childRect.top = getDecoratedTop(child);
            childRect.right = getDecoratedRight(child);
            childRect.bottom = getDecoratedBottom(child);
            if (!Rect.intersects(displayRect, childRect)) {
                removeAndRecycleView(child, recycler);
            }
        }

        for (int i = 0; i < getItemCount(); i++) {
            if (Rect.intersects(displayRect, allItemFrames.get(i))) {
                View view = recycler.getViewForPosition(i);
                addView(view);
                measureChildWithMargins(view, itemWidthUsed, itemHeightUsed);
                Rect rect = allItemFrames.get(i);
                layoutDecorated(view, rect.left - offsetX, rect.top, rect.right - offsetX, rect.bottom);
            }
        }

    }


    @Override
    public boolean isLastRow(int index) {
        if (index >= 0 && index < getItemCount()) {
            int indexOfPage = index % onePageSize;
            indexOfPage++;
            if (indexOfPage > (rows - 1) * columns && indexOfPage <= onePageSize) {
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean isLastColumn(int position) {
        if (position >= 0 && position < getItemCount()) {
            position++;
            if (position % columns == 0) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean isPageLast(int position) {
        position++;
        return position % onePageSize == 0;
    }
}

那又有人问了,我们如何监听页面滑动,进而更新指示器?

**
 * 实现RecycleView分页滚动的工具类
 * Created by Ly on 2017/4/22.
 */

public class PagingScrollHelper {

    RecyclerView mRecyclerView = null;

    private MyOnScrollListener mOnScrollListener = new MyOnScrollListener();

    private MyOnFlingListener mOnFlingListener = new MyOnFlingListener();
    private int offsetY = 0;
    private int offsetX = 0;

    int startY = 0;
    int startX = 0;


    enum ORIENTATION {
        HORIZONTAL, VERTICAL, NULL
    }

    ORIENTATION mOrientation = ORIENTATION.HORIZONTAL;

    public void setUpRecycleView(RecyclerView recycleView) {
        if (recycleView == null) {
            throw new IllegalArgumentException("recycleView must be not null");
        }
        mRecyclerView = recycleView;
        //处理滑动
        recycleView.setOnFlingListener(mOnFlingListener);
        //设置滚动监听,记录滚动的状态,和总的偏移量
        recycleView.setOnScrollListener(mOnScrollListener);
        //记录滚动开始的位置
        recycleView.setOnTouchListener(mOnTouchListener);
        //获取滚动的方向
        updateLayoutManger();
    }

    public void updateLayoutManger() {
        RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager();
        if (layoutManager != null) {
            if (layoutManager.canScrollVertically()) {
                mOrientation = ORIENTATION.VERTICAL;
            } else if (layoutManager.canScrollHorizontally()) {
                mOrientation = ORIENTATION.HORIZONTAL;
            } else {
                mOrientation = ORIENTATION.NULL;
            }
            if (mAnimator != null) {
                mAnimator.cancel();
            }
            startX = 0;
            startY = 0;
            offsetX = 0;
            offsetY = 0;

        }

    }

    ValueAnimator mAnimator = null;

    public class MyOnFlingListener extends RecyclerView.OnFlingListener {

        @Override
        public boolean onFling(int velocityX, int velocityY) {
            if (mOrientation == ORIENTATION.NULL) {
                return false;
            }
            //获取开始滚动时所在页面的index
            int p = getStartPageIndex();

            //记录滚动开始和结束的位置
            int endPoint = 0;
            int startPoint = 0;

            //如果是垂直方向
            if (mOrientation == ORIENTATION.VERTICAL) {
                startPoint = offsetY;

                if (velocityY < 0) {
                    p--;
                } else if (velocityY > 0) {
                    p++;
                }
                //更具不同的速度判断需要滚动的方向
                //注意,此处有一个技巧,就是当速度为0的时候就滚动会开始的页面,即实现页面复位
                endPoint = p * mRecyclerView.getHeight();

            } else {
                startPoint = offsetX;
                if (velocityX < 0) {
                    p--;
                } else if (velocityX > 0) {
                    p++;
                }
                endPoint = p * mRecyclerView.getWidth();

            }
            if (endPoint < 0) {
                endPoint = 0;
            }

            //使用动画处理滚动
            if (mAnimator == null) {
                mAnimator = new ValueAnimator().ofInt(startPoint, endPoint);

                mAnimator.setDuration(300);
                mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        int nowPoint = (int) animation.getAnimatedValue();

                        if (mOrientation == ORIENTATION.VERTICAL) {
                            int dy = nowPoint - offsetY;
                            //这里通过RecyclerView的scrollBy方法实现滚动。
                            mRecyclerView.scrollBy(0, dy);
                        } else {
                            int dx = nowPoint - offsetX;
                            mRecyclerView.scrollBy(dx, 0);
                        }
                    }
                });
                mAnimator.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        //回调监听
                        if (null != mOnPageChangeListener) {
                            mOnPageChangeListener.onPageChange(getPageIndex());
                        }
                    }
                });
            } else {
                mAnimator.cancel();
                mAnimator.setIntValues(startPoint, endPoint);
            }

            mAnimator.start();

            return true;
        }
    }

    public class MyOnScrollListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            //newState==0表示滚动停止,此时需要处理回滚
            if (newState == 0 && mOrientation != ORIENTATION.NULL) {
                boolean move;
                int vX = 0, vY = 0;
                if (mOrientation == ORIENTATION.VERTICAL) {
                    int absY = Math.abs(offsetY - startY);
                    //如果滑动的距离超过屏幕的一半表示需要滑动到下一页
                    move = absY > recyclerView.getHeight() / 2;
                    vY = 0;

                    if (move) {
                        vY = offsetY - startY < 0 ? -1000 : 1000;
                    }

                } else {
                    int absX = Math.abs(offsetX - startX);
                    move = absX > recyclerView.getWidth() / 2;
                    if (move) {
                        vX = offsetX - startX < 0 ? -1000 : 1000;
                    }

                }

                mOnFlingListener.onFling(vX, vY);

            }

        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            //滚动结束记录滚动的偏移量
            offsetY += dy;
            offsetX += dx;
        }
    }

    private MyOnTouchListener mOnTouchListener = new MyOnTouchListener();


    public class MyOnTouchListener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            //手指按下的时候记录开始滚动的坐标
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                startY = offsetY;
                startX = offsetX;
            }
            return false;
        }

    }

    private int getPageIndex() {
        int p = 0;
        if (mOrientation == ORIENTATION.VERTICAL) {
            p = offsetY / mRecyclerView.getHeight();
        } else {
            p = offsetX / mRecyclerView.getWidth();
        }
        return p;
    }

    private int getStartPageIndex() {
        int p = 0;
        if (mOrientation == ORIENTATION.VERTICAL) {
            p = startY / mRecyclerView.getHeight();
        } else {
            p = startX / mRecyclerView.getWidth();
        }
        return p;
    }

    onPageChangeListener mOnPageChangeListener;

    public void setOnPageChangeListener(onPageChangeListener listener) {
        mOnPageChangeListener = listener;
    }

    public interface onPageChangeListener {
        void onPageChange(int index);
    }

}


一个小问题折腾了我快半天!妈的到了快4点还没得睡!!!由此可见基础是多么重要!!!!妈的,恶补回来了必须。

贴上github地址:https://github.com/LinHuanTanLy/FullDialogMaster

//********分割线,现在时间是2017年11月29日17:58:23***************************************************************************

啊哈哈哈哈哈,差点没被人打死,朋友跟我说没做点击监听...我一看,还真的是吖。赶紧补回来,不然要被人打死了。

错误的做法

这个是用得比较多的办法,没办法嘛,谁叫安卓是回调地狱呢,那必须是Callback啊:

 public interface OnItemClickListener {
        /**
         * 点击菜单项的回调事件
         *
         * @param shareMenuBean
         */
        void onMenuClickListener(ShareMenuBean shareMenuBean);
    }

在dialog类里声明callback实例:

 /**
     * 分享的菜单点击回调
     */
    private static OnItemClickListener mOnItemClickListener;

在dialog的shou方法里进行赋值:

  /**
     * 防止重复弹出 显示此dialog的唯一方法
     *
     * @param appCompatActivity
     * @return
     */
    public static ShareDialog showDialog(FragmentActivity appCompatActivity, OnItemClickListener itemClickListener) {
        mOnItemClickListener = itemClickListener;
        FragmentManager fragmentManager = appCompatActivity.getSupportFragmentManager();
        ShareDialog shareDialog =
                (ShareDialog) fragmentManager.findFragmentByTag(TAG);
        if (null == shareDialog) {
            shareDialog = newInstance();
        }
        if (!appCompatActivity.isFinishing()
                && null != shareDialog
                && !shareDialog.isAdded()) {
            fragmentManager.beginTransaction()
                    .add(shareDialog, TAG)
                    .commitAllowingStateLoss();
        }
        return shareDialog;
    }

在View的点击事件里面进行回调:

  mShareMenuAdapter.setRecItemClick(new RecyclerItemCallback<ShareMenuBean, ShareMenuAdapter.ShareMenuHolder>() {
            @Override
            public void onItemClick(int position, ShareMenuBean model, int tag, ShareMenuAdapter.ShareMenuHolder holder) {
                super.onItemClick(position, model, tag, holder);
                mOnItemClickListener.onMenuClickListener(model);
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        mTvShareCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });

以上,就可以了。在下面附上UI图以及dialog代码:
分享的底部dialog

shareDialog的代码:

package com.catplay.platform.ui.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.catplay.platform.R;
import com.catplay.platform.model.impl.ShareMenuBean;
import com.catplay.platform.ui.adapter.ShareMenuAdapter;

import java.util.ArrayList;
import java.util.List;

import cn.droidlover.xrecyclerview.RecyclerItemCallback;

/**
 * @author Ly
 * @date 2017/10/14
 * 分享的弹窗
 */

public class ShareDialog extends DialogFragment {

    /**
     * dialog
     */
    protected Dialog dialog;
    /**
     * 就是一个标志位
     */
    private static final String TAG = ShareDialog.class.getName();
    /**
     * 分享的标题
     */
    private TextView mTvShareTitle;
    /**
     * 分享的菜单
     */
    private RecyclerView mRlvShareMenu;
    /**
     * 分享取消按钮
     */
    private TextView mTvShareCancel;
    /**
     * 分享的菜单的适配器
     */
    private ShareMenuAdapter mShareMenuAdapter;
    /**
     * 分享的菜单的数据源
     */
    private List<ShareMenuBean> mShareMenus = new ArrayList<>();
    /**
     * 分享的菜单点击回调
     */
    private static OnItemClickListener mOnItemClickListener;

    public ShareDialog() {

    }

    public static ShareDialog newInstance() {
        Bundle args = new Bundle();
        ShareDialog fragment = new ShareDialog();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return LayoutInflater.from(getActivity()).inflate(R.layout.diaog_share_layout, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }


    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.dialog);
        View view = View.inflate(getActivity(), R.layout.diaog_share_layout, null);
        builder.setView(view);
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);
        // 设置宽度为屏宽、靠近屏幕底部。
        Window window = dialog.getWindow();
        if (window != null && window.getDecorView() != null) {
            window.getDecorView().setPadding(0, 0, 0, 0);
            WindowManager.LayoutParams wlp = window.getAttributes();
            wlp.gravity = Gravity.BOTTOM;
            //设置没有效果
            wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
            window.setAttributes(wlp);
        } else {
            Log.e(TAG, "window是空的或者是window.getDecorView()是空的");
        }
        initView(view);
        return dialog;
    }

    /**
     * 初始化视图
     *
     * @param view
     */
    private void initView(View view) {
        mShareMenus.add(new ShareMenuBean(R.drawable.umeng_socialize_sina, getActivity().getString(R.string.text_sina)));
        mShareMenus.add(new ShareMenuBean(R.drawable.umeng_socialize_qzone, getActivity().getString(R.string.text_qzone)));
        mShareMenus.add(new ShareMenuBean(R.drawable.umeng_socialize_qq, getActivity().getString(R.string.text_qq)));
        mShareMenus.add(new ShareMenuBean(R.drawable.umeng_socialize_wechat, getActivity().getString(R.string.text_wechat)));
        mShareMenus.add(new ShareMenuBean(R.drawable.umeng_socialize_wxcircle, getActivity().getString(R.string.text_wx_circle)));
        mShareMenus.add(new ShareMenuBean(R.drawable.umeng_socialize_copyurl, getActivity().getString(R.string.text_copy)));
        mTvShareTitle = (TextView) view.findViewById(R.id.tv_share_title);
        mRlvShareMenu = (RecyclerView) view.findViewById(R.id.rlv_share_menu);
        mTvShareCancel = (TextView) view.findViewById(R.id.tv_share_cancel);
        mShareMenuAdapter = new ShareMenuAdapter(getActivity());
        mRlvShareMenu.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        mRlvShareMenu.setAdapter(mShareMenuAdapter);
        mShareMenuAdapter.addData(mShareMenus);
        mShareMenuAdapter.setRecItemClick(new RecyclerItemCallback<ShareMenuBean, ShareMenuAdapter.ShareMenuHolder>() {
            @Override
            public void onItemClick(int position, ShareMenuBean model, int tag, ShareMenuAdapter.ShareMenuHolder holder) {
                super.onItemClick(position, model, tag, holder);
                mOnItemClickListener.onMenuClickListener(model);
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        mTvShareCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
    }


    /**
     * 防止重复弹出 显示此dialog的唯一方法
     *
     * @param appCompatActivity
     * @return
     */
    public static ShareDialog showDialog(FragmentActivity appCompatActivity, OnItemClickListener itemClickListener) {
        mOnItemClickListener = itemClickListener;
        FragmentManager fragmentManager = appCompatActivity.getSupportFragmentManager();
        ShareDialog shareDialog =
                (ShareDialog) fragmentManager.findFragmentByTag(TAG);
        if (null == shareDialog) {
            shareDialog = newInstance();
        }
        if (!appCompatActivity.isFinishing()
                && null != shareDialog
                && !shareDialog.isAdded()) {
            fragmentManager.beginTransaction()
                    .add(shareDialog, TAG)
                    .commitAllowingStateLoss();
        }
        return shareDialog;
    }

    public interface OnItemClickListener {
        /**
         * 点击菜单项的回调事件
         *
         * @param shareMenuBean
         */
        void onMenuClickListener(ShareMenuBean shareMenuBean);
    }


//    eg:
// ShareDialog.showDialog(getActivity(), new ShareDialog.onItemClickListener() {
//        @Override
//        public void onMenuClickListener(ShareMenuBean shareMenuBean) {
//            showTsShort(shareMenuBean.toString());
//        }
//    });
}

使用的方法为:

 ShareDialog.showDialog(getActivity(), new ShareDialog.onItemClickListener() {
        @Override
        public void onMenuClickListener(ShareMenuBean shareMenuBean) {
            showTsShort(shareMenuBean.toString());
        }
    });

是不是写完觉得好简单啊...没意思啊...不好玩啊...之类的...然后好玩的就来了!!!

内存泄露

这特么就很尴尬了...所以这个办法其实是很不好的,抛弃之,我们找别的方案!

比较好的方案

因为上述我们的interface是static的,所以有可能会引发内存问题!而我们的dialog实质上是fragment!理论上fragment如何和dialog交互,那么我们的dialog也是可以这么做的。

  1. 宿主Activity实现dialog的interface
  2. dialog通过getActivity()并强转获取interface实例,进行事件分发。

代码如下:
获取interface实例

  final OnItemClickListener onItemClickListener= (OnItemClickListener) getActivity();

需要使用该dialog的宿主Activity需要实现对应的dialog的interface,


image.png

通过该方法,我们已经可以实现dialogFragment与Activity的无痛交流了。
代码很简单就不放了,反正重头戏也不是这个,
所以问题又有了!
如果我的dialog是在fragment里面弹出来的呢,getActivity()获取的是宿主fragment的宿主Activitty...总不能我点击个dialog,要跑到MainActivity里面去拿数据处理数据吧。

在fragment里面,除了getActivity()方法,还可以发现有其他2个,
image.png

可以拿到fragment!那是不是可以拿到宿主activity呢?

点击进入Fragment的源码,我们不难发现这个方法:

    /**
     * Return the target fragment set by {@link #setTargetFragment}.
     */
    final public Fragment getTargetFragment() {
        return mTarget;
    }

发现了mTarget,还有一个get()方法,那说明肯定还有一个set()方法,查找下我们可以找到:

 /**
     * Optional target for this fragment.  This may be used, for example,
     * if this fragment is being started by another, and when done wants to
     * give a result back to the first.  The target set here is retained
     * across instances via {@link FragmentManager#putFragment
     * FragmentManager.putFragment()}.
     *
     * @param fragment The fragment that is the target of this one.
     * @param requestCode Optional request code, for convenience if you
     * are going to call back with {@link #onActivityResult(int, int, Intent)}.
     */
    public void setTargetFragment(Fragment fragment, int requestCode) {
        mTarget = fragment;
        mTargetRequestCode = requestCode;
    }

既然mTarget是我们传进去的,那就好办了!开撸:

  /**
     * 防止重复弹出 显示此dialog的唯一方法
     *
     * @param appCompatActivity
     * @return
     */
    public RechargeDialog showDialog(Fragment tarFragment, RechargeConfBean.DataBean.PayBean payBean,
                                     ArrayList<WithDrawOptionsBean> withDrawOptionsBeanList) {
        FragmentManager fragmentManager = tarFragment.getActivity().getSupportFragmentManager();
        RechargeDialog rechargeDialog =
                (RechargeDialog) fragmentManager.findFragmentByTag(TAG);
        if (null == rechargeDialog) {
            rechargeDialog = newInstance(withDrawOptionsBeanList, payBean);
        }
        rechargeDialog.setTargetFragment(tarFragment, 1);
        if (!tarFragment.getActivity().isFinishing()
                && null != rechargeDialog
                && !rechargeDialog.isAdded()) {
            fragmentManager.beginTransaction()
                    .add(rechargeDialog, TAG)
                    .commitAllowingStateLoss();
        }
        return rechargeDialog;
    }

其中我们把CenterFragment传进去了

 rechargeDialog.setTargetFragment(tarFragment, 1);

那讲道理getTargetFragment()的时候获取到的必然是CenterFragment了吧,让它实现intefrace,看是否可以进行交互!


结果显示

结果

结果

这里已经实现了交互的逻辑了。这里贴下dialog的类代码:

/**
 * @author Ly
 * @date 2017/10/14
 * 充值的dialog
 */

public class RechargeDialog extends DialogFragment {

    /**
     * dialog
     */
    protected Dialog dialog;
    /**
     * 就是一个标志位
     */
    private static final String TAG = RechargeDialog.class.getName();


    private RadioGroup mRgRechargeType;
    private RadioButton mRbRechargeAli, mRbRechargeWechat, mRbRechargeCard;
    private RecyclerView mRlvRechargeOptions;
    private TextView mTvRechargeSubmit;


    private WithdrawOptionsAdapter mWithdrawOptionsAdapter;

    /**
     * 默认选中的金额
     */
    private String moneySelected;

    public RechargeDialog() {

    }


    public static RechargeDialog newInstance(ArrayList<WithDrawOptionsBean> withDrawOptionsBeanList,
                                             RechargeConfBean.DataBean.PayBean payBean) {
        Bundle args = new Bundle();
        args.putParcelableArrayList("extra", withDrawOptionsBeanList);
        args.putSerializable("payConf", payBean);
        RechargeDialog fragment = new RechargeDialog();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final Window window = getDialog().getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//注意此处
        window.setLayout(-1, -2);//这2行,和上面的一样,注意顺序就行;
        return LayoutInflater.from(getActivity()).inflate(R.layout.dialog_recharge_layout, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }


    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.dialog);
        View view = View.inflate(getActivity(), R.layout.dialog_recharge_layout, null);
        builder.setView(view);
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);
        // 设置宽度为屏宽、靠近屏幕底部。
        Window window = dialog.getWindow();
        if (window != null && window.getDecorView() != null) {
            window.getDecorView().setPadding(0, 0, 0, 0);
            WindowManager.LayoutParams wlp = window.getAttributes();
            wlp.gravity = Gravity.CENTER;
            //设置没有效果
            wlp.width = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(wlp);
        } else {
            Log.e(TAG, "window是空的或者是window.getDecorView()是空的");
        }
        initView(view);
        return dialog;
    }

    /**
     * 初始化视图
     *
     * @param view
     */
    private void initView(View view) {
        final OnItemClickListener onItemClickListener = (OnItemClickListener) getTargetFragment();
        mRgRechargeType = (RadioGroup) view.findViewById(R.id.rg_recharge_type);
        mRbRechargeAli = (RadioButton) view.findViewById(R.id.rb_recharge_ali);
        mRbRechargeWechat = (RadioButton) view.findViewById(R.id.rb_recharge_wechat);
        mRbRechargeCard = (RadioButton) view.findViewById(R.id.rb_recharge_card);
        mRlvRechargeOptions = (RecyclerView) view.findViewById(R.id.rlv_recharge_money);
        mTvRechargeSubmit = (TextView) view.findViewById(R.id.tv_recharge_submit);
        RechargeConfBean.DataBean.PayBean payBean = (RechargeConfBean.DataBean.PayBean) getArguments().getSerializable("payConf");
        if (TextUtils.isEmpty(payBean.getBank())) {
            mRbRechargeCard.setVisibility(View.GONE);
        }
        if (TextUtils.isEmpty(payBean.getAlipay())) {
            mRbRechargeAli.setVisibility(View.GONE);
        }
        if (TextUtils.isEmpty(payBean.getWechat())) {
            mRbRechargeWechat.setVisibility(View.GONE);
        }
        if (mRbRechargeAli.getVisibility() != View.GONE) {
            mRgRechargeType.check(R.id.rb_recharge_ali);
        }
        if (mRbRechargeAli.getVisibility() == View.GONE && mRbRechargeWechat.getVisibility() != View.GONE) {
            mRgRechargeType.check(R.id.rb_recharge_wechat);
        }
        if (mRbRechargeAli.getVisibility() == View.GONE && mRbRechargeWechat.getVisibility() == View.GONE
                && mRbRechargeCard.getVisibility() != View.GONE) {
            mRgRechargeType.check(R.id.rb_recharge_card);
        }
        mWithdrawOptionsAdapter = new WithdrawOptionsAdapter(getActivity());
        mRlvRechargeOptions.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        mRlvRechargeOptions.setAdapter(mWithdrawOptionsAdapter);
        mWithdrawOptionsAdapter.setRecItemClick(new RecyclerItemCallback<WithDrawOptionsBean, WithdrawOptionsAdapter.WithdrawOptionsViewHolder>() {
            @Override
            public void onItemClick(int position, WithDrawOptionsBean model, int tag, WithdrawOptionsAdapter.WithdrawOptionsViewHolder holder) {
                super.onItemClick(position, model, tag, holder);
                if (model != null) {
                    moneySelected = model.getRmb();
                }
                mWithdrawOptionsAdapter.doReSelect(position);
            }
        });
        mTvRechargeSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onItemClickListener != null) {
                    dismiss();
                    onItemClickListener.onMenuClickListener(moneySelected);

                }
            }
        });
        ArrayList<WithDrawOptionsBean> withDrawOptionsBeanList = getArguments().getParcelableArrayList("extra");
        if (withDrawOptionsBeanList != null && withDrawOptionsBeanList.size() > 0) {
            moneySelected = withDrawOptionsBeanList.get(0).getRmb();
        }
        mWithdrawOptionsAdapter.setData(withDrawOptionsBeanList);
    }


    /**
     * 防止重复弹出 显示此dialog的唯一方法
     *
     * @param appCompatActivity
     * @return
     */
    public RechargeDialog showDialog(Fragment tarFragment, RechargeConfBean.DataBean.PayBean payBean,
                                     ArrayList<WithDrawOptionsBean> withDrawOptionsBeanList) {
        FragmentManager fragmentManager = tarFragment.getActivity().getSupportFragmentManager();
        RechargeDialog rechargeDialog =
                (RechargeDialog) fragmentManager.findFragmentByTag(TAG);
        if (null == rechargeDialog) {
            rechargeDialog = newInstance(withDrawOptionsBeanList, payBean);
        }
        rechargeDialog.setTargetFragment(tarFragment, 1);
        if (!tarFragment.getActivity().isFinishing()
                && null != rechargeDialog
                && !rechargeDialog.isAdded()) {
            fragmentManager.beginTransaction()
                    .add(rechargeDialog, TAG)
                    .commitAllowingStateLoss();
        }
        return rechargeDialog;
    }

    public interface OnItemClickListener {
        /**
         * 提交的金额
         *
         * @param money
         */
        void onMenuClickListener(String money);
    }
}

centerfragment的代码:


/**
 * Created by Ly on 2017/10/13.
 * 个人中心页面的碎片
 *
 * @author Ly
 */

public class CenterFragment extends BaseLazyFragment<CenterPresent> implements RechargeDialog.OnItemClickListener {

    @BindView(R.id.tv_title_msg)
    TextView mTvTitleMsg;
    @BindView(R.id.iv_personal_pic)
    ImageView mIvPersonalPic;
    @BindView(R.id.tv_personal_level)
    TextView mTvPersonalLevel;
    @BindView(R.id.tv_personal_money)
    TextView mTvPersonalMoney;
    @BindView(R.id.tv_personal_raised)
    TextView mTvPersonalRaised;
    @BindView(R.id.tv_personal_phone)
    TextView mTvPersonalPhone;
    @BindView(R.id.tv_personal_withdraw)
    TextView mTvPersonalWithdraw;
    @BindView(R.id.tv_personal_recharge)
    TextView mTvPersonalRecharge;
    @BindView(R.id.tv_personal_bind)
    TextView mTvPersonalBind;
    @BindView(R.id.tv_personal_earn)
    TextView mTvPersonalEarn;
    @BindView(R.id.tv_personal_settings)
    TextView mTvPersonalSettings;
    @BindView(R.id.tv_center_login)
    TextView mTvCenterLogin;
    @BindView(R.id.ll_center_login)
    LinearLayout mLlCenterLogin;
    @BindView(R.id.ll_center_status)
    LinearLayout mLlCenterStatus;
    @BindView(R.id.ll_center_button)
    LinearLayout mLlCenterButton;
    Unbinder unbinder;
    @BindView(R.id.fake_status_bar)
    View mFakeStatusBar;


    public static CenterFragment newInstance() {
        Bundle args = new Bundle();
        CenterFragment fragment = new CenterFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mTvTitleMsg.setText(R.string.text_center);
    }


    @Override
    public void onResume() {
        super.onResume();
        getP().doUpdateUserInfo();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_center;
    }

    @Override
    public CenterPresent newP() {
        return new CenterPresent();
    }


    @OnClick({R.id.tv_personal_withdraw,
            R.id.tv_personal_recharge,
            R.id.tv_personal_bind,
            R.id.tv_personal_earn,
            R.id.tv_personal_settings,
            R.id.iv_personal_pic,
            R.id.tv_center_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_personal_withdraw:
                toWithDrawActivity();
                break;
            case R.id.tv_personal_recharge:
                getP().doGetRechargeConf();
                break;
            case R.id.tv_personal_bind:
                if (mTvPersonalBind.getText().equals(getString(R.string.text_bind))) {
                    BindPhoneActivity.toBindPhone(getActivity(), "1");
                } else {
                    BindPhoneActivity.toBindPhone(getActivity(), "2");
                }
                break;
            case R.id.tv_personal_earn:
                if (isLogin) {
                    PersonalPageActivity.toPersonalPageActivity(getActivity());
                } else {
                    toLogin();
                }
                break;
            case R.id.tv_personal_settings:
                if (isLogin) {
                    SettingsActivity.toSettingActivity(getActivity());
                } else {
                    toLogin();
                }
                break;
            case R.id.iv_personal_pic:

                break;
            case R.id.tv_center_login:
                LoginActivity.toLoginActivity(getActivity());
                break;
            default:
                break;
        }
    }

    /**
     * 去提现页面
     */
    private void toWithDrawActivity() {
        if (isPromotion) {
            WithdrawActivity.toWithdrawActivity(getActivity());
        } else {
            toApply();
        }

    }


    @Override
    protected void lazyLoad() {

    }

    /**
     * 更新用户数据
     *
     * @param loginUserBean
     */
    public void doUpdateUserInfo(LoginUserBean loginUserBean) {
        LoginUserBean.DataBean dataBean = loginUserBean.getData();
        if (dataBean != null) {
            // 已经登录
            isLogin = true;
            isPromotion = AppConf.CommConf.getPromoterFlag().equals(dataBean.getIs_promoter());
            mLlCenterButton.setVisibility(View.VISIBLE);
            mLlCenterStatus.setVisibility(View.VISIBLE);
            mLlCenterLogin.setVisibility(View.GONE);
            mTvPersonalLevel.setText(String.format(getString(R.string.text_vip_level), dataBean.getVip()));
            mTvPersonalMoney.setText(dataBean.getCat_coin());
            mTvPersonalRaised.setText(dataBean.getWithdraw());
            mTvPersonalPhone.setText(TextUtils.isEmpty(dataBean.getPhone()) ? getString(R.string.text_bind_phone_un)
                    : Kits.Regular.hidePhoneNumber(dataBean.getPhone()));
            if (TextUtils.isEmpty(dataBean.getPhone())) {
                mTvPersonalBind.setText(getString(R.string.text_bind));
            } else {
                mTvPersonalBind.setText(getString(R.string.text_unbind));
            }
        } else {
            isLogin = false;
            mLlCenterButton.setVisibility(View.GONE);
            mLlCenterStatus.setVisibility(View.GONE);
            mLlCenterLogin.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 获取充值配置成功
     *
     * @param data
     */
    public void fillRechargeConf(RechargeConfBean.DataBean data) {
        if (data != null && data.getConfig() != null) {
            ArrayList<WithDrawOptionsBean> withDrawOptionsBeanList = new ArrayList<>();
            for (int i = 0; i < data.getConfig().size(); i++) {
                RechargeConfBean.DataBean.ConfigBean configBean = data.getConfig().get(i);
                WithDrawOptionsBean withDrawOptionsBean = new WithDrawOptionsBean(configBean.getId(), String.valueOf(data.getRate() * configBean.getAmount()),
                        String.valueOf(configBean.getAmount()), i == 0);
                withDrawOptionsBeanList.add(withDrawOptionsBean);
            }
            RechargeDialog mRechargeDialog = new RechargeDialog();
            mRechargeDialog.showDialog(CenterFragment.this,data.getPay(), withDrawOptionsBeanList);
        }
    }

    @Override
    public void onMenuClickListener(String money) {
        XLog.e("money---"+money);
    }
}

另外一个

我们刚刚看到代码

 /**
     * Optional target for this fragment.  This may be used, for example,
     * if this fragment is being started by another, and when done wants to
     * give a result back to the first.  The target set here is retained
     * across instances via {@link FragmentManager#putFragment
     * FragmentManager.putFragment()}.
     *
     * @param fragment The fragment that is the target of this one.
     * @param requestCode Optional request code, for convenience if you
     * are going to call back with {@link #onActivityResult(int, int, Intent)}.
     */
    public void setTargetFragment(Fragment fragment, int requestCode) {
        mTarget = fragment;
        mTargetRequestCode = requestCode;
    }

requestCode ????
一看到这,我们应该可以马上想到另外一个方法吧* public void onActivityResult(int requestCode, int resultCode, Intent data) {}*。

所以其实我们还有另外的方式来获取交互的数据,在确认按钮的点击事件中添加代码:

 mTvRechargeSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("money", moneySelected);
                //获得目标Fragment,并将数据通过onActivityResult放入到intent中进行传值
                getTargetFragment().onActivityResult(1, Activity.RESULT_OK, intent);
                if (onItemClickListener != null) {
                    dismiss();
                    onItemClickListener.onMenuClickListener(moneySelected);

                }
            }
        });

其中主要是:

 Intent intent = new Intent();
                intent.putExtra("money", moneySelected);
                //获得目标Fragment,并将数据通过onActivityResult放入到intent中进行传值
                getTargetFragment().onActivityResult(1, Activity.RESULT_OK, intent);

把值放进去bundle,再塞进onactivityResult()方法中。

而在fragment中我们重写:

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            XLog.e(data.getStringExtra("money"));
        }
    }

而结果是:


image.png

修改后的centerfragment代码是:

/**
 * Created by Ly on 2017/10/13.
 * 个人中心页面的碎片
 *
 * @author Ly
 */

public class CenterFragment extends BaseLazyFragment<CenterPresent> implements RechargeDialog.OnItemClickListener {

    @BindView(R.id.tv_title_msg)
    TextView mTvTitleMsg;
    @BindView(R.id.iv_personal_pic)
    ImageView mIvPersonalPic;
    @BindView(R.id.tv_personal_level)
    TextView mTvPersonalLevel;
    @BindView(R.id.tv_personal_money)
    TextView mTvPersonalMoney;
    @BindView(R.id.tv_personal_raised)
    TextView mTvPersonalRaised;
    @BindView(R.id.tv_personal_phone)
    TextView mTvPersonalPhone;
    @BindView(R.id.tv_personal_withdraw)
    TextView mTvPersonalWithdraw;
    @BindView(R.id.tv_personal_recharge)
    TextView mTvPersonalRecharge;
    @BindView(R.id.tv_personal_bind)
    TextView mTvPersonalBind;
    @BindView(R.id.tv_personal_earn)
    TextView mTvPersonalEarn;
    @BindView(R.id.tv_personal_settings)
    TextView mTvPersonalSettings;
    @BindView(R.id.tv_center_login)
    TextView mTvCenterLogin;
    @BindView(R.id.ll_center_login)
    LinearLayout mLlCenterLogin;
    @BindView(R.id.ll_center_status)
    LinearLayout mLlCenterStatus;
    @BindView(R.id.ll_center_button)
    LinearLayout mLlCenterButton;
    Unbinder unbinder;
    @BindView(R.id.fake_status_bar)
    View mFakeStatusBar;


    public static CenterFragment newInstance() {
        Bundle args = new Bundle();
        CenterFragment fragment = new CenterFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mTvTitleMsg.setText(R.string.text_center);
    }


    @Override
    public void onResume() {
        super.onResume();
        getP().doUpdateUserInfo();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_center;
    }

    @Override
    public CenterPresent newP() {
        return new CenterPresent();
    }


    @OnClick({R.id.tv_personal_withdraw,
            R.id.tv_personal_recharge,
            R.id.tv_personal_bind,
            R.id.tv_personal_earn,
            R.id.tv_personal_settings,
            R.id.iv_personal_pic,
            R.id.tv_center_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_personal_withdraw:
                toWithDrawActivity();
                break;
            case R.id.tv_personal_recharge:
                getP().doGetRechargeConf();
                break;
            case R.id.tv_personal_bind:
                if (mTvPersonalBind.getText().equals(getString(R.string.text_bind))) {
                    BindPhoneActivity.toBindPhone(getActivity(), "1");
                } else {
                    BindPhoneActivity.toBindPhone(getActivity(), "2");
                }
                break;
            case R.id.tv_personal_earn:
                if (isLogin) {
                    PersonalPageActivity.toPersonalPageActivity(getActivity());
                } else {
                    toLogin();
                }
                break;
            case R.id.tv_personal_settings:
                if (isLogin) {
                    SettingsActivity.toSettingActivity(getActivity());
                } else {
                    toLogin();
                }
                break;
            case R.id.iv_personal_pic:

                break;
            case R.id.tv_center_login:
                LoginActivity.toLoginActivity(getActivity());
                break;
            default:
                break;
        }
    }

    /**
     * 去提现页面
     */
    private void toWithDrawActivity() {
        if (isPromotion) {
            WithdrawActivity.toWithdrawActivity(getActivity());
        } else {
            toApply();
        }

    }


    @Override
    protected void lazyLoad() {

    }

    /**
     * 更新用户数据
     *
     * @param loginUserBean
     */
    public void doUpdateUserInfo(LoginUserBean loginUserBean) {
        LoginUserBean.DataBean dataBean = loginUserBean.getData();
        if (dataBean != null) {
            // 已经登录
            isLogin = true;
            isPromotion = AppConf.CommConf.getPromoterFlag().equals(dataBean.getIs_promoter());
            mLlCenterButton.setVisibility(View.VISIBLE);
            mLlCenterStatus.setVisibility(View.VISIBLE);
            mLlCenterLogin.setVisibility(View.GONE);
            mTvPersonalLevel.setText(String.format(getString(R.string.text_vip_level), dataBean.getVip()));
            mTvPersonalMoney.setText(dataBean.getCat_coin());
            mTvPersonalRaised.setText(dataBean.getWithdraw());
            mTvPersonalPhone.setText(TextUtils.isEmpty(dataBean.getPhone()) ? getString(R.string.text_bind_phone_un)
                    : Kits.Regular.hidePhoneNumber(dataBean.getPhone()));
            if (TextUtils.isEmpty(dataBean.getPhone())) {
                mTvPersonalBind.setText(getString(R.string.text_bind));
            } else {
                mTvPersonalBind.setText(getString(R.string.text_unbind));
            }
        } else {
            isLogin = false;
            mLlCenterButton.setVisibility(View.GONE);
            mLlCenterStatus.setVisibility(View.GONE);
            mLlCenterLogin.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 获取充值配置成功
     *
     * @param data
     */
    public void fillRechargeConf(RechargeConfBean.DataBean data) {
        if (data != null && data.getConfig() != null) {
            ArrayList<WithDrawOptionsBean> withDrawOptionsBeanList = new ArrayList<>();
            for (int i = 0; i < data.getConfig().size(); i++) {
                RechargeConfBean.DataBean.ConfigBean configBean = data.getConfig().get(i);
                WithDrawOptionsBean withDrawOptionsBean = new WithDrawOptionsBean(configBean.getId(), String.valueOf(data.getRate() * configBean.getAmount()),
                        String.valueOf(configBean.getAmount()), i == 0);
                withDrawOptionsBeanList.add(withDrawOptionsBean);
            }
            RechargeDialog mRechargeDialog = new RechargeDialog();
            mRechargeDialog.showDialog(CenterFragment.this, data.getPay(), withDrawOptionsBeanList);
        }
    }

    @Override
    public void onMenuClickListener(String money) {
        XLog.e("money---" + money);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            XLog.e(data.getStringExtra("money"));
        }
    }
}

https://github.com/LinHuanTanLy/FullDialogMaster/blob/master/README.md
基本代码是这样的,待会整理下git发出去,如果有更好的办法或者思路,烦请告知我。

此致

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,468评论 5 473
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,620评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,427评论 0 334
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,160评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,197评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,334评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,775评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,444评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,628评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,459评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,508评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,210评论 3 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,767评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,850评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,076评论 1 258
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,627评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,196评论 2 341

推荐阅读更多精彩内容