【问题标题】:How to show a layout into another view by programming?如何通过编程将布局显示到另一个视图中?
【发布时间】:2020-09-15 14:09:00
【问题描述】:

我正在尝试扩展布局并将其显示给视图组。我该怎么做?

我在资源/布局目录中有我的自定义布局文件target_view_layout.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"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
        android:id="@+id/targetCardViewId"
...

在activity.xml 文件中我有一个视图:

...

<View
            android:id="@+id/targetViewId"
            android:layout_width="0dp"
            android:layout_height="150dp"
...

内部活动java文件我试过这个:

        private View targetView;
        targetView = findViewById(R.id.targetViewId);

        LayoutInflater layoutInflater = getLayoutInflater();
        targetView = layoutInflater.inflate(R.layout.target_view_layout,null);

如何将膨胀的视图附加到 targetView 中?

【问题讨论】:

  • 你到底想做什么?你的意思是把target_view_layout变成targetViewId
  • 是的。我正在尝试类似的东西
  • 那么targetView 需要是某种ViewGroup - 例如,&lt;FrameLayout&gt;&lt;LinearLayout&gt; 等 - 您可以使用以下内容将布局直接膨胀到其中:@ 987654332@, getLayoutInflater().inflate(R.layout.target_view_layout, targetView);.
  • 你的意思是我必须在我的 activity.xml 文件中使用 而不是
  • 它必须是某种ViewGroup,因为普通的View 不能有孩子。有很多不同的ViewGroups 可用,所以选择最适合您的设计的。如果targetView 唯一要保存的是target_view_layout 的一份副本,那么&lt;FrameLayout&gt; 将是合适的。相反,如果您打算垂直堆叠其中几个,例如,&lt;LinearLayout&gt; 会更好。

标签: android android-studio


【解决方案1】:

我认为您的意图是将 target_view_layout.xml 膨胀到您的活动布局视图中,ID 为 targetViewId,如果是这种情况,请尝试,

    private View targetView;
            targetView = findViewById(R.id.targetViewId);

            LayoutInflater layoutInflater = getLayoutInflater();
            View child = layoutInflater.inflate(R.layout.target_view_layout,null);
            targetView.add(child);

【讨论】:

  • 找不到 targetView.add(child),没有这个方法。
  • 这可能是您的自定义视图不是容器/父级。让您的自定义视图扩展 Android 容器类之一,例如 RelativeLayout 或 ConstraintLayout。
  • 通过在activity.xml 文件和采用private LinearLayout targetView 的java 文件中将&lt;View&gt; 替换为&lt;LinearLayout&gt; 解决了问题。但是如何将 View 扩展到容器类?
  • @philoopher97 您可以创建自己的自定义视图来扩展容器视图。看看这个链接stackoverflow.com/a/11198222/6561178
【解决方案2】:

您当前的代码只是将膨胀视图分配给变量 targetView,您要做的是在 targetView 中添加膨胀视图 使用 View.add(View view) 函数来实现

private View targetView;
private View view;
targetView = findViewById(R.id.targetViewId);

LayoutInflater layoutInflater = getLayoutInflater();
view = layoutInflater.inflate(R.layout.target_view_layout,null);
targetView.add(view)'

【讨论】:

  • 找不到 targetView.add()。 targetView 中没有这样的方法。
  • 只需使用任何视图组(FrameLayout、LinearLayout 等)代替您在 XML 中的视图
  • 通过将 activity.xml 文件中的 替换为 以及采用私有 LinearLayout targetView 的 java 文件解决了问题。谢谢你的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多