如何在Android Studio预览窗口中显示使用合并标记创建的自定义视图
当我有一个包含自定义视图的布局时,如何让自定义视图的内容显示在Android Studio的预览窗口中 我有一个基于LinearLayout的自定义视图:如何在Android Studio预览窗口中显示使用合并标记创建的自定义视图,android,android-studio,android-layout,Android,Android Studio,Android Layout,当我有一个包含自定义视图的布局时,如何让自定义视图的内容显示在Android Studio的预览窗口中 我有一个基于LinearLayout的自定义视图: class MyCustomView:LinearLayout { constructor(context:Context?):super(context) constructor(context:Context?, attrs:AttributeSet?):super(context, attrs) {
class MyCustomView:LinearLayout {
constructor(context:Context?):super(context)
constructor(context:Context?, attrs:AttributeSet?):super(context, attrs) {
initialize(context, attrs)
}
constructor(context:Context?, attrs:AttributeSet?, defStyleAttr:Int):super(context, attrs, defStyleAttr) {
initialize(context, attrs)
}
constructor(context:Context?, attrs:AttributeSet?, defStyleAttr:Int, defStyleRes:Int):super(context, attrs, defStyleAttr, defStyleRes) {
initialize(context, attrs)
}
fun initialize(context:Context?, attrs:AttributeSet?) {
LayoutInflater.from(context).inflate(R.layout.my_custom_view_layout, this)
}
}
它膨胀根为
标记的布局:
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:parentTag="LinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/message_display"
android:text="hello world"
/>
</merge>
我将视图作为元素包含在主布局文件中:
<LinearLayout 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"
android:orientation="vertical">
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/txt_before"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="before"/>
<com.my.app.MyCustomView
android:id="@+id/custom_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/txt_after"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="before"/>
</LinearLayout>
在预览窗口中查看主布局时,自定义视图的内容不可见。我希望能够看到我的自定义视图,包括“hello world”文本字段。如何实现这一点?您可以尝试重建项目,但我认为您需要以编程方式添加其他视图
CustomLayout extends LinearLayout{
public CustomLayout(Context context) {
super(context);
//Add your view to this layout
this.add(new MyCustomFirstView());
//Add other views the same way and customize LayoutParams here...
}
}
我希望有帮助:)