美文网首页Android进阶之路
Android自定义布局实现连线题效果

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

作者: 左浩洋 | 来源:发表于2020-09-24 15:11 被阅读0次

效果图

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

相关文章

网友评论

    本文标题:Android自定义布局实现连线题效果

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