自定義Button效果

咱們在界面上常常會用到button按鈕,但一般button點擊後看不到點擊的效果,若是用戶連續點擊了兩次,就會報NAR錯誤,這樣交互性就比較差了。若是咱們自定義了button點擊效果,好比咱們點擊了button能讓咱們看到咱們確實點擊了button按鈕,這樣就會有效的避免重複點擊了。

              自定義點擊效果有兩種方式,一種是在xml中定義,另外一種是在代碼中定義。 android

             首先看一下如何在xml中定義: ide

             在drawable下新建selector.xml文件: this

          

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.   
  4.     <item android:drawable="@drawable/button_press" android:state_pressed="true"/>  
  5.     <item android:drawable="@drawable/button_nomal" android:state_focused="false" android:state_pressed="false"/>  
  6.     <item android:drawable="@drawable/button_focus"  android:state_focused="true"/>  
  7.     <item android:drawable="@drawable/button_nomal" android:state_focused="false"/>  
  8.   
  9. </selector>  

     定義了兩種狀態 一種是按下  一種是得到焦點。  drawable分別引用了這三張圖片

 

\

      

      而後在main.xml下添加button按鈕 xml

   

  1. <Button  
  2.  android:id="@+id/button1"  
  3.  android:layout_width="wrap_content"  
  4.  android:layout_height="wrap_content"  
  5.  android:text="button效果演示"  
  6.  android:background="@drawable/selector" />   

          在MainActivtiy中獲得button

 

    

  1. Button button1=(Button) this.findViewById(R.id.button1);  
  2.         button1.setOnClickListener(new View.OnClickListener() {  
  3.               
  4.             @Override  
  5.             public void onClick(View v) {  
  6.                 // TODO Auto-generated method stub  
  7.                 Toast.makeText(getApplicationContext(), "你點擊了button按鈕", Toast.LENGTH_SHORT).show();  
  8.             }  
  9.         });  

            下面看下點擊效果:

 

           點擊button前: 繼承

      \

       當按下button按鈕時: 圖片

       \

         接下來 看下第二種實現方式,在代碼中實現: utf-8

        首先在main.xml中添加: get

     

  1. <Button  
  2.      android:id="@+id/button2"  
  3.      android:layout_width="wrap_content"  
  4.      android:layout_height="wrap_content"  
  5.      android:text="button效果演示"  
  6.      android:background="@drawable/button_nomal"/>  
         
  接下面在MainActivity中實現:

 

    

  1. Button button2=(Button) this.findViewById(R.id.button2);  
  2.        button2.setOnTouchListener(new OnTouchListener() {  
  3.           
  4.         @Override  
  5.         public boolean onTouch(View v, MotionEvent event) {  
  6.             // TODO Auto-generated method stub  
  7.             if(event.getAction()==MotionEvent.ACTION_DOWN){  
  8.                 v.setBackgroundResource(R.drawable.button_press);  
  9.             }else if(event.getAction()==MotionEvent.ACTION_UP){  
  10.                 v.setBackgroundResource(R.drawable.button_nomal);  
  11.             }  
  12.             return false;  
  13.         }  
  14.     });  
          在這類綁定了button的OnTouchListener監聽,由於OnClickListener繼承了OnTouchListener。運行效果和上面同樣,這裏不作過多解釋。
相關文章
相關標籤/搜索