自定义加减器
作者:互联网
- 自定义MyView 继承LinearLayout
package com.bw.shoppingpractice;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MyView extends LinearLayout implements View.OnClickListener {
private Button add;
private Button jian;
private TextView textView;
private int i=1;
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.myview,this);
add = findViewById(R.id.button1);
jian = findViewById(R.id.button2);
textView = findViewById(R.id.text1);
add.setOnClickListener(this);
jian.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
i++;
textView.setText("" + i);
break;
case R.id.button2:
if (i > 1) {
i--;
textView.setText("" + i);
} else
{
Toast.makeText(getContext(),"不能再减了",Toast.LENGTH_SHORT).show();
}
break;
}
}
}
1.在你需要的地方写上布局
<com.bw.shoppingpractice.MyView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="70dp"
android:id="@+id/myview"
></com.bw.shoppingpractice.MyView>
- 加减器的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<Button
android:layout_width="50dp"
android:layout_height="50dp"
android:text="+"
android:id="@+id/button1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:textSize="25dp"
android:id="@+id/text1"
/>
<Button
android:layout_width="50dp"
android:layout_height="50dp"
android:text="-"
android:id="@+id/button2"
/>
</LinearLayout>
标签:自定义,加减器,private,public,context,import,android,id 来源: https://blog.csdn.net/weixin_44329686/article/details/89010296