The simplest single picture of a custom control in history implements the Click Effect of the button (Rai) _ Easiest Custom view

Source: Internet
Author: User

Custom controls may not be easy for beginners who have never contacted a custom control, in fact, sometimes the custom control is not so difficult, learning this thing is from easy to difficult, from the primary school A, O, E to this year's college entrance examination of Reading comprehension of "a delicious" is it, or for example, from the primary school of A, B, C, D to high school foreign Heavenly book, alas, do not say, said more are tears, hate what Li Bai, Newton Ah, Archimedes ah some people are not people, the harm we can only give up the culture of learning to run over the code, alas, do not say, Palace big (next door PHP colleagues), give me some paper, wipe fast to the mouth of the snot tears. Pull far ah, said so much, learn no shortcuts, try, the years of the Sao.

Get to the point. We all know that Android's custom control has three kinds, one: Completely custom, is inherits our great view class, 1.1 points measurement, puts, draws, two kinds: the combination control; Three: Inherit the existing control class in Android to change or extend the function. And that's what I'm going to say today.

In the development, for a button, sometimes the design only gave us a background picture, and the product will we achieve this button click effect How to do it, of course, you can go to find the design to give you a piece or use PS to change color, you can. The road to the vast island-rich islands thousands, swim past, fly past all can do. Today I provide a custom control to achieve a single picture Click the way for everyone to reference, only for reference.

First we create a Java file that inherits from the button because we want to extend the button. To implement the related construction method, the code is as follows:

public class Haveclickeffectbutton extends Android.support.v7.widget.AppCompatButton {public
    Haveclickeffectbutton (context) {
        super (context);
    }

    Public Haveclickeffectbutton, @Nullable AttributeSet attrs) {
        Super (context, attrs);
    }

    Public Haveclickeffectbutton (context, @Nullable attributeset attrs, int defstyleattr) {
        Super (context, Attrs, defstyleattr);
    }

And then, because we're going to do things by clicking on the effect, so we're going to implement its ontouchevent (Motionevent event) method, which explains to you that this approach is an important approach to the Android event distribution process, Its role is to handle events, such as Longclick events, click events are triggered in this method, for the Android event distribution mechanism is not clear to see my article, I made a detailed summary of the Android event distribution mechanism from Activiy to Windows to the Viewgrop final arrival view. What do we rewrite the Ontouchevent (Motionevent event) method to do, look at the code first:

@Override Public
Boolean ontouchevent (Motionevent event) {
    switch (event.getactionmasked ()) {
        case Motionevent.action_down:
            if (isenabled ())
               Setviewalpha ();
            break;
        Case Motionevent.action_cancel:
             clearviewalpha ();
            break;
        Case MOTIONEVENT.ACTION_UP:
           if (isenabled ())
              PerformClick ();
            Clearviewalpha ();
           break;
    return true;
}

Analysis of this code, the great god around Ah, I captured three commonly used motionevent state, and Motionevent.action_down, Motionevent.action_cancel, motionevent.action_up , first when we click on a button first trigger down event, we first judge the current control is available, not to do any processing, if available, I do setviewalpha () operation, see name, this method is to set the current view transparency, look at the code:

private void Setviewalpha () {
    setalpha (0.8f);
}

Simply, without explanation, set the transparency of the current view to the original 80%. And then we do it multiple times when our fingers move, but we don't have to motionevent.action_move, it doesn't matter what the current function is, here's a mention of the control executing when we move out of the current view Motionevent.action_cancel Event, then we need to deal with this event, and if we don't deal with it, the problem is that our transparency changes at down, we have to recover, so we need to restore the background in this event, so we call the Clearviewalpha () method, and look at the implementation:

private void Clearviewalpha () {
    setalpha (1f);
}

We also have to deal with a state that is the user's normal click event when the case Motionevent.action_up event, in this event, in addition to restore the transparency of the view also to trigger the view of the Click event, and call the system PerformClick () method, Here our custom view is complete, let's try it and see the effect, we create our view in the XML layout file, as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "xmlns:tools=" Http://schemas.android.com/tools "android:layout_width=" Match_parent "Android:layout_hei ght= "Match_parent" tools:context= "com.jason.mybuttondemo.MainActivity" > <linearlayout android:layou T_width= "Match_parent" android:layout_height= "wrap_content" android:layout_margintop= "40DP" Androi d:orientation= "Horizontal" > <com.jason.mybuttondemo.haveclickeffectbutton android:id= "@+id/btn_ Cancel_order "android:layout_width=" 0DP "android:layout_height=" Wrap_content "Android:
            layout_weight= "1" android:background= "@drawable/btn_cancel_order" android:text= "Cancel Order" Android:textcolor= "@android: Color/white" android:textsize= "15DP"/> <com.jason.mybuttondemo.hav Eclickeffectbutton ANdroid:id= "@+id/btn_print_order" android:layout_width= "0DP" android:layout_height= "Wrap_content" android:layout_weight= "1" android:background= "@drawable/print_order" android:text= "Print order "Android:textcolor=" @android: Color/white "android:textsize=" 15DP "/> </linearlayout&gt

; </RelativeLayout>

The emphasis is on the Android:background property of the first control we set the selector file, which sets the picture to be displayed in two different states, as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <selector xmlns:android=
"http://schemas.android.com/apk/res/" Android ">
    <item android:drawable=" "@drawable/cancel_order_noclick" android:state_enabled= "false"/>
    <item android:drawable= "@drawable/cancel_order"/>
</selector>

The second set is a single picture, not a selector file, first of all, we are bound in the activity directly regardless of the state:

public class Mainactivity extends Appcompatactivity {

    @Override
    protected void OnCreate (Bundle Savedinstancestate) {
        super.oncreate (savedinstancestate);
        Setcontentview (r.layout.activity_main);
        Haveclickeffectbutton btn_cancel_order= (Haveclickeffectbutton) Findviewbyid (r.id.btn_cancel_order);
        Haveclickeffectbutton btn_print_order= (Haveclickeffectbutton) Findviewbyid (R.id.btn_print_order);
    }

Run a look at the effect:

Then we put the Cancel Order button's enable state in code to false, and look at the effect:

You can see that we set the selector file function effect came out, the button click Effect is gone, showing the background of our disable button.

I posted the entire view code:

Package Com.jason.mybuttondemo;
Import Android.content.Context;
Import android.support.annotation.Nullable;
Import Android.util.AttributeSet;

Import android.view.MotionEvent; /** * @Explain: Only the design of a background map has a click effect view; * @Author: Lyl * @Version: V2.0 * @Time: 2017/6/9/12:17 * * public class HAVECLICKEF
        Fectbutton extends Android.support.v7.widget.AppCompatButton {public Haveclickeffectbutton {
    Super (context);
    Public Haveclickeffectbutton, @Nullable AttributeSet attrs) {Super (context, attrs); Public Haveclickeffectbutton (context context, @Nullable attributeset attrs, int defstyleattr) {Super (conte
    XT, Attrs, defstyleattr);
            @Override public boolean ontouchevent (Motionevent event) {switch (event.getactionmasked ()) {
                Case MotionEvent.ACTION_DOWN:if (IsEnabled ()) Setviewalpha ();
            Break Case Motionevent.action_canCel:clearviewalpha ();
            Break
                Case MotionEvent.ACTION_UP:if (IsEnabled ()) PerformClick ();
                Clearviewalpha ();
        Break
    return true;
    private void Setviewalpha () {setalpha (0.8f);
    private void Clearviewalpha () {Setalpha (1f); }


}

Here, what I'm going to say today is over, a very simple thing, do you have a new understanding of the custom control?








Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.