1.自定义view
2.在xml中写入控件
3.写入一个布局 (+,- 数字)
第一步:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#a19999" android:orientation="horizontal"> <TextView android:id="@+id/jia_jian" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:gravity="center" android:text="-" android:textColor="#fff" android:textSize="20sp" /> <TextView android:id="@+id/jia" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:gravity="center" android:text="1" android:textColor="#fff" android:textSize="20sp" /> <TextView android:id="@+id/jia_jia" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="5dp" android:gravity="center" android:text="+" android:textColor="#fff" android:textSize="20sp" /> </LinearLayout>
第二步:
public AddView(Context context) { this(context, null); } public AddView(Context context, AttributeSet attrs) { this(context, attrs, -1); } public AddView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //找控件 initView(context); //监听 initListener(); } private void initView(Context context) { rootView = View.inflate(context, R.layout.jia_jian, this); jia_jian = rootView.findViewById(R.id.jia_jian); jia_jia = rootView.findViewById(R.id.jia_jia); jia = rootView.findViewById(R.id.jia); // jia.setText("1"); } private void initListener() { //加 jia_jia.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { add(); } }); //减 jia_jian.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { jian(); } }); } private void add() { String s = jia.getText().toString(); int i = Integer.parseInt(s); i++; setCurrentCount(i); } private void jian() { String s = jia.getText().toString(); int i = Integer.parseInt(s); if (i > 1) { i--; setCurrentCount(i); } else { Toast.makeText(getContext(), "不能再减少了", Toast.LENGTH_SHORT).show(); } } public void setCurrentCount(int i) { jia.setText(""+i); if (onNumChangeListener != null) { onNumChangeListener.onNumChanged(this, i); } } //接口 private OnNumChangeListener onNumChangeListener; public void setOnNumChangeListener(OnNumChangeListener onNumChangeListener) { this.onNumChangeListener = onNumChangeListener; } public interface OnNumChangeListener { void onNumChanged(View view, int curNum); }
第三步:
把控件写入布局