使按钮工作时滑动它们

时间:2016-11-02 10:52:12

标签: android android-studio

我正在开发一个钢琴应用程序,目前我正在研究一些东西,当我用手指将它们滑过时,我的按钮会起作用。

以下是更全面的解释:

Here is what happens when i move my finger outside of this button, without releasing my finger

Here is what I would like to have when I slide my finger to another button - button which was touched first, stops working, becomes green and button which i enter with my finger works, so it turns red

我的代码:

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <Button
        android:id="@+id/imageButtonSelector"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/new_button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

new_button.xml

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

</selector>

MainActivity.java

package com.example.android.focus;

import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

Button imageButton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addListenerOnButton();

}

public void addListenerOnButton() {

    imageButton = (Button) findViewById(R.id.imageButtonSelector);

    imageButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Toast.makeText(MainActivity.this,
                    "ImageButton (selector) is clicked!",
                    Toast.LENGTH_SHORT).show();

        }

    });

}

}

我需要做些什么才能让我的应用按预期工作? 任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

由于您将滑动多个按钮,我不认为在每个按钮上实现onclick监听器可以实现您想要的效果

但我建议你采用两种方法  尝试创建一个自定义视图(可能使用一堆矩形创建自己的钢琴布局与Android视图组和处理您的触摸手势,动作移动,向下... ..

或者如果你仍然需要按钮,我猜你将需要android多点触控事件并创建创建自定义按钮扩展appcompat按钮类,以便它检测到滑动按钮

希望这可以帮助你