Creating Custom Views

来源:互联网 发布:过期未注册域名查询 编辑:程序博客网 时间:2024/04/30 22:43

Creating a View Class

subclass a View

A constructor that takes a Context and a AttributeSet object as parameters allows the layout editor create and edit an instance of your view.

class PieChart extends View {    public PieChart(Context context, AttributeSet attrs) {        super(context, attrs);    }}

Define Custom Attributes

  1. Define custom attributes in a < declare-styleable> resource element. It’s customary to put these resources into a res/values/attrs.xml file.
<resources>   <declare-styleable name="PieChart">       <attr name="showText" format="boolean" />       <attr name="labelPosition" format="enum">           <enum name="left" value="0"/>           <enum name="right" value="1"/>       </attr>   </declare-styleable></resources>
  1. Specify values for the attributes in your XML layout. Once you define the custom attributes, you can use them in layout XML files just like built-in attributes. The only difference is that your custom attributes belong to a different namespace. Instead of belonging to the http://schemas.android.com/apk/res/android namespace, they belong to http://schemas.android.com/apk/res/[your package name]. The tag name is the fully qualified name of the custom view class. If your view class is an inner class, you must further qualify it with the name of the view’s outer class, just like com.example.customviews.charting.PieChart$PieView
  2. Retrieve attribute values at runtime
  3. Apply the retrieved attribute values to your view
0 0
原创粉丝点击