如何在 android 中动态更改自定义视图

How to change the custom view dynamically in android

首先 - 我是 android 的新手。我创建了一些自定义视图 类,如下所示。

在我的布局文件中,我添加了 CustomViewOne,如下所示

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.test.custom.CustomViewOne
        android:id="@+id/cvone"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:visibility="visible" />

</LinearLayout>

正如预期的那样工作正常。

但我想在某些事件(按钮点击等...)中用 CustomViewTwo/CustomViewThree 动态替换此 CustomViewOne

如何做到 运行 次?

LinearLayout parent = findViewById(R.id.parent);
CustomViewOne customViewOne = findViewById(R.id.cvone);
parent.removeView(customViewOne);

//Now Add your CustomViewTwo
CustomViewTwo customViewTwo = new CustomViewTwo(YourActivity.this);
parent.addView(customViewTwo);

将它们转换为 CustomViewBaseClass 使处理不那么复杂:

CustomViewBaseClass customView = (CustomViewBaseClass) findViewById(R.id.cvone);
mLinearLayout.removeView(customView);

customView = (CustomViewBaseClass) new CustomViewTwo(MainActivity.this);
mLinearLayout.addView(customView);

因为否则,人们总是需要用 instanceof 来检查他们的 class。