單擊Android上的按鈕效果

[英]click effect on button in Android


in android while I set background image to Button I can not see any effect on button. I need some effect on button so user can recognize that button is clicked. Button should be dark while a few second when it clicked , so what should I do for this ?

在android中,當我將背景圖像設置為Button時,我看不到對按鈕的任何影響。我需要對按鈕產生一些影響,以便用戶可以識別出該按鈕被單擊。按鈕應該是黑暗的,而在點擊時幾秒鍾,那么我應該為此做些什么呢?

10 个解决方案

#1


119  

This can be achieved by creating a drawable xml file containing a list of states for the button. So for example if you create a new xml file called "button.xml" with the following code:

這可以通過創建包含按鈕狀態列表的可繪制xml文件來實現。因此,例如,如果使用以下代碼創建名為“button.xml”的新xml文件:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/YOURIMAGE" />
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/gradient" />
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/gradient" />
    <item android:drawable="@drawable/YOURIMAGE" />
</selector>

To keep the background image with a darkened appearance on press, create a second xml file and call it gradient.xml with the following code:

要在背景中保持背景圖像的外觀變暗,請創建第二個xml文件,並使用以下代碼將其命名為gradient.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <bitmap android:src="@drawable/YOURIMAGE"/>
    </item>
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <gradient android:angle="90" android:startColor="#880f0f10" android:centerColor="#880d0d0f" android:endColor="#885d5d5e"/>
        </shape>
    </item>
</layer-list>

In the xml of your button set the background to be the button xml e.g.

在按鈕的xml中,將背景設置為按鈕xml,例如

android:background="@drawable/button"

Hope this helps!

希望這可以幫助!

Edit: Changed the above code to show an image (YOURIMAGE) in the button as opposed to a block colour.

編輯:更改上面的代碼以在按鈕中顯示圖像(YOURIMAGE)而不是塊顏色。

#2


63  

It is simpler when you have a lot of image buttons, and you don't want to write xml-s for every button.

當你有很多圖像按鈕時,它會更簡單,你不想為每個按鈕編寫xml-s。

Kotlin Version:

Kotlin版本:

fun buttonEffect(button: View) {
    button.setOnTouchListener { v, event ->
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                v.background.setColorFilter(-0x1f0b8adf, PorterDuff.Mode.SRC_ATOP)
                v.invalidate()
            }
            MotionEvent.ACTION_UP -> {
                v.background.clearColorFilter()
                v.invalidate()
            }
        }
        false
    }
}

Java Version:

Java版本:

public static void buttonEffect(View button){
    button.setOnTouchListener(new OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    v.getBackground().setColorFilter(0xe0f47521,PorterDuff.Mode.SRC_ATOP);
                    v.invalidate();
                    break;
                }
                case MotionEvent.ACTION_UP: {
                    v.getBackground().clearColorFilter();
                    v.invalidate();
                    break;
                }
            }
            return false;
        }
    });
}

#3


59  

Create your AlphaAnimation Object that decides how much will be the fading effect of the button, then let it start in the onClickListener of your buttons

創建AlphaAnimation對象,決定按鈕的淡化效果,然后讓它從按鈕的onClickListener開始

For example :

例如 :

private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);

// some code

public void onClick(View v) {
    v.startAnimation(buttonClick);
}

of course this is just a way, not the most preferred one, it's just easier

當然這只是一種方式,而不是最受歡迎的方式,它更容易

#4


7  

To make your item consistent with the system look and feel is not hard by referencing the system attribute android:attr/selectableItemBackground. For example, if you want to make an ImageView in your widget look "selectable" with proper highlighting etc: just do

通過引用系統屬性android:attr / selectableItemBackground來使您的項目與系統外觀一致並不難。例如,如果您想在窗口小部件中使用適當的突出顯示等“可選”,那么就這樣做了

<ImageView
    ...
    android:background="?android:attr/selectableItemBackground"
    ...
    />

There are a lot in android_sdk_path/platforms/android-x. Happy digging!

android_sdk_path / platforms / android-x中有很多內容。快樂挖!

EDIT: I found out later that this simple attribute does not live in SDK < v11. So the best way I know now is to download the appwidget template pack and use it.

編輯:我后來發現這個簡單的屬性不存在於SDK

https://stackoverflow.com/a/11513474/4683601

https://stackoverflow.com/a/11513474/4683601

#5


7  

Or using only one background image you can achive the click effect by using setOnTouchListener

或者只使用一個背景圖像,您可以使用setOnTouchListener來實現單擊效果

Two ways

兩種方式

((Button)findViewById(R.id.testBth)).setOnTouchListener(new OnTouchListener() {

      @Override
        public boolean onTouch(View v, MotionEvent event) {
          switch (event.getAction()) {
              case MotionEvent.ACTION_DOWN: {
                  Button view = (Button) v;
                  view.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
                  v.invalidate();
                  break;
              }
              case MotionEvent.ACTION_UP:
                  // Your action here on button click
              case MotionEvent.ACTION_CANCEL: {
                  Button view = (Button) v;
                  view.getBackground().clearColorFilter();
                  view.invalidate();
                  break;
              }
          }
          return true;
        }
});

enter image description here

And if you don't want to use setOnTouchLister, the another way of achieving this is

