Android 如何实现点击某个区域做动作?

Android 如何实现点击某个区域做动作?,android,facebook,sliding,Android,Facebook,Sliding,是facebook滑动菜单的一个例子 滑动时,用户可以看到20%的空间,这与facebook相似。Facebook通过点击这20%的任意位置来实现它,菜单是向后滑动的 如何实现这一点?一种方法是在活动中使用OnTouchListener。您可以准确地检测触摸屏幕的位置 import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; i

是facebook滑动菜单的一个例子

滑动时,用户可以看到20%的空间,这与facebook相似。Facebook通过点击这20%的任意位置来实现它,菜单是向后滑动的


如何实现这一点?

一种方法是在活动中使用OnTouchListener。您可以准确地检测触摸屏幕的位置

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.Toast;

public class AndroidTestActivity extends Activity implements OnTouchListener {
  LinearLayout main;

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

    main = (LinearLayout) findViewById(R.id.main_layout);
    main.setOnTouchListener(this); // you need to set the touch listener for your view. And every element around the detection area.
  }

  public boolean onTouch(View v, MotionEvent e) {
    if(e.getX() <= main.getWidth() / 5) {
      Toast.makeText(this, "In the %20..", Toast.LENGTH_SHORT).show();
      return true;      
    }

    return false;
  }
}
您还需要标识主布局

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

谢谢你的回答,但这似乎对我不起作用。即使我没有设置任何条件,但我单击了布局的任何区域动画没有启动20%区域我仍然得到了其他组件,但是我单击了20%区域内的组件,它将执行组件自己的功能,而不是启动动画如果您有任何其他布局,图像视图或该区域的任何其他内容,您需要使用setOnTouchListener为其添加侦听器。。