Android自定义布局实现连线题效果

效果图

1600933835379.gif

MainActivity布局

 <com.zhy.connectingviewdemo.connectingView.ConnectingView
    android:id="@+id/m_connect"
    android:layout_width="match_parent"
    android:orientation="vertical"
    app:nomal_color="#666666"
    app:right_color="#008000"
    app:error_color="#FF0000"
    android:layout_height="500dp"/>
<Button
    android:id="@+id/m_ok"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="确认答案" />
<Button
    android:id="@+id/m_reset"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="重置" />

MainActivity

@BindView(R.id.m_connect)
ConnectingView mConnect;
@BindView(R.id.m_ok)
Button mOk;
@BindView(R.id.m_reset)
Button mReset;

private List<ConnectListBean> mLeftDataList = new ArrayList<>();
private List<ConnectListBean> mRightDataList = new ArrayList<>();
private ConnectAdapter<ConnectListBean> mConnectAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    mLeftDataList.add(new ConnectListBean(1, "晴朗的", 1, 2));
    mLeftDataList.add(new ConnectListBean(2, "天真的", 2, 5));
    mLeftDataList.add(new ConnectListBean(3, "鲜艳的", 3, 1));
    mLeftDataList.add(new ConnectListBean(4, "勇敢的", 4, 3));
    mLeftDataList.add(new ConnectListBean(5, "绿色的", 5, 4));

    mRightDataList.add(new ConnectListBean(1, "花朵", 3, 1));
    mRightDataList.add(new ConnectListBean(2, "天空", 1, 2));
    mRightDataList.add(new ConnectListBean(3, "哨兵", 4, 3));
    mRightDataList.add(new ConnectListBean(4, "翠鸟", 5, 4));
    mRightDataList.add(new ConnectListBean(5, "孩子", 2, 5));

    showData();
}

private void showData() {
    mConnectAdapter = new ConnectAdapter<ConnectListBean>(MainActivity.this, mLeftDataList, mRightDataList, R.layout.item_conn_left, R.layout.item_conn_right) {
        @Override
        public void leftConvert(ConnectViewHolder holder, ConnectListBean item, int position, boolean isSelect, boolean isVerify, boolean isRight) {
            SuperTextView view = holder.getView(R.id.m_text);
            view.setText(item.getTitle());
            view.setTextColor(isSelect || isVerify ? 0xffffffff : 0xff333333);
            view.setSolid(isVerify ? isRight ? 0xff008000 : 0xffFF0000 : isSelect ? 0xff5075FC : 0xfff9f9f9);
        }

        @Override
        public void rightConvert(ConnectViewHolder holder, ConnectListBean item, int position, boolean isSelect, boolean isVerify, boolean isRight) {
            SuperTextView view = holder.getView(R.id.m_text);
            view.setText(item.getTitle());
            view.setTextColor(isSelect || isVerify ? 0xffffffff : 0xff333333);
            view.setSolid(isVerify ? isRight ? 0xff008000 : 0xffFF0000 : isSelect ? 0xff5075FC : 0xfff9f9f9);
        }

        @Override
        public boolean verifyAnswer(ConnectListBean leftItem, ConnectListBean rightItem, int leftPosion, int rightPosition) {
            return leftItem.getRightId() == rightItem.getId();
        }

    };
    mConnect.setAdapter(mConnectAdapter);
    mConnect.setAutoVerifyAnswer(false).setOnVerifyAnswer(rightNum -> {
        Toast.makeText(this, "正确数量:"+rightNum, Toast.LENGTH_SHORT).show();
    });
}

@OnClick({R.id.m_ok, R.id.m_reset})
public void onViewClicked(View view) {
    switch (view.getId()) {
        case R.id.m_ok:
            mConnect.verifyAnswer();//验算正确答案
            break;
        case R.id.m_reset:
            mConnect.reset();//重置
            break;
    }
}

ConnectListBean