如果您不想使用setOnTouchLister,另一種實現此目的的方法是

    myButton.getBackground().setColorFilter(.setColorFilter(0xF00, Mode.MULTIPLY);

    StateListDrawable listDrawable = new StateListDrawable();
    listDrawable.addState(new int[] {android.R.attr.state_pressed}, drawablePressed);
    listDrawable.addState(new int[] {android.R.attr.defaultValue}, myButton);

    myButton.setBackgroundDrawable(listDrawable);

#6


2  

just wanna add another easy way to do this: If your ImageButton remains its background and you don't set it to null, it will work like a normal button and will show the click animation while clicking exactly like other buttons.The way to hide the background while it is still there:

只是想添加另一個簡單的方法來執行此操作:如果您的ImageButton仍然是它的背景而您沒有將其設置為null,它將像普通按鈕一樣工作,並將顯示點擊動畫,同時像其他按鈕一樣點擊。隱藏的方式它仍在那里的背景:

<ImageButton
    android:id="@+id/imageButton2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingBottom="1dp"
    android:paddingLeft="1dp"
    android:paddingRight="1dp"
    android:paddingTop="1dp"
    android:src="@drawable/squareicon" />

The paddings won't let the background be visible and make the button act like other buttons.

填充不會讓背景可見,並使按鈕像其他按鈕一樣。

#7


2  

Step: set a button in XML with onClick Action:

 <Button
android:id="@+id/btnEditUserInfo"
style="?android:borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="@dimen/txt_height"
android:layout_gravity="center"
android:background="@drawable/round_btn"
android:contentDescription="@string/image_view"
android:onClick="edit_user_info"
android:text="Edit"
android:textColor="#000"
android:textSize="@dimen/login_textSize" />

Step: on button clicked show animation point
//pgrm mark ---- ---- ----- ---- ---- ----- ---- ---- -----  ---- ---- -----

    public void edit_user_info(View view) {

        // show click effect on button pressed
        final AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
        view.startAnimation(buttonClick);

        Intent intent = new Intent(getApplicationContext(),  EditUserInfo.class);
        startActivity(intent);

    }// end edit_user_info

#8


2  

This is the best solution I came up with taking hints from @Vinayak's answer. All the other solutions have different drawbacks.

這是我從@Vinayak的回答中得到提示的最佳解決方案。所有其他解決方案都有不同的缺點。

First of all create a function like this.

首先創建一個這樣的函數。

void addClickEffect(View view)
{
    Drawable drawableNormal = view.getBackground();

    Drawable drawablePressed = view.getBackground().getConstantState().newDrawable();
    drawablePressed.mutate();
    drawablePressed.setColorFilter(Color.argb(50, 0, 0, 0), PorterDuff.Mode.SRC_ATOP);

    StateListDrawable listDrawable = new StateListDrawable();
    listDrawable.addState(new int[] {android.R.attr.state_pressed}, drawablePressed);
    listDrawable.addState(new int[] {}, drawableNormal);
    view.setBackground(listDrawable);
}

Explanation:

說明:

getConstantState().newDrawable() is used to clone the existing Drawable otherwise the same drawable will be used. Read more from here: Android: Cloning a drawable in order to make a StateListDrawable with filters

getConstantState()。newDrawable()用於克隆現有的Drawable,否則將使用相同的drawable。從這里閱讀更多內容:Android:克隆一個drawable,以便使用過濾器創建一個StateListDrawable

mutate() is used to make the Drawable clone not share its state with other instances of Drawable. Read more about it here: https://developer.android.com/reference/android/graphics/drawable/Drawable.html#mutate()

mutate()用於使Drawable克隆不與其他Drawable實例共享其狀態。在這里閱讀更多相關信息:https://developer.android.com/reference/android/graphics/drawable/Drawable.html#mutate()

Usage:

用法:

You can pass any type of View (Button, ImageButton, View etc) as the parameter to the function and they will get the click effect applied to them.

您可以將任何類型的視圖(Button,ImageButton,View等)作為參數傳遞給函數,它們將獲得應用於它們的單擊效果。

addClickEffect(myButton);
addClickEffect(myImageButton);

#9


0  

Making a minor addition to Andràs answer:

對Andràs做一個小小的補充回答:

You can use postDelayed to make the color filter last for a small period of time to make it more noticeable:

您可以使用postDelayed使濾色器持續一小段時間,使其更加明顯:

        @Override
        public boolean onTouch(final View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    v.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
                    v.invalidate();
                    break;
                }
                case MotionEvent.ACTION_UP: {
                    v.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            v.getBackground().clearColorFilter();
                            v.invalidate();
                        }
                    }, 100L);
                    break;
                }
            }
            return false;
        }

You can change the value of the delay 100L to suit your needs.

您可以更改延遲100L的值以滿足您的需要。

#10


0  

If you're using xml background instead of IMG, just remove this :

如果您使用的是xml背景而不是IMG,請將其刪除:

<item>
    <bitmap android:src="@drawable/YOURIMAGE"/>
</item>

from the 1st answer that @Ljdawson gave us.

從@Ljdawson給我們的第一個答案。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/08/24/76760c86eb96f047aebd9a585ddf2c06.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com