【问题标题】:Setting layout of a CustomView based on user input根据用户输入设置 CustomView 的布局
【发布时间】:2016-04-05 18:55:34
【问题描述】:

我有一个扩展RelativeLayout 的自定义视图。在该类的 init(Context context, AttributeSet attrs) 方法中,我通过以下方式设置布局文件:

inflate(getContext(), R.layout.in_session_view_layout, this);

我在这样的列表项中使用这个自定义视图:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:verizon="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_margin="5dp">

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center">

    <ImageView
        android:id="@+id/flag"
        android:layout_width="60dp"
        android:layout_height="160dp"
        android:layout_below="@id/txt"
        android:layout_gravity="center"
        android:layout_margin="5dp" />

</FrameLayout>

    <com.widgets.FreeBeeNotificationView
        android:id="@+id/freebee_pre_session_view"
        android:layout_width="wrap_content"
        android:layout_height="35dp"
        android:layout_gravity="right|top"
        android:layout_marginBottom="6dp"
        android:layout_marginRight="6dp"
        android:layout_marginTop="6dp"
        verizon:textSize="12sp" />

</FrameLayout>

现在,要求是,需要根据用户输入在自定义视图中动态设置此布局文件。但是,在自定义视图的 init() 方法已经被调用后,我收到了用户输入,因为一旦加载了上面给出的 FrameLayout,这个方法就会被调用。

如何根据用户输入将布局文件动态设置为自定义视图?谁能帮帮我。

谢谢。

【问题讨论】:

  • 您需要先对 R.layout.in_session_view_layout 进行膨胀,然后当用户输入到达时再对另一个布局进行膨胀,还是在用户输入到达后只需对 R.layout.in_session_view_layout 进行膨胀?
  • 我有 2 种布局:R.layout.in_session_view_layout_1 和 R.layout.in_session_view_layout。用户输入到达后,任何一个都需要在视图中膨胀。

标签: android android-layout android-custom-view


【解决方案1】:

希望我正确理解了您的要求。如果不是,请进一步解释。 你可以这样做。

在您的自定义视图中创建一个名为 setLayout(int layoutId) 的方法

public void setLayout(int layoutId)
{
     removeAllViews();
     LayoutInflater inflater = LayoutInflater.from(getContext());
     inflater.inflate(getContext(), layoutId, this);
}

当你有你的用户输入时,你调用

yourCustomView.setLayout(R.layout.new_layout);

免责声明:所有这些都来自内存,未经测试,因此可能无法编译。

【讨论】:

  • 所以,在 init() 方法中我将设置任何一个布局文件。然后根据用户输入覆盖之前的布局;通过使用 setLayout 方法对吗?
  • 是的,removeAllViews 删除了自定义相对布局的所有子视图,因此您拥有一个干净的视图组,您可以在其上添加新布局。请注意,如果您只是使用一些不需要复杂逻辑的静态布局,这应该可以按预期工作。对于更复杂的场景,您可能需要根据您的要求使用 ViewPager 或 ViewFlipper 或其他。
猜你喜欢
  • 2017-05-28
  • 1970-01-01
  • 2022-06-29
  • 1970-01-01
  • 2014-06-29
  • 2011-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多