首页 > 解决方案 > 如何在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

如何做这个运行时?

标签: androidandroid-layoutandroid-view

解决方案


铸造它们CustomViewBaseClass使处理不那么复杂:

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

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

因为否则,人们总是不得不用 . 检查他们的班级instanceof


推荐阅读