【发布时间】:2016-09-21 08:32:01
【问题描述】:
我的应用中有一行按钮。我想要实现的是:当我将手指拖到按钮上时,将调用一个方法。
到目前为止,我的代码如下所示:
布局:
<?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。使用这个例子stackoverflow.com/a/12938787/3286614