用全屏DialogFragment代替Activity,结合ViewPager展示图片

最近在知乎上看到一篇很不错的分享,关于Fragment的一些用法和开发经验,其中提倡用全屏的DialogFragment代替Activity处理一些特殊的场景,比如用户点击item触发打开一些内容详情页,相册点击小图片时会将图片全屏放大展示…等等的这些场景都可以考虑用全屏的DialogFragment来代替Activity来代替进行视图的展示。

由于具体的代码逻辑非常简单,我就直接上代码了,注释也写得很清楚,你肯定能看懂:

public class FullScreenDlgFragment extends DialogFragment implements View.OnClickListener{
    private int mClickItem;//对应显示ViewPager子项的位置
    private List<String> mListImgUrls;
    private ViewPager mViewPager;
    private Integer[] mImgIds;//本地图片资源ID
    private Dialog mDialog;
    public static final String TAG_NAME=AlertDlgFragment.class.getName();
    private Context mContext;

    //即学即用的工厂方法
    public static FullScreenDlgFragment newInstance(Context context, Integer[] imgIds, int clickItem) {
        Bundle args = new Bundle();
        FullScreenDlgFragment fragment = new FullScreenDlgFragment();
        fragment.setArguments(args);
        fragment.mContext = context;
        fragment.mImgIds = imgIds;
        fragment.mClickItem = clickItem;
        return fragment;
    }

      //由ViewPager来响应点击
    @Override
    public void onClick(View v) {
        this.dismiss();
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        //设置Dialog样式
        setStyle(DialogFragment.STYLE_NORMAL, R.style.CustomDialog_fill);
        mDialog=new Dialog(mContext);
        //去标题栏
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        initView();
        return mDialog;
    }

    private void initView() {
        //将Dialog设置全屏!!!
        setDlgParams();

        mViewPager = new ViewPager(mContext);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        mViewPager.setLayoutParams(params);
        mViewPager.setBackgroundColor(0xFF000000);
        initViewPager();
        mDialog.setContentView(mViewPager);
    }

    private void setDlgParams() {
        ViewGroup.LayoutParams lay = mDialog.getWindow().getAttributes();
        DisplayMetrics dm = new DisplayMetrics();
        mDialog.getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);
        Rect rect = new Rect();
        View view = mDialog.getWindow().getDecorView();
        view.getWindowVisibleDisplayFrame(rect);
        lay.height = dm.heightPixels - rect.top;
        lay.width = dm.widthPixels;
    }

    private void initViewPager() {
        if (mImgIds != null && mImgIds.length > 0) {
            List<View> listImgs = new ArrayList<>();
            for (int i = 0; i < mImgIds.length; i++) {
                ImageView iv = new ImageView(mContext);
                ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                iv.setLayoutParams(params);
                listImgs.add(iv);
                iv.setOnClickListener(this);
                iv.setImageResource(mImgIds[i]);
                // 加载网络图片
                // BitmapHelper.getInstance(mContext).display(iv,
                // mListImgUrls.get(i));
            }
            if (listImgs.size() > 0) {
                MyPagerAdapter pageAdapter = new MyPagerAdapter(listImgs);
                mViewPager.setAdapter(pageAdapter);
                mViewPager.setCurrentItem(mClickItem);
            }
        }
    }
}

styles.xml

<style name="CustomDialog_fill" parent="Theme.AppCompat.Dialog">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowFrame">@null</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:backgroundDimEnabled">false</item>
    <item name="android:windowBackground">@android:color/white</item>
</style>

具体使用只需:

FullScreenDlgFragment.newInstance(this,new Integer[]{R.mipmap.p1,R.mipmap.p2,R.mipmap.p3,R.mipmap.p4},2).show(getFragmentManager(),AlertDlgFragment.TAG_NAME);

特别鸣谢,以下两篇文章:
【干货】Dialog的高冷用法
面条在知乎上“关于 Android,用多个 activity,还是单 activity 配合 fragment?”的回答

