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


原文地址: https://www.cveoy.top/t/topic/pqjN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录