android - 创建自定义 View

标签 android android-ui

我想创建一个自定义 View TestView 类,我可以通过 new TestView() 为其创建对象。 然而,一个新的 View 类需要一个 AttributeSet 对象。我从哪里获得该 AttributeSet 以及它必须包含什么?

最佳答案

这不是强制性的,大多数时候你甚至不必担心它,只要你从 View 提供构造函数并将它们传递给 super() .

public CustomView(Context context)  // No Attributes in this one.
{
  super(context);
  // Your code here
}

public CustomView(Context context, AttributeSet attrs)
{
  super(context, attrs);
  // Your code here
}

public CustomView(Context context, AttributeSet attrs, int default_style)
{
  super(context, attrs, default_style);
  // Your code here
}

View 负责处理您在将 View 添加到布局时通常传入的所有 android:* 属性。如果您定义了这些属性,您的构造函数可以使用这些属性或您自己的属性:

<com.blrfl.CustomView
 android:id="@+id/customid"
 android:layout_weight="1"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:layout_gravity="center"
 blrfl:foo="bar"
 blrfl:quux="bletch"
/>

关于android - 创建自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4418700/

相关文章:

android - 如何将一组图标导入 Android Studio 项目

java - 如何从文件的特定行读取

c# - Xamarin : Get MvxRecyclerView working

Android 通用应用方法

android - match_parent 并且未按预期填充 - Android/XML

android - 具有不均匀列大小或 Horizo​​ntal StaggeredGridView 的动态适配器 View

javascript - 单击react-native android时创建模式

android - Android 中用于通知的 XML 垂直线

android - 如何停止 Genymotion 虚拟设备?

android - 如何从子 Activity 完成父 Activity