fragment does not have a view ``` package com.yidi.livelibrary.widget.dialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; 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.hn.library.utils.AppLogger; import com.yidi.livelibrary.R; import com.yidi.livelibrary.ui.fragment.HnContributionFragment; import java.util.ArrayList; import java.util.List; /** * Menu Dialog */ public class HnContributionDialog extends DialogFragment implements View.OnClickListener { private FragmentActivity mActivity; private TextView tvLeft; private TextView tvMiddle; private TextView tvRight; private ViewPager viewPager; private String anchor_user_id; private ArrayList<Fragment> mFragments = new ArrayList<>(); public static HnContributionDialog newInstance(String anchor_user_id) { Bundle bundle = new Bundle(); bundle.putString("anchor_user_id",anchor_user_id); HnContributionDialog sDialog = new HnContributionDialog(); sDialog.setArguments(bundle); return sDialog; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mActivity = getActivity(); Bundle bundle = getArguments(); if (bundle != null) { anchor_user_id = bundle.getString("anchor_user_id"); AppLogger.e(anchor_user_id); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { View view = View.inflate(mActivity, R.layout.live_left_dialog, null); Dialog dialog = null; dialog = new Dialog(mActivity, R.style.LeftDialog); dialog.setContentView(view); dialog.setCanceledOnTouchOutside(true); Window alertWindow = dialog.getWindow(); WindowManager.LayoutParams params = alertWindow.getAttributes(); alertWindow.setGravity(Gravity.LEFT); params.height = (mActivity.getWindowManager().getDefaultDisplay().getHeight()); params.width = mActivity.getWindowManager().getDefaultDisplay().getWidth(); alertWindow.setAttributes(params); dialog.getWindow().setDimAmount(0f); //初始化组件 initView(view); return dialog; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } /** * 初始化视图 * * @param view */ private void initView(View view) { tvLeft = (TextView) view.findViewById(R.id.tvLeft); tvMiddle = (TextView) view.findViewById(R.id.tvMiddle); tvRight = (TextView) view.findViewById(R.id.tvRight); viewPager = (ViewPager) view.findViewById(R.id.vp); view.findViewById(R.id.vOut).setOnClickListener(this); tvLeft.setSelected(true); tvLeft.setOnClickListener(this); tvMiddle.setOnClickListener(this); tvRight.setOnClickListener(this); viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { switch (position) { case 0: tvLeft.setSelected(true); tvMiddle.setSelected(false); tvRight.setSelected(false); break; case 1: tvLeft.setSelected(false); tvMiddle.setSelected(true); tvRight.setSelected(false); break; case 2: tvLeft.setSelected(false); tvMiddle.setSelected(false); tvRight.setSelected(true); break; default: break; } } @Override public void onPageScrollStateChanged(int state) { } }); mFragments.add(HnContributionFragment.newInstance("day",anchor_user_id)); mFragments.add(HnContributionFragment.newInstance("week",anchor_user_id)); mFragments.add(HnContributionFragment.newInstance("all",anchor_user_id)); PagerAdapter adapter = new PagerAdapter(getFragmentManager(), mFragments); viewPager.setAdapter(adapter); } public void setViewPager(){ } class PagerAdapter extends FragmentPagerAdapter { private List<Fragment> mFragments; public PagerAdapter(FragmentManager fm, List<Fragment> mFragments) { super(fm); this.mFragments = mFragments; } @Override public int getCount() { return mFragments.size(); } @Override public CharSequence getPageTitle(int position) { return null; } @Override public Fragment getItem(int position) { Fragment fragment = mFragments.get(position); return fragment; } } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.tvLeft) { tvLeft.setSelected(true); tvMiddle.setSelected(false); tvRight.setSelected(false); } else if (id == R.id.tvMiddle) { tvLeft.setSelected(false); tvMiddle.setSelected(true); tvRight.setSelected(false); } else if (id == R.id.tvRight) { tvLeft.setSelected(false); tvMiddle.setSelected(false); tvRight.setSelected(true); } else if (id == R.id.vOut) { dismiss(); } } @Override public void onDestroy() { super.onDestroy(); } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); mActivity = null; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO: inflate a fragment view View rootView = super.onCreateView(inflater, container, savedInstanceState); return rootView; } @Override public void onDestroyView() { super.onDestroyView(); } } ```
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页