美文网首页
通用布局辅助、重力感应、通用适配器、自定义无边框Dialog

通用布局辅助、重力感应、通用适配器、自定义无边框Dialog

作者: 名字不想带英文 | 来源:发表于2020-03-28 16:32 被阅读0次

    纯粹记录
    1.TopHelper:通用布局可以用到这个,像缺省页什么的

    import android.app.Activity;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.FrameLayout;
    
    import com.eluton.medclass.R;
    
    public class TopHelper {
        // TODO: 2020/3/28  对于复用的view直接用这种吧,类似dialog,都是盖在最顶层
        private Activity activity;
        private FrameLayout frameLayout;
        private View goalView;//复用的图
        private boolean isShow = false;//是否显示
    
        public boolean isShow() {//判断页面是否可见
            return isShow;
        }
    
        public TopHelper(Activity activity) {
            this.activity = activity;
            frameLayout = (FrameLayout) activity.findViewById(android.R.id.content);
            initView();
        }
    
        private void initView() {//
    //       R.layout.re_category:是你自定义的要复用的布局
            goalView = LayoutInflater.from(activity).inflate(R.layout.re_category, frameLayout, false);
        }
    
        public void showCategory() {
            if (goalView == null) {
                initView();
            }
            if (goalView.getParent() == null) {//防止frameLayout多次添加goalView,而且有parent的view也不能被添加
                isShow = true;
                frameLayout.addView(goalView);
            }
    
        }
    
        public void hideCate() {
            if (frameLayout != null && goalView != null) {
                isShow = false;
                frameLayout.removeView(goalView);
            }
        }
    }
    
    

    2.重力感应

    //重力感应
    public class SensorHelper {
        // TODO: 2020/3/28 一般用在播放视频方面
        private Activity activity;
        private SensorInterface sensorInterface;
    
        public void setSensorInterface(SensorInterface sensorInterface) {
            this.sensorInterface = sensorInterface;
        }
    
        public SensorHelper(Activity activity) {
            this.activity = activity;
            SensorManager sensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);
            Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            OrientationSensorListener listener = new OrientationSensorListener();
            sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);
        }
    
        // TODO: 2019/1/19 重力感应
        public class OrientationSensorListener implements SensorEventListener {
            private static final int _DATA_X = 0;
            private static final int _DATA_Y = 1;
            private static final int _DATA_Z = 2;
    
            public static final int ORIENTATION_UNKNOWN = -1;
    
            @Override
            public void onAccuracyChanged(Sensor sensor, int i) {
            }
    
            @Override
            public void onSensorChanged(SensorEvent event) {
                float[] values = event.values;
                int orientation = ORIENTATION_UNKNOWN;
                float X = -values[_DATA_X];
                float Y = -values[_DATA_Y];
                float Z = -values[_DATA_Z];
                float magnitude = X * X + Y * Y;
                // Don't trust the angle if the magnitude is small compared to the y value
                if (magnitude * 4 >= Z * Z) {
                    float OneEightyOverPi = 57.29577957855f;
                    float angle = (float) Math.atan2(-Y, X) * OneEightyOverPi;
                    orientation = 90 - (int) Math.round(angle);
                    // normalize to 0 - 359 range
                    while (orientation >= 360) {
                        orientation -= 360;
                    }
                    while (orientation < 0) {
                        orientation += 360;
                    }
                }
                if (sensorInterface != null) {
                    sensorInterface.angle(orientation);
                }
            }
        }
    
        public interface SensorInterface {
            void angle(int orientation);
        }
    
        public void depict(int orientation) {
            if (orientation >= 45 && orientation < 135) {
                activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
    //            LogUtil.i("横屏翻转: ");
            } else if (orientation >= 135 && orientation < 225) {
                activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_PORTRAIT);
    //            LogUtil.i("竖屏翻转: ");
            } else if (orientation >= 225 && orientation < 315) {
                activity.setRequestedOrientation(SCREEN_ORIENTATION_LANDSCAPE);
    //            LogUtil.i("横屏: ");
            } else if ((orientation >= 315 && orientation < 360) || (orientation >= 0 && orientation < 45)) {
                activity.setRequestedOrientation(SCREEN_ORIENTATION_PORTRAIT);
    //            LogUtil.i("竖屏: ");
            }
        }
    }
    
    

    3.获取屏幕宽高、dp和·px间的相互转换

    import android.app.Activity;
    import android.content.Context;
    import android.util.DisplayMetrics;
    import android.view.WindowManager;
    
    public class ScreenHelper {
        private Context context;
        private int height;
        private int width;
    
        public ScreenHelper(Context context) {
            this.context = context;
            WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics metrics = new DisplayMetrics();
            manager.getDefaultDisplay().getMetrics(metrics);
            width = metrics.widthPixels;
            height = metrics.heightPixels;
        }
    
        //    获取屏幕高度
        public int getHeight() {
            return height;
        }
    
        //    获取屏幕高度
        public int getWidth() {
            return width;
        }
    
        //    判断是否是全屏
        public boolean isLandscape(Activity activity) {
            DisplayMetrics dm = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
            int mWidth = dm.widthPixels;
            int mHeight = dm.heightPixels;
            if (mHeight > mWidth) {//layout port
                return false;
            }
            return true;
        }
    
        /**
         * dpתpx
         */
        public static int dip2px(Context ctx, float dpValue) {
            final float scale = ctx.getResources().getDisplayMetrics().density;
            return (int) (dpValue * scale + 0.5f);
        }
    
    
        /**
         * pxתdp
         */
        public static int px2dip(Context ctx, float pxValue) {
            final float scale = ctx.getResources().getDisplayMetrics().density;
            return (int) (pxValue / scale + 0.5f);
        }
    }
    
    

    4.适配器

    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.Color;
    import android.graphics.Rect;
    import android.graphics.Typeface;
    import android.graphics.drawable.AnimationDrawable;
    import android.graphics.drawable.Drawable;
    import android.support.v7.widget.CardView;
    import android.text.Layout;
    import android.text.Spannable;
    import android.text.TextPaint;
    import android.text.method.LinkMovementMethod;
    import android.text.style.ClickableSpan;
    import android.util.SparseArray;
    import android.util.TypedValue;
    import android.view.LayoutInflater;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.BaseAdapter;
    import android.widget.GridView;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.ListView;
    import android.widget.ProgressBar;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.bumptech.glide.Glide;
    import com.eluton.base.BaseApplication;
    import com.eluton.cardutil.CardUtils;
    import com.eluton.medclass.R;
    import com.eluton.utils.LogUtil;
    
    import java.util.ArrayList;
    
    
    /**
     * Created by Administrator on 2016/8/30 0030.
     * T。泛型:可以是各种对象,例如Dog,Penson包括map,list等
     * abstract:抽象类的标志,抽象类一般被用来被继承
     * SparseArray<E>来代替HashMap<Integer, E>
     */
    public abstract class MyAdapter<T> extends BaseAdapter {
    
        private ArrayList<T> mData;
        private int mLayoutRes;           //item布局id
    
    
        public MyAdapter(ArrayList<T> mData, int mLayoutRes) {
            this.mData = mData;
            this.mLayoutRes = mLayoutRes;
        }
    
        @Override
        public int getCount() {
            return mData != null ? mData.size() : 0;
        }
    
        @Override
        public T getItem(int position) {
            return mData.get(position);
        }
    
        @Override
        public long getItemId(int position) {
            return position;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = ViewHolder.bind(parent.getContext(), convertView, parent, mLayoutRes
                    , position);
            bindView(holder, getItem(position));
            return holder.getItemView();
        }
    
        public abstract void bindView(ViewHolder holder, T obj);
    
        //添加一个元素
        public void add(T data) {
            if (mData == null) {
                mData = new ArrayList<>();
            }
            mData.add(data);
            notifyDataSetChanged();
        }
    
        //往特定位置,添加一个元素
        public void add(int position, T data) {
            if (mData == null) {
                mData = new ArrayList<>();
            }
            mData.add(position, data);
            notifyDataSetChanged();
        }
    
        public void remove(T data) {
            if (mData != null) {
                mData.remove(data);
            }
            notifyDataSetChanged();
        }
    
        public void remove(int position) {
            if (mData != null) {
                mData.remove(position);
            }
            notifyDataSetChanged();
        }
    
        public void clear() {
            if (mData != null) {
                mData.clear();
            }
            notifyDataSetChanged();
        }
    
    
        public static class ViewHolder {
    
            private SparseArray<View> mViews;   //存储ListView 的 item中的View
            private View item;                  //存放convertView
            private int position;               //游标
            private Context context;            //Context上下文
    
            //构造方法,完成相关初始化
            private ViewHolder(Context context, ViewGroup parent, int layoutRes) {
                mViews = new SparseArray<>();
                this.context = context;
                View convertView = LayoutInflater.from(context).inflate(layoutRes, parent, false);
    //            第3个参数:那么attachToRoot是什么作用呢? 他会自动把layout加到View hierarchy中, 不需要手动调用root.addView,当然在Adapter.getView里面不用手动调用root.addView是因为Adapter已经帮我们做了, 所以如果我们在Adapter.getView里面传入attachToRoot为true的话,就会报错, 因为一个view不能attach两次
                convertView.setTag(this);//this指holder
                item = convertView;
            }
    
            //绑定ViewHolder与item
            public static ViewHolder bind(Context context, View convertView, ViewGroup parent,
                                          int layoutRes, int position) {
                ViewHolder holder;
                if (convertView == null) {
                    holder = new ViewHolder(context, parent, layoutRes);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                    holder.item = convertView;
                }
                holder.position = position;
                return holder;
            }
    
            @SuppressWarnings("unchecked")
            public <T extends View> T getView(int id) {
                T t = (T) mViews.get(id);
                if (t == null) {
                    t = (T) item.findViewById(id);
                    mViews.put(id, t);
                }
                return t;
            }
    
    
            /**
             * 获取当前条目
             */
            public View getItemView() {
                return item;
            }
    
            /**
             * 获取条目位置
             */
            public int getItemPosition() {
                return position;
            }
    
            /**
             * 设置文字
             */
            public ViewHolder setText(int id, CharSequence text) {
                View view = getView(id);
                if (view instanceof TextView) {
                    ((TextView) view).setText(text);
                }
                return this;
            }
    
            public ViewHolder setTextSize(int id, int size) {
                View view = getView(id);
                if (view instanceof TextView) {
                    ((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
                }
                return this;
            }
    
            public ViewHolder setPadding(int id, int left, int top, int right, int bottom) {
                View view = getView(id);
                if (view instanceof TextView) {
                    ((TextView) view).setPadding(left, top, right, bottom);
                }
                return this;
            }
    
    
            public ViewHolder setMovementMethod(int id) {
                View view = getView(id);
                if (view instanceof TextView) {
                    ((TextView) view).setMovementMethod(LinkMovementMethod.getInstance());
                }
                return this;
            }
    
            public ViewHolder setSpecail(int id) {
                View view = getView(id);
                if (view instanceof TextView) {
    //                LogUtil.i("C");
    //                TextView包含可点击链接
                    ((TextView) view).setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent motionEvent) {
                            boolean ret = false;
                            int action = motionEvent.getAction();
                            TextView tv = (TextView) v;
                            CharSequence text = ((TextView) v).getText();
                            Spannable stext = Spannable.Factory.getInstance().newSpannable(text);
    //                        if (text instanceof SpannableString) {
                            if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
                                LogUtil.i("G");
                                int x = (int) motionEvent.getX();
                                int y = (int) motionEvent.getY();
                                x -= tv.getTotalPaddingLeft();
                                y -= tv.getTotalPaddingTop();
                                x += tv.getScrollX();
                                y += tv.getScrollY();
                                Layout layout = tv.getLayout();
                                int line = layout.getLineForVertical(y);
                                int off = layout.getOffsetForHorizontal(line, x);
                                ClickableSpan[] link = stext.getSpans(off, off, ClickableSpan.class);
    
                                if (link.length != 0) {
                                    LogUtil.i("A");
                                    if (action == MotionEvent.ACTION_UP) {
                                        link[0].onClick(tv);
                                        LogUtil.i("H");
                                    }
                                    ret = true;
    //                                link[0].onClick(tv);
                                } else {
                                    LogUtil.i("B");
                                }
    //                            }
                            }
                            return ret;
                        }
                    });
                }
                return this;
            }
    
            private class MyClickSpan extends ClickableSpan {
    
                private String tag;
    
                public MyClickSpan(String tag) {
                    this.tag = tag;
                }
    
                @Override
                public void onClick(View widget) {
                    LogUtil.i("D");
                    Toast.makeText(BaseApplication.getContext(), tag + " is clicked", Toast.LENGTH_SHORT).show();
                }
    
                @Override
                public void updateDrawState(TextPaint ds) {
                    LogUtil.i("E");
                    ds.setColor(Color.RED);
                }
            }
    
            /**
             * 设置文字
             */
            public ViewHolder setText(int id, CharSequence text, CharSequence text_zero) {
                View view = getView(id);
                if (view instanceof TextView) {
                    ((TextView) view).setText(text);
                    if (text.equals(text_zero)) {
                        ((TextView) view).setTextColor(context.getResources().getColor(R.color.green_00b395));
                    } else {
                        ((TextView) view).setTextColor(0xff333333);
                    }
                }
                return this;
            }
    
            public ViewHolder setAdapter(int id, MyAdapter adapter) {
                View view = getView(id);
                if (view instanceof ListView) {
                    ((ListView) view).setAdapter(adapter);
                } else if (view instanceof GridView) {
                    ((GridView) view).setAdapter(adapter);
                }
                return this;
            }
    
            /**
             * 设置gridviewd点击事件
             */
            public ViewHolder setOnItemClickListener(int id, AdapterView.OnItemClickListener onItemClickListener) {
                View view = getView(id);
                if (view instanceof GridView) {
                    ((GridView) view).setOnItemClickListener(onItemClickListener);
                } else {
                    ((ListView) view).setOnItemClickListener(onItemClickListener);
                }
                return this;
            }
    
            public ViewHolder setProgress(int id, int progress) {
                View view = getView(id);
                if (view instanceof ProgressBar) {
                    ((ProgressBar) view).setProgress(progress);
                }
                return this;
            }
    
            public Drawable getDrawable(int id) {
                View view = getView(id);
                if (view instanceof ImageView) {
                    Drawable drawable = ((ImageView) view).getDrawable();
                    return drawable;
                }
                return null;
            }
    
    
            public Rect getRect(int id) {
                View view = getView(id);
                Rect rect = new Rect();
                view.getGlobalVisibleRect(rect);
                return rect;
            }
    
            public int getViewCount(int id) {
                View view = getView(id);
                if (view instanceof LinearLayout) {
                    int num = ((LinearLayout) view).getChildCount();
                    return num;
                }
                return 0;
            }
    
    
            public ViewHolder setTextAppend(int id, String space, CharSequence text) {
                View view = getView(id);
                if (view instanceof TextView) {
                    ((TextView) view).setText(space);
                    ((TextView) view).append(text);
                }
                return this;
            }
    
            public ViewHolder setDrawLeft(int id, Drawable drawable) {
                View view = getView(id);
                if (view instanceof TextView) {
                    ((TextView) view).setCompoundDrawables(drawable, null, null, null);
                }
                return this;
            }
    
            public ViewHolder setSize(int id, CharSequence text, String state) {
                View view = getView(id);
                if (view instanceof TextView) {
                    if (!state.equals("0")) {
                        ((TextView) view).setText("/" + text);
                    } else {
                        ((TextView) view).setText("");
                    }
                }
                return this;
            }
    
            public ViewHolder setCurrent(int id, CharSequence text, String state) {
                View view = getView(id);
                if (view instanceof TextView) {
                    if (!state.equals("0")) {
                        ((TextView) view).setText(text);
                    } else {
                        ((TextView) view).setText("");
                    }
                }
                return this;
            }
    
            public ViewHolder setSpeed(int id, CharSequence text, String state) {
                View view = getView(id);
                if (view instanceof TextView) {
                    if (!state.equals("0")) {
                        ((TextView) view).setText(text);
                    } else {
                        ((TextView) view).setText("");
                    }
                }
                return this;
            }
    
    
            /**
             * 设置文字颜色
             */
            public ViewHolder setTextColor(int id, int textColor) {
                View view = getView(id);
                if (view instanceof TextView) {
                    ((TextView) view).setTextColor(textColor);
                }
                return this;
            }
    
            public ViewHolder setCardView(int id, int startColor, int endColor) {
                CardView view = getView(id);
                CardUtils.setCardShadowColor(view, startColor, endColor);
                return this;
            }
    
            public ViewHolder setTextBold(int id, boolean isBold) {
                View view = getView(id);
                if (view instanceof TextView) {
                    if (isBold) {
                        ((TextView) view).setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    } else {
                        ((TextView) view).setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    }
                }
                return this;
            }
    
    
            public ViewHolder setImageBitmap(int id, Bitmap bitmap) {
                View view = getView(id);
                if (view instanceof ImageView) {
                    ((ImageView) view).setImageBitmap(bitmap);
                }
                return this;
            }
    
    
            //设置背景(专属)
            public ViewHolder setBackgroundControl(int id, int drawableRes, boolean flag, boolean isClick) {
                View view = getView(id);
                if (view instanceof ImageView) {
                    ((ImageView) view).setImageResource(drawableRes);
                }
                if (flag || isClick) {
                    view.setVisibility(View.INVISIBLE);
                }
                return this;
            }
    
    
            //设置背景
            public ViewHolder setBackground(int id, int drawableRes) {
                View view = getView(id);
                view.setBackgroundResource(drawableRes);
                return this;
            }
    
            //设置背景
            public ViewHolder setBackgroundColor(int id, int drawableRes) {
                View view = getView(id);
                view.setBackgroundColor(drawableRes);
                return this;
            }
    
            /**
             * 设置图片
             */
            public ViewHolder setImageResource(int id, int drawableRes) {
                View view = getView(id);
                if (view instanceof ImageView) {
                    ((ImageView) view).setImageResource(drawableRes);
                } else {
                    view.setBackgroundResource(drawableRes);
                }
                return this;
            }
    
            /**
             * 设置图片
             */
            public ViewHolder setImageGlide(int id, String url) {
                View view = getView(id);
                if (view instanceof ImageView && url != null && !url.equals("1")) {
                    Glide.with(BaseApplication.getContext()).load(url).into((ImageView) view);
                } else {
                    ((ImageView) view).setImageResource(R.mipmap.ic_launcher);
                }
                return this;
            }
    
            public ViewHolder setImageScale(int id, ImageView.ScaleType scaleType) {
                View view = getView(id);
                if (view instanceof ImageView) {
                    ((ImageView) view).setScaleType(scaleType);
                }
                return this;
            }
    
    
            public ViewHolder setTextOne(int id, CharSequence text, int id2, int id3) {
                View view = getView(id);
                View view2 = getView(id2);
                View view3 = getView(id3);
                if (view instanceof TextView) {
                    ((TextView) view).setText(text);
                    view2.setVisibility(View.INVISIBLE);
                    view3.setVisibility(View.INVISIBLE);
                }
                return this;
            }
    
    
            /**
             * 设置点击监听
             */
            public ViewHolder setOnClickListener(int id, View.OnClickListener listener) {
                getView(id).setOnClickListener(listener);
                return this;
            }
    
            /**
             * 设置触摸监听
             */
            public ViewHolder setOnTouchListener(int id, View.OnTouchListener listener) {
                getView(id).setOnTouchListener(listener);
                return this;
            }
    
            /**
             * 设置可见
             */
            public ViewHolder setVisibility(int id, int visible) {
                getView(id).setVisibility(visible);
                return this;
            }
    
            public ViewHolder removeView(int id) {
                ((ViewGroup) getView(id)).removeAllViews();
                return this;
            }
    
            public ViewHolder addLinearView(int id, View view) {
                ((ViewGroup) getView(id)).addView(view);
                return this;
            }
    
            public void startAnim(int id) {
                AnimationDrawable drawable = (AnimationDrawable) getView(id).getBackground();
                drawable.start();
            }
    
    //        public ViewHolder setVisibility(int id, boolean isDelete) {
    //            if (isDelete){
    //                getView(id).setVisibility(View.GONE);
    //            }else {
    //                getView(id).setVisibility(View.VISIBLE);
    //            }
    //            return this;
    //        }
    
            /**
             * 设置标签
             */
            public ViewHolder setTag(int id, Object obj) {
                getView(id).setTag(obj);
                return this;
            }
    
    
            /**
             * 设置可点击
             */
            public ViewHolder setEnabled(int id, boolean adapter) {
                View view = getView(id);
                view.setEnabled(adapter);
                return this;
            }
    
            //其他方法可自行扩展
        }
    }
    

    Recycler通用适配器

    import android.app.Activity;
    import android.content.Context;
    import android.graphics.Rect;
    import android.graphics.drawable.Drawable;
    import android.os.Build;
    import android.os.Looper;
    import android.os.Message;
    import android.support.annotation.NonNull;
    import android.support.v7.widget.RecyclerView;
    import android.text.Html;
    import android.util.SparseArray;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.webkit.WebSettings;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.widget.AbsListView;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.ListView;
    import android.widget.TextView;
    
    
    import com.bumptech.glide.Glide;
    import com.eluton.base.BaseApplication;
    import com.eluton.webpic.ImageGetterUtil;
    import com.eluton.webpic.MyTagHandler;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public abstract class ZRecyclerAdapter<T> extends RecyclerView.Adapter<ZRecyclerAdapter.ViewHolder> {
    
        protected List<T> tList = new ArrayList<>();
        protected Context context;
        protected LayoutInflater layoutInflater;
        protected int layoutId;
        private RecycleInter recycleInter;
    
        public void setRecycleInter(RecycleInter recycleInter) {
            this.recycleInter = recycleInter;
        }
    
        public ZRecyclerAdapter(List<T> tList, Context context, int layoutId) {
            this.tList = tList;
            this.context = context;
            this.layoutId = layoutId;
            layoutInflater = LayoutInflater.from(context);
        }
    
        public interface RecycleInter {
            void itemClick(int position);
        }
    
        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
            bindView(holder, tList.get(position), position);
            holder.item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (recycleInter != null)
                        recycleInter.itemClick(position);
                }
            });
        }
    
        @Override
        public int getItemViewType(int position) {
            if (multiTypeSupport != null) {
                return multiTypeSupport.getLayoutId(tList.get(position));
            }
            return super.getItemViewType(position);
        }
    
        @Override
        public int getItemCount() {
            return tList.size();
        }
    
        private MultiTypeSupport<T> multiTypeSupport;
    
        public void setMultiTypeSupport(MultiTypeSupport<T> multiTypeSupport) {
            this.multiTypeSupport = multiTypeSupport;
        }
    
        public interface MultiTypeSupport<T> {
            int getLayoutId(T item);
        }
    
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            if (multiTypeSupport != null) {
                layoutId = viewType;
            }
            View view = layoutInflater.inflate(layoutId, parent, false);
            ViewHolder viewHolder = new ViewHolder(view);
            return viewHolder;
        }
    
        public abstract void bindView(ViewHolder holder, T obj, int position);
    
        public static class ViewHolder extends RecyclerView.ViewHolder {
            private SparseArray<View> mViews;
            View item;//存放convertView
    
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                item = itemView;
                mViews = new SparseArray();
            }
    
    //        private ViewHolder(Context paramContext, ViewGroup paramViewGroup, int layoutId) {
    //            this.context = paramContext;
    //            View convertView = LayoutInflater.from(paramContext).inflate(layoutId, paramViewGroup, false);
    //            convertView.setTag(this);
    //            item = convertView;
    //        }
    //        public static ViewHolder bind(Context paramContext, View paramView, ViewGroup paramViewGroup, int layoutId, int paramInt2) {
    //            ViewHolder holder;
    //            if (paramView == null) {
    //                holder = new ViewHolder(paramContext, paramViewGroup, layoutId);
    //            } else {
    //                holder = (ViewHolder) paramView.getTag();
    //                holder.item = paramView;
    //            }
    //            holder.position = paramInt2;
    //            return holder;
    //        }
    
            @SuppressWarnings("unchecked")
            public <T extends View> T getView(int id) {
                T t = (T) mViews.get(id);
                if (t == null) {
                    t = (T) item.findViewById(id);
                    mViews.put(id, t);
                }
                return t;
            }
    
            /**
             * 获取当前条目
             */
            public View getItemView() {
                return item;
            }
    
    
            /**
             * 设置文字
             */
            public ViewHolder setText(int id, CharSequence text) {
                View view = getView(id);
                if (view instanceof TextView) {
                    ((TextView) view).setText(text);
                }
                return this;
            }
    
            public ViewHolder setDrawableRight(int id, Drawable drawableRight) {
                View view = getView(id);
                if (view instanceof TextView) {
                    ((TextView) view).setCompoundDrawables(null, null, drawableRight, null);
                }
                return this;
            }
    
            public ViewHolder setAdapter(int id, BaseAdapter adapter) {
                View view = getView(id);
                if (view instanceof AbsListView) {
                    ((AbsListView) view).setAdapter(adapter);
                }
                return this;
            }
    
            /**
             * 设置图片
             */
            public ViewHolder setImageResource(int id, int drawableRes) {
                View view = getView(id);
                if (view instanceof ImageView) {
                    ((ImageView) view).setImageResource(drawableRes);
                } else {
                    view.setBackgroundResource(drawableRes);
                }
                return this;
            }
    
            public ViewHolder setImageGlide(int id, String url) {
                View view = getView(id);
                if (view instanceof ImageView) {
                    Glide.with(BaseApplication.getContext()).load(url).into((ImageView) view);
                }
                return this;
            }
    
    
            /**
             * 设置点击监听
             */
            public ViewHolder setOnClickListener(int id, View.OnClickListener listener) {
                getView(id).setOnClickListener(listener);
                return this;
            }
    
            public ViewHolder setWebContent(int id, final String webStr) {
                final WebView web = (WebView) getView(id);
    //            ImageGetterUtil.getXLYGetter(activity, pad, new ImageGetterUtil.Callback() {
    //                @Override
    //                public void callBack(Html.ImageGetter imageGetter) {
    //                    final CharSequence charSequence = Html.fromHtml(webStr, imageGetter,new MyTagHandler(activity));//
    //                    activity.runOnUiThread(new Runnable() {
    //                        @Override
    //                        public void run() {
    //                            //此时已在主线程中,更新UI
    //                            web.setText(charSequence);
    //                        }
    //                    });
    ////                    Handler mainHandler = new Handler(Looper.getMainLooper());
    ////                    mainHandler.post(new Runnable() {
    ////                        @Override
    ////                        public void run() {
    ////                            //已在主线程中,更新UI
    ////                            web.setText(charSequence);
    ////                        }
    ////                    });
    //                }
    //            });
    
                String kk = webStr.replace("<img", "<img width=\"100%\"");
                web.loadDataWithBaseURL(null, kk, "text/html", "UTF-8", null);
                return this;
            }
    
            /**
             * 设置可见
             */
            public ViewHolder setVisibility(int id, int visible) {
                getView(id).setVisibility(visible);
                return this;
            }
    
            /**
             * 设置标签
             */
            public ViewHolder setTag(int id, Object obj) {
                getView(id).setTag(obj);
                return this;
            }
    
            public void setEnabled(int paramInt, boolean paramBoolean) {
                getView(paramInt).setEnabled(paramBoolean);
            }
    
            public void setTextColor(int paramInt1, int paramInt2) {
                View localView = getView(paramInt1);
                if ((localView instanceof TextView))
                    ((TextView) localView).setTextColor(paramInt2);
            }
    
            public Drawable getDrawable(int paramInt) {
                View localView = getView(paramInt);
                if ((localView instanceof ImageView))
                    return ((ImageView) localView).getDrawable();
                return null;
            }
    
            public void setBackgroundResource(int paramInt1, int paramInt2) {
                getView(paramInt1).setBackgroundResource(paramInt2);
            }
    
            public Rect getRect(int paramInt) {
                View localView = getView(paramInt);
                Rect localRect = new Rect();
                localView.getGlobalVisibleRect(localRect);
                return localRect;
            }
    
            public void setBackgroundColor(int paramInt1, int paramInt2) {
                getView(paramInt1).setBackgroundColor(paramInt2);
            }
    
    
            public ViewHolder e(int paramInt1, int paramInt2) {
                View localView = getView(paramInt1);
                if ((localView instanceof ImageView)) {
                    ((ImageView) localView).setImageResource(paramInt2);
                    return this;
                }
                localView.setBackgroundResource(paramInt2);
                return this;
            }
        }
    }
    

    5.创建无边界的dialog,在styles.xml添加下面内容

    <style name="AlertDialog" parent="android:style/Theme.Dialog">
            <item name="android:background">@android:color/transparent</item>
            <item name="android:windowBackground">@android:color/transparent</item>
            <item name="android:windowNoTitle">true</item>
        </style>
    

    使用流程如下

    //这个布局是您自定义的布局,这里只是举个例子(dialog_workwarn)
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_height="match_parent">
    
        <LinearLayout
            android:layout_width="315dp"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:background="@drawable/shape_r6_white"
            android:orientation="vertical">
    
            <ImageView
                android:id="@+id/img"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:scaleType="center"
                android:src="@mipmap/live_notice" />
    
            <TextView
                android:id="@+id/notice"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="16dp"
                android:layout_marginRight="20dp"
                android:layout_marginBottom="16dp"
                android:gravity="center"
                tools:text="马卡可能小姐按摩下卡萨没显卡是相爱时就看你瞎说想你撒即可向你看撒就像那句是开心呐"
                android:lineSpacingMultiplier="1.2"
                android:textColor="@color/black_1e1e1e"
                android:textSize="15sp" />
    
            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/green_00b395" />
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="44dp"
                android:orientation="horizontal">
    
                <TextView
                    android:id="@+id/cancel"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/shape_r6lb_white"
                    android:gravity="center"
                    android:text="稍后再做"
                    android:textColor="@color/green_00b395"
                    android:textSize="16sp" />
    
                <TextView
                    android:id="@+id/ensure"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/shape_r6rb_green"
                    android:gravity="center"
                    android:text="立即去做"
                    android:textColor="@color/white"
                    android:textSize="16sp" />
            </LinearLayout>
        </LinearLayout>
    </RelativeLayout>
    
    AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.AlertDialog);
                View view = LayoutInflater.from(activity).inflate(R.layout.dialog_workwarn, null);
                TextView ensure = view.findViewById(R.id.ensure);
                TextView cancel = view.findViewById(R.id.cancel);
                ImageView warnImg = view.findViewById(R.id.img);
                warnImg.setImageResource(R.mipmap.live_homework_notice);
                TextView warnTv = view.findViewById(R.id.notice);
                warnTv.setText("还有课后作业,记得去完成哦!");
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    }
                });
                ensure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    }
                });
                builder.setView(view);
                builder.setCancelable(false);
                tipDialog = builder.create();
    

    相关文章

      网友评论

          本文标题:通用布局辅助、重力感应、通用适配器、自定义无边框Dialog

          本文链接:https://www.haomeiwen.com/subject/uqksuhtx.html