這是你想要的東西的基礎知識。它可能並不完全是你想要的,因爲手指之間必須有一些空間,我曾經認識到這一點。如果兩個手指靠在一起,它將ACTION_MOVE
作爲MotionEvent
。如果你真的需要,你可能會解釋這些&確定是否有兩個或更多的手指緊靠在一起。 MotionEvent
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int MAX_TOUCHES = 3;
private View buttonView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
buttonView = findViewById(R.id.button_view);
buttonView.setOnTouchListener(new View.OnTouchListener() {
boolean eventConsumed = false;
// Only handling these 4 events means that there must be some space
// between fingers when touching
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
Log.d(TAG, "" + motionEvent.toString());
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:
setButtonColor(motionEvent.getPointerCount());
eventConsumed = true;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
// subtract 1 from the count, this event still includes the touch just removed
setButtonColor(motionEvent.getPointerCount() - 1);
eventConsumed = true;
break;
default:
break;
}
return eventConsumed;
}
});
}
private void setButtonColor(int count) {
Log.d(TAG, "count = " + count);
if(count < 0) {
count = 0;
} else if(count > MAX_TOUCHES) {
count = MAX_TOUCHES;
}
switch (count) {
case 0:
buttonView.setBackgroundColor(getButtonColor(R.color.colorNotPressed));
break;
case 1:
buttonView.setBackgroundColor(getButtonColor(R.color.colorRed));
break;
case 2:
buttonView.setBackgroundColor(getButtonColor(R.color.colorYellow));
break;
case 3:
buttonView.setBackgroundColor(getButtonColor(R.color.colorGreen));
break;
default:
break;
}
}
// This keeps you from getting a warning about getResources().getColor() being deprecated
@SuppressWarnings(value = "deprecation")
private int getButtonColor(int id) {
int color;
if(Build.VERSION.SDK_INT >= 23) {
color = getColor(id);
} else {
color = getResources().getColor(id);
}
return color;
}
}
activity_main.xml中(不包括AppBar或FAB東西)
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
>
<View
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_centerInParent="true"
android:text="Big Button"
android:background="@color/colorNotPressed"
android:id="@+id/button_view"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Big Button"
android:textSize="20sp"
/>
</RelativeLayout>
有了這些你colors.xml文件
<color name="colorNotPressed">#606060</color>
<color name="colorRed">#FF0000</color>
<color name="colorYellow">#FFFF00</color>
<color name="colorGreen">#00FF00</color>
HTTPS:/ /github.com/devunwired/custom-touch-examples這個存儲庫可能會有所幫助。 – Raghunandan
我在找哪個確切的例子? – user381261