android - 如何在android中动态更改自定义视图
问题描述
首先-我是android的新手。我创建了一些自定义视图类,如下所示。
- 自定义视图基类
- 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
如何做这个运行时?
解决方案
铸造它们CustomViewBaseClass
使处理不那么复杂:
CustomViewBaseClass customView = (CustomViewBaseClass) findViewById(R.id.cvone);
mLinearLayout.removeView(customView);
customView = (CustomViewBaseClass) new CustomViewTwo(MainActivity.this);
mLinearLayout.addView(customView);
因为否则,人们总是不得不用 . 检查他们的班级instanceof
。
推荐阅读
- node.js - 处理同一路径中的多个参数
- java - 在构建 maven 项目时避免在 jar 文件中绑定库
- python - Python pandas 用复杂计算迭代行的当前代码更快的方式
- r - 有没有办法绘制两个变量出现在 R 中的实例?
- javascript - 需要给定正则表达式的负版本(JS)
- java - Spring Boot Bitbucket Pilpline 到 ECR
- powershell - 使用 CMD 为文件夹中所有文件的最后修改日期生成日志?
- python - Python 类变量在 while 循环内不更新。(同一类中具有另一个函数的线程正在更改它们)
- java - 说话失败:尝试阅读文本时未绑定到 TTS 引擎
- python - 有人可以解释为什么会这样吗