<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="2dp"
android:layout_marginLeft="10dp"
android:layout_width="60dp"
android:layout_height="30dp"
android:layout_gravity="center_vertical"
android:background="#99000000"
android:gravity="center_vertical">
<TextView
android:background="#ffffff"
android:layout_weight="1"
android:id="@+id/sub_tv"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center"
android:text="-"
android:textSize="16sp" />
<TextView
android:text="1"
android:layout_marginLeft="2dp"
android:background="#ffffff"
android:layout_weight="1"
android:id="@+id/product_number_tv"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center"
/>
<TextView
android:layout_marginLeft="2dp"
android:background="#ffffff"
android:layout_weight="1"
android:id="@+id/add_tv"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center"
android:text="+"
android:textSize="16sp" />
</LinearLayout>
代码
package com.lichao.bwei.com.lichao20181120;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* date:2018/11/20
* author:李超(li)
* function:
*/
public class Add_Remove extends LinearLayout implements View.OnClickListener {
private TextView sub_tv;
private TextView product_number_tv;
private TextView add_tv;
private int i ;
public Add_Remove(Context context) {
this(context, null);
}
public Add_Remove(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public Add_Remove(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
View inflate = inflate(context, R.layout.add_remove, this);
add_tv = inflate.findViewById(R.id.add_tv);
product_number_tv = inflate.findViewById(R.id.product_number_tv);
sub_tv = inflate.findViewById(R.id.sub_tv);
add_tv.setOnClickListener(this);
sub_tv.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.add_tv:
i++;
product_number_tv.setText(i+"");
onNumberChangeListener.onNumberChange(i);
break;
case R.id.sub_tv:
if (i>1){
i--;
product_number_tv.setText(i+"");
onNumberChangeListener.onNumberChange(i);
}else {
Toast.makeText(getContext(),"不能在减少",Toast.LENGTH_SHORT).show();
}
break;
}
}
public void setNum(int i){
this.i = i;
product_number_tv.setText(i+"");
}
public int getNum(int i){
return i;
}
OnNumberChangeListener onNumberChangeListener;
public void setOnNumberChangeListener(OnNumberChangeListener onNumberChangeListener) {
this.onNumberChangeListener = onNumberChangeListener;
}
interface OnNumberChangeListener {
void onNumberChange(int num);
}
}