效果图
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<ImageView
android:id="@+id/btn_reduce"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/addgoods"
android:textSize="20sp" />
<TextView
android:id="@+id/tv_count"
android:layout_width="50dp"
android:layout_height="40dp"
android:gravity="center"
android:textSize="20sp"
android:text="1"/>
<ImageView
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/addgoods"
android:textSize="20sp" />
</LinearLayout>
view类
package com.example.liangyonghui0404.view.activity;
import android.content.Context;
import android.location.Address;
import android.media.Image;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.liangyonghui0404.R;
public class AdderView extends LinearLayout implements View.OnClickListener {
private final TextView count;
private int value;
public AdderView(Context context, AttributeSet attrs) {
super(context, attrs);
View view = View.inflate(context, R.layout.number_adder, this);
count = view.findViewById(R.id.tv_count);
ImageView add = view.findViewById(R.id.btn_add);
ImageView reduce= view.findViewById(R.id.btn_reduce);
add.setOnClickListener(this);
reduce.setOnClickListener(this);
String s = count.getText().toString();
value = Integer.parseInt(s);
setValue(value);
}
//点击事件
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_add:
add();
break;
case R.id.btn_reduce:
reduce();
break;
}
}
//加减方法
private void reduce() {
value--;
setValue(value);
if(onValue!=null){
onValue.onvalue(value);
}
}
private void add() {
value++;
setValue(value);
if(onValue!=null){
onValue.onvalue(value);
}
}
//setget 方法
public int getValue() {
String trim = count.getText().toString().trim();
if(trim!=null){
value = Integer.valueOf(trim);
}
return value;
}
public void setValue(int value) {
this.value = value;
count.setText(value+"");
}
//接口回调
public interface OnValue{
void onvalue(int i);
}
private OnValue onValue;
public void setAdderView(OnValue onValue) {
this.onValue = onValue;
}
}
使用简单 调用接口即可
viewHolder.adderView.setAdderView(new AdderView.OnValue() {
@Override
public void onvalue(int i) {
Log.e("my",""+i);
}
});