自定義控制元件 加減器
阿新 • • 發佈:2018-12-25
package com.sn.shopcat; import android.content.Context; import android.support.annotation.Nullable; 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:易宸鋒(dell) * function:組合式自定義控制元件簡易版 */ public class MyAddSubView extends LinearLayout implements View.OnClickListener { private int number = 1; private TextView sub_tv; private TextView product_number_tv; private TextView add_tv; public MyAddSubView(Context context) { this(context, null); } public MyAddSubView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public MyAddSubView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); View view = inflate(context, R.layout.add_remove_view_layout, this); sub_tv=view.findViewById(R.id.sub_tv); product_number_tv=view.findViewById(R.id.product_number_tv); add_tv=view.findViewById(R.id.add_tv); sub_tv.setOnClickListener(this); add_tv.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.sub_tv: if (number > 1) { --number; product_number_tv.setText(number + ""); if (onNumberChangeListener != null) { onNumberChangeListener.onNumberChange(number); } } else { Toast.makeText(getContext(), "不能再少了", Toast.LENGTH_SHORT).show(); } break; case R.id.add_tv: ++number; product_number_tv.setText(number + ""); if (onNumberChangeListener != null) { onNumberChangeListener.onNumberChange(number); } break; } } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; product_number_tv.setText(number + ""); } OnNumberChangeListener onNumberChangeListener; public void setOnNumberChangeListener(OnNumberChangeListener onNumberChangeListener) { this.onNumberChangeListener = onNumberChangeListener; } interface OnNumberChangeListener { void onNumberChange(int num); } }
佈局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:padding="2dp" android:layout_width="60dp" android:layout_height="30dp" android:background="#99000000"> <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:id="@+id/add_tv" android:layout_width="wrap_content" android:layout_height="30dp" android:layout_marginLeft="2dp" android:layout_weight="1" android:background="#ffffff" android:gravity="center" android:text="+" android:textSize="16sp" /> </LinearLayout>