怎么在继承View的类中怎么添加一个其他控件,例如button;或者是当继承View的类作为Activity的自定义控件时候,Activity怎么给View类传值???
该回答引用ChatGPT
要在继承自View的类中添加其他控件,例如Button,可以通过在构造函数中创建一个新的Button对象,并将其添加到View的布局中,例如:
public class CustomView extends View {
private Button mButton;
public CustomView(Context context) {
super(context);
mButton = new Button(context);
mButton.setText("Click me");
// 设置Button的布局参数
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mButton.setLayoutParams(layoutParams);
// 将Button添加到View中
addView(mButton);
}
}
要在自定义View中接收来自Activity的值,可以使用自定义属性和XML布局文件。首先,在res/values/attrs.xml文件中定义自定义属性:
<resources>
<declare-styleable name="CustomView">
<attr name="customValue" format="integer" />
</declare-styleable>
</resources>
接下来,在CustomView的构造函数中获取自定义属性的值:
public class CustomView extends View {
private int mCustomValue;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
mCustomValue = a.getInteger(R.styleable.CustomView_customValue, 0);
a.recycle();
}
}
最后,在XML布局文件中使用自定义View时,可以设置自定义属性的值:
<com.example.CustomView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:customValue="123" />
在Activity中使用自定义View时,可以像使用其他控件一样访问它,并设置自定义属性的值:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomView customView = findViewById(R.id.customView);
customView.setCustomValue(456);
}
}