【问题标题】:Create a dynamic Custom View in Android在 Android 中创建动态自定义视图
【发布时间】:2015-03-16 09:11:01
【问题描述】:
我需要在我的应用程序中生成一个动态自定义视图。
我需要一个由一个图像按钮和 2 个文本视图组成的自定义视图,在按钮上方和下方。图片按钮上还应该有一个 onClick 监听器,当按下时会调用一个函数。
我所说的动态是指将按需创建这些视图,应该有一个“虚拟”结构,我应该能够从中创建我需要的任意数量的自定义视图。
我该怎么做?
【问题讨论】:
标签:
android
android-activity
android-custom-view
【解决方案1】:
只需使用 xml 为您的视图创建布局,然后使用布局充气器:
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View yourView = inflater.inflate(R.layout.view_layout, parent, false);
要访问它的组件,请使用:
ImageButton imageButton = (ImageButton) yourView.findViewById(R.id.button);
【解决方案2】:
您可以从创建扩展 View 类的自定义视图类 MyCustomView 开始。为自定义视图创建一个单独的 XML 布局(虚拟结构)并将其膨胀到自定义视图构造函数中,
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.my_custom_view_layout, this, true);
您可以将任何侦听器添加到将成为此复合视图类的一部分的 Button 视图。看看这个链接进一步了解:http://www.vogella.com/tutorials/AndroidCustomViews/article.html
最后,只要把这个对象当作一个视图,你就可以把它放在界面上任何你想要的地方。