android - 带有 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>
当我运行应用程序时,我得到一个空屏幕。它没有显示显示“测试自定义视图”的文本视图。任何帮助将不胜感激。谢谢
解决方案
您的自定义视图中的视图膨胀代码看起来错误。请按照下面给出的方式尝试。
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.view_color_options, this, true);
推荐阅读
- react-native - 在 ItemSeparatorComponent 中使用索引
- python - pyinstaller 要求在 venv 和 -p 中确实提供了依赖项
- python - 如何允许 iframe 从 Django 网站访问其他网站?
- sql - INNER JOIN 的语法性能
- python - 鼠标悬停在破折号中的事件回调,python
- javascript - 默认使用 @rollup/plugin-commonjs 从 CJS 模块导入导出
- python - 在数据框中将句子列表连接成一个
- javascript - Babel 支持浏览器 11
- asp.net - Asp.net 将奇怪的编码字符添加到 url
- android - 如何拥有可点击的背景视图,这不会导致在其顶部的视图上单击事件?