首先-我是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
如何执行此运行时?
答案 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);