android 约束布局实现自定义View的示例代码
下面是一个使用约束布局实现自定义View的示例代码:
首先,创建一个名为CustomView的自定义View类:
public class CustomView extends ConstraintLayout {
private TextView textView;
private Button button;
public CustomView(Context context) {
super(context);
init();
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.custom_view_layout, this, true);
textView = findViewById(R.id.textView);
button = findViewById(R.id.button);
// 设置布局参数
LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
setLayoutParams(layoutParams);
}
public void setText(String text) {
textView.setText(text);
}
public void setButtonText(String text) {
button.setText(text);
}
}
然后,在res目录下创建一个名为custom_view_layout.xml的布局文件,用于定义自定义View的外观和布局:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@id/button"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click"
app:layout_constraintTop_toBottomOf="@id/textView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
最后,在使用自定义View的布局文件中添加CustomView:
<com.example.myapplication.CustomView
android:id="@+id/customView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"/>
通过在代码中调用customView.setText("Hello World!");和customView.setButtonText("Click Me!");来设置CustomView的文本内容。
希望对你有所帮助
原文地址: https://www.cveoy.top/t/topic/hHbp 著作权归作者所有。请勿转载和采集!