【问题标题】:Why couldn't I add a costume view to LinearLayout?为什么我不能向 LinearLayout 添加服装视图?
【发布时间】:2021-12-30 17:43:01
【问题描述】:

在过去的几个小时里,我一直在为向 LinearLayout 添加一个简单的客户视图而苦苦挣扎。我在 SO 上找到了几种解决方案,但大多数答案相对不完整,提供了布局模型替代方案,为 OP 工作但不适合我等。我不是 Android 开发人员,而是偶尔开发一些应用程序。我真的需要一些帮助。

视图类

package com.android2d.supportclass;
public class Shapes extends View {
    Paint paint;

    public Shapes(Context context) {
        super(context);
  }
 protected void onDraw(Canvas canvas) {
  ..
   ..

    }
  }

活动

   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new Shapes(this));
      
    }

它们工作得很好(没有那个activity_main.xml)。但是现在如果我修改它,创建那个activity_main.xml:

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".a0_5_PercobaanWithSpaces">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ScrollView
            android:id="@+id/scrollview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <com.android2d.supportclass.Shapes
                    android:id="@+id/mview"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

            </LinearLayout>
        </ScrollView>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

并将我的活动修改为

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main)     
 
}

然后应用程序运行,但客户类中的任何内容都没有出现。这应该很容易,不是吗?我的错误可能是什么?

【问题讨论】:

  • 您需要在Shapes 中实现其余的View 构造函数,尤其是两个参数的构造函数。
  • @CommonsWare。好的 。我从本网站某处的答案中想起了其他构造函数。我稍后会实施它们并向您报告。我要休息了。谢谢

标签: java android android-layout layout


【解决方案1】:

您没有显示自定义视图的所有代码,但我认为根本问题是您没有代码来衡量您的视图。当您使用视图设置内容时,它会填满屏幕,因为它是顶级视图。一旦你把它放到一个LinearLayout中并指定wrap_content,你就必须告诉布局你的自定义视图有多大。 (对此的快速测试是在 XML 中显式设置视图的宽度和高度,例如高度为500dp。)

网上有很多关于如何编写自定义视图的资源。 here 是讨论测量自定义视图的问题。

您还应该为 ConstraintLayout 的所有直接子级指定约束,并避免使用 match_parent,因为不鼓励使用它。

【讨论】:

  • 嗨,我认为这就是问题所在。测量视图的排序。就像“它已经在那里,但视图大小、约束等禁止它被看到”。但我没有时间充分调查它(有点忙)所以现在坚持下去。暂时 +1。
猜你喜欢
  • 2012-08-08
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 2020-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多