public class ConnectListBean {
private int id;//题目id
private String title;//题目文字
private int leftId;//左侧对应id
private int rightId;//右侧对应id

public ConnectListBean(int id, String title, int leftId, int rightId) {
    this.id = id;
    this.title = title;
    this.leftId = leftId;
    this.rightId = rightId;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public int getLeftId() {
    return leftId;
}

public void setLeftId(int leftId) {
    this.leftId = leftId;
}

public int getRightId() {
    return rightId;
}

public void setRightId(int rightId) {
    this.rightId = rightId;
}
}

item布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.coorchice.library.SuperTextView
        android:id="@+id/m_text"
        android:layout_width="100dp"
        android:layout_height="38dp"
        android:text="苹果"
        android:textColor="#333333"
        android:textSize="13sp"
        android:gravity="center"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        app:stv_corner="5dp"
        android:layout_marginLeft="10dp"
        app:stv_solid="#f9f9f9" />
  </LinearLayout>

注意:具体内容一定要垂直居中显示

ConnectingView

public class ConnectingView extends RelativeLayout {
private Context mContext;
private ConnectAdapter mAdapter;
private List<View> mLeftViewList = new ArrayList<>();
private List<View> mRightViewlist = new ArrayList<>();
private Map<String, ConnectBean> mLineMap = new HashMap();
private Map<View, String> mDoneLineMap = new HashMap<>();
private Map<Integer, Integer> mSelectMap = new HashMap<>();
private boolean mIsAutoVerifyAnswer = true;
private int mRightNum;
private OnVerifyAnswer mOnVerifyAnswer;
private int COLOR_NOMAL = 0xff666666;
private int COLOR_RIGHT = 0xff008000;
private int COLOR_ERROR = 0xffFF0000;
private int mNomalColor;
private int mRightColor;
private int mErrorColor;
private boolean mIsFinsh = false;

public ConnectingView(Context context) {
    this(context, null);
}

public ConnectingView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ConnectingView);
    mNomalColor = ta.getColor(R.styleable.ConnectingView_nomal_color, COLOR_NOMAL);
    mRightColor = ta.getColor(R.styleable.ConnectingView_right_color, COLOR_RIGHT);
    mErrorColor = ta.getColor(R.styleable.ConnectingView_error_color, COLOR_ERROR);
    mContext = context;
}


int mTopMargin = 0 ;
public void setAdapter(ConnectAdapter adapter){
    mAdapter = adapter;
    mTopMargin = 0 ;
    for (int i = 0; i < adapter.getCount(); i++) {
        LayoutParams ll = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        View view =  adapter.getLeftView( i, null,false ,false, false);
        ll.topMargin = mTopMargin;
        int width = MeasureSpec.makeMeasureSpec(0,
                MeasureSpec.UNSPECIFIED);
        int height = MeasureSpec.makeMeasureSpec(0,
                MeasureSpec.UNSPECIFIED);
        view.measure(width, height);
        mTopMargin+= view.getMeasuredHeight();
        view.setLayoutParams(ll);
        mLeftViewList.add(view);
        addView(view);
    }
    mTopMargin = 0 ;
    for (int i = 0; i < adapter.getCount(); i++) {
        LayoutParams ll = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        View view = adapter.getRightView( i, null,false, false, false);
        ll.topMargin = mTopMargin;
        ll.addRule(ALIGN_PARENT_RIGHT);
        int width = MeasureSpec.makeMeasureSpec(0,
                MeasureSpec.UNSPECIFIED);
        int height = MeasureSpec.makeMeasureSpec(0,
                MeasureSpec.UNSPECIFIED);
        view.measure(width, height);
        mTopMargin+= view.getMeasuredHeight();
        view.setLayoutParams(ll);
        mRightViewlist.add(view);
        addView(view);
    }
    setOnClick();
}

private View mLeftSelectView, mRightSelectView;
private int mLeftPosition = -1, mRightPosition = -1;
private void setOnClick() {
    for (int i = 0; i < mLeftViewList.size(); i++) {
        View view =  mLeftViewList.get(i);
        int finalI = i;
        view.setOnClickListener(v -> {
            if (mIsFinsh)return;
            if (mRightSelectView != null){
                mLeftPosition = finalI;
                mLeftSelectView  = v;
                drawLine();
            }else{
                if (mLeftPosition != -1){
                    mAdapter.getLeftView( mLeftPosition, mLeftSelectView,false, false, false);
                }
                mLeftPosition = finalI;
                mLeftSelectView  = v;
                mAdapter.getLeftView( mLeftPosition, mLeftSelectView,true, false,false);
            }
        });
    }
    for (int i = 0; i < mRightViewlist.size(); i++) {
        View view =  mRightViewlist.get(i);
        int finalI = i;
        view.setOnClickListener(v -> {
            if (mIsFinsh)return;
            if (mLeftSelectView != null){
                mRightPosition = finalI;
                mRightSelectView = v;
                drawLine();
            }else{
                if (mRightPosition != -1){
                    mAdapter.getRightView( mRightPosition, mRightSelectView,false, false, false);
                }
                mRightPosition = finalI;
                mRightSelectView = v;
                mAdapter.getRightView( mRightPosition, mRightSelectView,true, false, false);
            }
        });
    }
}

