我的应用程序中有一排按钮。我想实现的是:当我将手指拖过按钮时,会调用一个方法。Android - 在滑动按钮行时触发ontouch事件
我的代码看起来像这样至今:
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.a4web.example.MainActivity">
</LinearLayout>
的Java:
public class MainActivity extends AppCompatActivity {
LinearLayout rootView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rootView = (LinearLayout) findViewById(R.id.activity_main);
for(int i=0; i<5; i++){
Button button = new Button(this);
button.setText(i);
button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
doSomething();
break;
}
return false;
}
});
rootView.addView(button);
}
}
我的方法DoSomething的当我按下按钮只能被调用。当我拖动一个按钮时,我怎么能实现它被调用。我应该听什么类型的活动?
您可以覆盖OnTouchListener让你SwipeListener。使用此示例http://stackoverflow.com/a/12938787/3286614 – Rachit