首页 > 解决方案 > 带有 xml 的 CustomView 不显示在屏幕上

问题描述

我正在尝试将我的自定义视图添加到主要活动的 xml 中。我为视图创建了以下 xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Testing custom view"
        android:textSize="20dp" />
</LinearLayout>

并创建了以下类,其中上述 xml 被夸大:

public class TestView extends LinearLayout {
public TestView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    View.inflate(context, R.layout.test_name, null);

}

在主要活动的 xml 中,我添加了如下自定义视图:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication.MainActivity">

<com.example.myapplication.TestView
    android:id="@+id/submit_area"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</LinearLayout>

当我运行应用程序时,我得到一个空屏幕。它没有显示显示“测试自定义视图”的文本视图。任何帮助将不胜感激。谢谢

标签: androidxmlandroid-layoutandroid-activityandroid-linearlayout

解决方案


您的自定义视图中的视图膨胀代码看起来错误。请按照下面给出的方式尝试。

  LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.view_color_options, this, true);

推荐阅读