this.addView(l_view);//把l_view增加到当前容器 调用这个会崩溃?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<com.lkfdemo.customcontrol.myControls.InputNumberView
android:layout_width="match_parent"
android:layout_height="250dp"/>
</LinearLayout>
---------------
<?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:id="@+id/btn_plus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"/>
<EditText
android:id="@+id/et_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:text="10"/>
<Button
android:id="@+id/btn_minus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"/>
</LinearLayout>
-----------------
package com.lkfdemo.customcontrol.myControls;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import com.lkfdemo.customcontrol.R;
// 右键 copy /paste Special -> Copy Reference
public class InputNumberView extends RelativeLayout {
private int f_number;
private View g_btnminus;
private View g_btnPlus;
private EditText g_etValue;
public InputNumberView(Context context) {
this(context,null);
}
public InputNumberView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public InputNumberView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
setUpEvent();
}
/*设置事件
*/
private void setUpEvent() {
g_btnminus.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
f_number--;
upDataText();
}
});
g_btnPlus.setOnClickListener(v -> {
f_number=f_number+5;
upDataText();
});
}
private void initView(Context context) {
//LayoutInflater.from(context).inflate(R.layout.input_number_view, this);//最后一个参数默认为true
View l_view = LayoutInflater.from(context).inflate(R.layout.input_number_view, this, true);
//this.addView(l_view);//把l_view增加到当前容器 调用这个会崩溃!!???????????
g_btnminus = findViewById(R.id.btn_minus);
g_btnPlus = findViewById(R.id.btn_plus);
g_etValue = findViewById(R.id.et_value);
}
public int getF_number() {
return f_number;
}
public void setF_number(int p_value) {
this.f_number = p_value;
upDataText();
}
private void upDataText() {
g_etValue.setText(String.valueOf(f_number));
}
}
您的每一个用心回答,都会让这个世界变得更美好一些!