安卓自定义视图,以在Java中动态插入到布局中
我经常强调这一点,我对Android和Java一般来说都是新手:-) 这些xml布局让我头疼
您看到的代码由RelativeLayout中的两个ImageView和两个TextView组成,它们一起构成了一个布局,对我来说,它是一个“自定义按钮”。当我复制并粘贴到我的布局中时,它几乎按照我想要的方式工作
当我需要这样的按钮时,如何在代码中动态地使用xml布局的这一部分,并且仍然能够更改某些属性,例如TextView中的文本
我希望你明白我的意思,我的第一语言不是英语
<RelativeLayout
安卓:layout_width="wrap_content"
安卓:layout_height="match_parent" >
<ImageView
安卓:id="@+id/myImageView"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_marginTop="20dp"
安卓:layout_marginLeft="10dp"
安卓:src="@drawable/box" />
<TextView
安卓:id="@+id/myImageViewText"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_alignBottom="@+id/myImageView"
安卓:layout_alignLeft="@+id/myImageView"
安卓:layout_alignRight="@+id/myImageView"
安卓:layout_alignTop="@+id/myImageView"
安卓:layout_margin="1dp"
安卓:gravity="center"
安卓:text="S-"
安卓:textColor="#000000"
安卓:textStyle="bold" />
<TextView
安卓:id="@+id/textView1"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_alignBottom="@+id/myImageViewText"
安卓:layout_centerHorizontal="true"
安卓:layout_marginBottom="25dp"
安卓:text="your turn!"
安卓:textAppearance="?安卓:attr/textAppearanceSmall" />
<ImageView
安卓:id="@+id/imageView2"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_above="@+id/textView1"
安卓:layout_alignParentTop="true"
安卓:layout_marginBottom="15dp"
安卓:layout_marginTop="-10dp"
安卓:cropToPadding="false"
安卓:src="@drawable/icon" />
</RelativeLayout>
# 1 楼答案
确定开始像这样扩展您自己的视图:
我确实有一个
Button
由ImageView
和TextView
组成的LinearLayout
用xml设计:XML
调用ViewObject
查看菜单按钮
每当您想在xml中使用它时,请确保为视图提供完整的包,如下所示:
使用XML
如果您想在代码中使用它,只需如下所示:
使用JAVA
您甚至可以更详细地定义自己的属性以在
XML
中使用,例如设置Image
的源、更改Text
、更改TextColor
等# 2 楼答案
创建自定义的
View
子类。在构造器中膨胀布局,在那里找到必要的视图,并创建必要属性的setter/getter。然后,每次需要这个自定义按钮时,都可以使用这个子类通过代码或xml创建它。如果您还需要能够更改xml中的某些属性,那么您可能需要为自定义视图声明可设置样式的属性。我想你可以找到很多关于如何创建自定义视图的教程这是常见的教程Here您可以阅读有关自定义属性的内容。最后here是我上面提到的最好的例子
# 3 楼答案
您可以膨胀布局并将其添加到其他布局
现在您可以在按钮布局中找到子视图,如下所示
然后可以更改内部子视图的值或属性