Android之Button自訂點擊效果

來源:互聯網
上載者:User

                我們在介面上經常會用到button按鈕,但通常button點擊後看不到點擊的效果,如果使用者連續點擊了兩次,就會報NAR錯誤,這樣互動性就比較差了。如果我們自訂了button點擊效果,比如我們點擊了button能讓我們看到我們確實點擊了button按鈕,這樣就會有效避免重複點擊了。

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

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

             在drawable下建立selector.xml檔案:

         

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

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

     

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

   

<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button效果示範" android:background="@drawable/selector" /> 

          在MainActivtiy中得到button

    

Button button1=(Button) this.findViewById(R.id.button1);        button1.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubToast.makeText(getApplicationContext(), "你點擊了button按鈕", Toast.LENGTH_SHORT).show();}});

            下面看下點擊效果:

           點擊button前:

     

       當按下button按鈕時:

      

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

        首先在main.xml中添加:

     

<Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button效果示範" android:background="@drawable/button_nomal"/>

        
  接下面在MainActivity中實現:

    

 Button button2=(Button) this.findViewById(R.id.button2);        button2.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {// TODO Auto-generated method stubif(event.getAction()==MotionEvent.ACTION_DOWN){v.setBackgroundResource(R.drawable.button_press);}else if(event.getAction()==MotionEvent.ACTION_UP){v.setBackgroundResource(R.drawable.button_nomal);}return false;}});

          在這類綁定了button的OnTouchListener監聽,因為OnClickListener繼承了OnTouchListener。運行效果和上面一樣,這裡不做過多解釋。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.