private void drawLine() {
    ConnectBean bean = new ConnectBean();
    bean.setPosition(mLeftPosition);
    bean.setStartX(mLeftSelectView.getWidth()+ dp2px( 5));
    bean.setStartY(mLeftSelectView.getTop() + mLeftSelectView.getHeight()/2);
    bean.setEndX(mRightSelectView.getLeft() - dp2px(5));
    bean.setEndY(mRightSelectView.getTop()+ mRightSelectView.getHeight()/2);

    if (mDoneLineMap.get(mLeftSelectView) != null){
        mLineMap.remove(mDoneLineMap.get(mLeftSelectView));
        mDoneLineMap.remove(mLeftSelectView);

    }
    if (mDoneLineMap.get(mRightSelectView) != null){
        mLineMap.remove(mDoneLineMap.get(mRightSelectView));
        mDoneLineMap.remove(mRightSelectView);
    }

    mLineMap.put(mLeftSelectView + ""+ mRightSelectView, bean);
    mDoneLineMap.put(mLeftSelectView , mLeftSelectView + ""+ mRightSelectView);
    mDoneLineMap.put(mRightSelectView, mLeftSelectView + ""+ mRightSelectView);
    mAdapter.getLeftView( mLeftPosition, mLeftSelectView,false, false, false);
    mAdapter.getRightView(mRightPosition, mRightSelectView,false,false, false);
    mSelectMap.put(mLeftPosition, mRightPosition);
    mLeftSelectView = null;
    mRightSelectView = null;
    mLeftPosition = -1;
    mRightPosition = -1;
    invalidate();
    if (mLineMap.size() == mAdapter.getCount() && mIsAutoVerifyAnswer){
        mRightNum = 0;
        for (int i = 0; i <  mAdapter.getCount(); i++) {
            for (String index : mLineMap.keySet()){
                if ( i == mLineMap.get(index).getPosition()){
                    boolean bool = mAdapter.verifyAnswer(mAdapter.getLeftList().get(i), mAdapter.getRightList().get(mSelectMap.get(i)), i, mSelectMap.get(i));
                    mAdapter.getLeftView(i, mLeftViewList.get(i), false,true, bool);
                    mAdapter.getRightView(i, mRightViewlist.get(mSelectMap.get(i)), false,true, bool);
                    mRightNum =  bool  ? mRightNum +1 : mRightNum;
                    mLineMap.get(index).setVerify(true);
                    mLineMap.get(index).setRight(bool);
                }
            }
        }
        mIsFinsh = true;
        invalidate();
    }
}


@Override
protected void dispatchDraw(Canvas canvas) {
    super.dispatchDraw(canvas);
    for (ConnectBean bean : mLineMap.values()){
        canvas.save();
        Paint paint = new Paint();
        paint.setColor(bean.isVerify() ? bean.isRight() ? mRightColor : mErrorColor : mNomalColor);
        paint.setStrokeWidth(dp2px(2));
        paint.setAntiAlias(true);
        canvas.drawLine(bean.getStartX(), bean.getStartY(), bean.getEndX(), bean.getEndY(), paint);
        canvas.restore();
    }
}

public ConnectingView setAutoVerifyAnswer(boolean bool){
    mIsAutoVerifyAnswer =  bool;
    return this;
}

public ConnectingView verifyAnswer(){
    if (mSelectMap.size() != mAdapter.getCount()){
        mRightNum = -1;
    }else{
        mRightNum = 0;
        for (int i = 0; i <  mAdapter.getCount(); i++) {
            for (String index : mLineMap.keySet()){
                if ( i == mLineMap.get(index).getPosition()){
                    boolean bool = mAdapter.verifyAnswer(mAdapter.getLeftList().get(i), mAdapter.getRightList().get(mSelectMap.get(i)), i, mSelectMap.get(i));
                    mAdapter.getLeftView(i, mLeftViewList.get(i), false,true, bool);
                    mAdapter.getRightView(i, mRightViewlist.get(mSelectMap.get(i)), false,true, bool);
                    mRightNum =  bool  ? mRightNum +1 : mRightNum;
                    mLineMap.get(index).setVerify(true);
                    mLineMap.get(index).setRight(bool);
                }
            }
        }
        mIsFinsh = true;
        invalidate();
    }

    if (mOnVerifyAnswer != null){
        mOnVerifyAnswer.onVerifyAnswer(mRightNum);
    }
    return this;
}

