16
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android 簡単にボタンに"押した感"を出す

Last updated at Posted at 2017-05-25

Androidで、簡単にImagebuttonやbuttonに押した感を出す方法

image3.jpg
1.下記、2つのJavaクラスを作成して、プロジェクトに追加。
 ※「*****」部分は編集してください

PushButton.java
package *****パッケージ名*****;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;

/*** プッシュするエフェクトのボタン ***/
public class PushButton extends Button {
    public PushButton(Context context) {
        super(context);
    }

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

    @Override
    public void setPressed(boolean pressed) {
        if(pressed){
            this.setScaleY(0.92f);
            this.setScaleX(0.96f);
        }else{
            this.setScaleY(1.0f);
            this.setScaleX(1.0f);
        }
        super.setPressed(pressed);
    }

}
AlphaButton.java
package *****パッケージ名*****;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;

/*** 半透明になるエフェクトのボタン ***/
public class AlphaButton extends Button {
    public AlphaButton(Context context) {
        super(context);
    }

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

    @Override
    public void setPressed(boolean pressed) {
        if(pressed){
            this.setAlpha(0.75f);
        }else{
            this.setAlpha(1.0f);
        }
        super.setPressed(pressed);
    }

}

2.あとはレイアウトXMLに「Button」の代わりにカスタムボタンを配置
・レイアウト例
 ※「*****」部分は編集してください

layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainframe"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#000000">

    <!--- 押すと縮小するボタン -->
    <*****パッケージ名*****.PushButton
        android:id="@+id/button_sample01"
        android:layout_width="200dp"
        android:layout_height="60dp"
        android:background="@drawable/button_sample"
        />

    <!--- 押すと半透明のボタン -->
    <*****パッケージ名*****.AlphaButton
        android:id="@+id/button_sample02"
        android:layout_width="200dp"
        android:layout_height="60dp"
        android:background="@drawable/button_sample"
        />
</LinearLayout>

以上

16
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?