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

时间:2018-09-15 13:23:56

标签: android android-layout android-view

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

  • CustomViewBaseClass
  • CustomViewOne扩展了CustomViewBaseClass
  • CustomViewTwo扩展了CustomViewBaseClass
  • CustomViewThree扩展了CustomViewBaseClass

在布局文件中,我如下添加了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

如何执行此运行时?

2 个答案:

答案 0 :(得分:1)

将它们投射到CustomViewBaseClass可以简化处理过程:

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

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

否则,总是需要用instanceof检查他们的课程。

答案 1 :(得分:0)

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);