public ConnectingView setOnVerifyAnswer(OnVerifyAnswer onVerifyAnswer){
    mOnVerifyAnswer = onVerifyAnswer;
    return this;
}

public interface OnVerifyAnswer{
    void onVerifyAnswer(int rightNum);
}

public void reset(){
    mIsFinsh = false;
    mSelectMap.clear();
    mLineMap.clear();
    mDoneLineMap.clear();
    for (int i = 0; i < mLeftViewList.size(); i++) {
        mAdapter.getLeftView(i, mLeftViewList.get(i), false,false, false);
    }
    for (int i = 0; i < mRightViewlist.size(); i++) {
        mAdapter.getRightView(i, mRightViewlist.get(i), false,false, false);
    }
    invalidate();
}
public  int dp2px(float dp) {
    final float scale = mContext.getResources().getDisplayMetrics().density;
    return (int) (dp * scale + 0.5f);
}
}

ConnectAdapter

public abstract class ConnectAdapter<T> {
private List<T> mLeftList;
private List<T> mRightList;
private int mItemLeftLoayoutId, mItemRightLoayoutId;
private Context mContext;

protected ConnectAdapter(Context context, List<T> leftlist, List<T> rightList, int itemLeftLayoutId, int itemRightLayoutId){
    mContext = context;
    if (leftlist.size() != rightList.size()){
        new Thread("左右两侧数据数量不一致");
    }
    mLeftList = leftlist;
    mRightList = rightList;
    mItemLeftLoayoutId = itemLeftLayoutId;
    mItemRightLoayoutId = itemRightLayoutId;
}

public View getLeftView(int position, View view, boolean isSelect, boolean isVerify, boolean isRight){
    if (view == null){
        view = LayoutInflater.from(mContext).inflate(mItemLeftLoayoutId, null);
        view.setTag(new ConnectViewHolder(view));
    }
    ConnectViewHolder viewHolder = (ConnectViewHolder) view.getTag();
    leftConvert(viewHolder, (T) mLeftList.get(position), position, isSelect, isVerify, isRight);
    return view;
}

public View getRightView(int position, View view, boolean isSelect, boolean isVerify, boolean isRight){
    if (view == null){
        view = LayoutInflater.from(mContext).inflate(mItemRightLoayoutId, null);
        view.setTag(new ConnectViewHolder(view));
    }
    ConnectViewHolder viewHolder = (ConnectViewHolder) view.getTag();
    rightConvert(viewHolder, (T) mRightList.get(position), position, isSelect, isVerify, isRight);
    return view;
}

public int getCount(){
    return mLeftList.size();
}

public List<T> getLeftList() {
    return mLeftList;
}

public List<T> getRightList(){
    return mRightList;
}

public T getItem(int position){
    return (T) mLeftList.get(position);
}

public abstract void leftConvert(ConnectViewHolder holder, T item,  int position, boolean isSelect, boolean isVerify, boolean isRight);//isSelect:当前是否被选中;isVerify:是否被验证过;isRight:验证后,是否正确
public abstract void rightConvert(ConnectViewHolder holder, T item,  int position, boolean isSelect, boolean isVerify, boolean isRight);
public abstract boolean verifyAnswer(T leftItem, T rightItem, int leftPosion,   int rightPosition);//角标以左侧为准

}

ConnectViewHolder

public class ConnectViewHolder {
private final SparseArray<View> mViews;
private View mConvertView;

ConnectViewHolder(View convertView) {
    this.mViews = new SparseArray<View>();
    mConvertView = convertView;
}
/**
 * 通过控件的Id获取对于的控件,如果没有则加入views
 *
 * @param viewId
 * @return
 */
public <T extends View> T getView(int viewId) {
    View view = mViews.get(viewId);
    if (view == null) {
        view = mConvertView.findViewById(viewId);
        mViews.put(viewId, view);
    }
    return (T) view;
}

public View setText(int viewId, String text) {
    TextView view = getView(viewId);
    view.setText(text);
    return view;
}

public View setText(int viewId, Spanned text) {
    TextView view = getView(viewId);
    view.setText(text);
    return view;
}
}

源码地址

https://gitee.com/zuozuo_zhy/connecting-view.git

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