Creating Custom Views

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">Creating Custom Views</span>

A well-designed custom view is much like any other well-designed class. In addition to being a well-designed class, though, a custom view should:

a> Conform to Android standards

b> Provide custom styleable attributes that work with Android XML layouts

c> Send accessibility events

d> Be compatible with multiple Android platforms

Subclass a View

To allow the Android Developer Tools to interact with your view, at a minimum you must provide a constructor that takes a context and an attribute set object as parameters. This constructor allows the layout editor to create and edit an instance of your view.

public class PieChart extends View {

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

}

Define Custom Attributes

Well-written custom views can also be added and styled via XML. To enable this behavior in your custom view, you must:

a> Define custom attributes for your view in a <declare-styleable> resource element

b> Specify values for the attributes in your XML layout

c> Retrieve attribute values at runtime

d> Apply the retrieved attribute values to your view

To define custom attributes, add <declare-styleable> resources to your project. 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="labelPositon" format="enum">
            <enum name="left" value="0" />
            <enum name="right" value="1" />
        </attr>
    </declare-styleable>

</resources>
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. You can choose any alias you want for your namespace.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res/com.demo.view.custom"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.demo.view.custom.PieChart
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:labelPositon="left"
        app:showText="true" />

</RelativeLayout>
Notice the name of the XML tag that adds the custom view to the layout, which is the fully qualified name of the custom view class.

Apply Custom Attributes

When a view is created from an XML layout, all of the attributes in the XML tag are read from the resource bundle and passed into the view's constructor as an attribute set object. Then, pass the attribute set object to obtainStyledAttributes(), which passes back a typed array object which is an array of values that have already been dereferenced and styled.

Note that TypedArray objects are a shared resource and must be recycled after use.

Add Properties and Events

Attributes are a powerful way of controlling the behavior and appearance of views, but they can only be read when the view is initialized. To provide dynamic behavior, expose a property getter and setter pair for each custom attribute.

Notice the setter should call invalidate() and requestLayout(). These calls are crucial to ensure that the view behaves reliably.

Custom views should also support event listeners to communicate important events.

   It's easy to forget to expose properties and events, especially when you're the only user of the custom view. A good rule to follow is to always expose any property that affects the visible appearance or behavior of your custom view.

Custom Drawing

The most important part of a custom view is its appearance.

Override onDraw()

The most important step in drawing a custom view is to override the onDraw() method. The parameter to onDraw() is a canvas object that the view can use to draw itself.

Before you can call any drawing methods, though, it's necessary to create a paint object.

Create Drawing Objects

The android.graphics framework divides drawing into two areas:

a> What to draw, handled by Canvas

b> How to draw, handled by Paint

Simply put, Canvas defines shapes that you can draw on the screen, while Paint defines the color, style, font, and so forth of each shape you draw.

So, before you draw anything, you need to create one or more Paint objects.

Creating objects ahead of time is an important optimization as Views are redrawn very frequently and many drawing objects require expensive initialization.

Handle Layout Events

In order to properly draw your custom view, you need to know what size it is. You should never make assumptions about the size of your view on the screen.

If your view doesn't need special control over its size, you only need to override one method: onSizeChanged(), which is called when your view is first assigned a size, and again if the size of your view changes for any reason.

When your view is assigned a size, the layout manager assumes that the size includes all of the view's padding. You must handle the padding values when you calculate your view's size.

If you need finer control over your view's layout parameters, implement onMeasure().

There are three important things to note in this method:

a> The calculations take into account the view's padding.

b> The helper method resolveSizeAndState() is used to create the view's desired size to the spec passed into onMeasure().

c> onMeasure() has no return value. Instead, the method communicates its result by calling setMeasuredDimension(). Calling this method is mandatory. If you omit this call, the view class throws a runtime exception.

Drawing

Every view implements onDraw() differently, but there are some common operations that most views share:

a> Draw text using drawText().

b> Draw primitive shape using drawRect(), drawOval(), and drawArc().

c> Draw more complex shapes using the Path class.

d> Define gradient fills by creating LinearGradient objects. Call setShader() to use your LinearGradient on filled shapes.

e> Draw bitmaps using drawBitmap().

Making the View Interactive

Drawing a UI is only one part of creating a custom view. You also need to make your view respond to user input in a way that closely resembles the real-world action you're mimicking. Objects should always act in the same way that real objects do.

Handle Input Gestures

Android supports an input event model. User actions are turned into events that trigger callbacks, and you can override the callbacks to customize how your application responds to the user. The most common input event in the Android system is touch, which triggers onTouchEvent(android.view.MotionEvent).

Touch events by themselves are not particularly useful. To convert raw touch events into gestures, Android provides GestureDetector.

When you pass onTouchEvent() a touch event that it doesn't recognize as part of a gesture, it returns false.

Create Physically Plausible Motion

Make Your Transitions Smooth

Optimizing the View

To avoid a UI that feels sluggish or stutters during playback, ensure that animations consistently run at 60 frames per second.

Do Less, Less Frequently

In particular you should eliminate allocations in onDraw(), because allocations may lead to a garbage collection that would cause a stutter.

Another very expensive operation is traversing layouts.

1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看REAdMe.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看REAdMe.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看READme.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 、 1资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看READmE.文件(md如有),本项目仅用作交流学习参考,请切勿用于商业用途。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值