下面列出了怎么用android.view.View.OnTouchListener的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns an {@link OnTouchListener} that can be added to the anchor view
* to implement drag-to-open behavior.
* <p>
* When the listener is set on a view, touching that view and dragging
* outside of its bounds will open the popup window. Lifting will select
* the currently touched list item.
* <p>
* Example usage:
* <pre>
* PopupMenu myPopup = new PopupMenu(context, myAnchor);
* myAnchor.setOnTouchListener(myPopup.getDragToOpenListener());
* </pre>
*
* @return a touch listener that controls drag-to-open behavior
*/
public OnTouchListener getDragToOpenListener() {
if (mDragListener == null) {
mDragListener = new ForwardingListener(mAnchor) {
@Override
protected boolean onForwardingStarted() {
show();
return true;
}
@Override
protected boolean onForwardingStopped() {
dismiss();
return true;
}
@Override
public ShowableListMenu getPopup() {
// This will be null until show() is called.
return mPopup.getPopup();
}
};
}
return mDragListener;
}
private OnTouchListener createTraitOnTouchListener(final ImageView arrow,
final int imageIdUp, final int imageIdDown) {
return new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
arrow.setImageResource(imageIdDown);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
arrow.setImageResource(imageIdUp);
case MotionEvent.ACTION_CANCEL:
break;
}
// return true to prevent calling btn onClick handler
return false;
}
};
}
protected void onMessageListInit(){
messageList.init(toChatUsername, chatType, chatFragmentListener != null ?
chatFragmentListener.onSetCustomChatRowProvider() : null);
//设置list item里的控件的点击事件
setListItemClickListener();
messageList.getListView().setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
hideKeyboard();
inputMenu.hideExtendMenuContainer();
return false;
}
});
isMessageListInited = true;
}
private QsDetailItemsList(LinearLayout view) {
mView = view;
mListView = (ListView) mView.findViewById(android.R.id.list);
mListView.setOnTouchListener(new OnTouchListener() {
// Setting on Touch Listener for handling the touch inside ScrollView
@Override
public boolean onTouch(View v, MotionEvent event) {
// Disallow the touch request for parent scroll on touch of child view
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
mEmpty = mView.findViewById(android.R.id.empty);
mEmpty.setVisibility(View.GONE);
mEmptyText = (TextView) mEmpty.findViewById(android.R.id.title);
mEmptyIcon = (ImageView) mEmpty.findViewById(android.R.id.icon);
mListView.setEmptyView(mEmpty);
}
void initTraitDetails() {
if (prefixTraits != null) {
final TextView traitDetails = findViewById(R.id.traitDetails);
traitDetails.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
traitDetails.setMaxLines(10);
break;
case MotionEvent.ACTION_UP:
traitDetails.setMaxLines(1);
break;
}
return true;
}
});
}
}
private void initKeyboard() {
mKeyboardView.setOnKeyboardActionListener(new PinKeyboardView.PinPadActionListener() {
@Override
public void onKey(int primaryCode, int[] keyCodes) {
Editable e = mPinputView.getText();
if (primaryCode == PinKeyboardView.KEYCODE_DELETE) {
int len = e.length();
if (len == 0) {
return;
}
e.delete(len - 1, e.length());
} else {
mPinputView.getText().append((char) primaryCode);
}
}
});
mKeyboardView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == ACTION_DOWN && getConfig().shouldVibrateOnKey()) {
VibrationHelper.vibrate(mContext, getConfig().vibrateDuration());
}
return false;
}
});
}
@SuppressWarnings("deprecation")
public SelectRemindWayPopup(Context context) {
mContext = context;
mPopupWindow = new PopupWindow(context);
mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
mPopupWindow.setWidth(WindowManager.LayoutParams.FILL_PARENT);
mPopupWindow.setHeight(WindowManager.LayoutParams.FILL_PARENT);
mPopupWindow.setTouchable(true);
mPopupWindow.setFocusable(true);
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.setAnimationStyle(R.style.AnimBottom);
mPopupWindow.setContentView(initViews());
mPopupWindow.getContentView().setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
mPopupWindow.setFocusable(false);
mPopupWindow.dismiss();
return true;
}
});
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListView.setOnScrollListener(new OnScroll());
mListView.setAdapter(new ArrayAdapter<String>(getActivity(), R.layout.list_item, android.R.id.text1, mListItems));
if(MainActivity.NEEDS_PROXY){//in my moto phone(android 2.1),setOnScrollListener do not work well
mListView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mScrollTabHolder != null)
mScrollTabHolder.onScroll(mListView, 0, 0, 0, mPosition);
return false;
}
});
}
}
protected void onMessageListInit(){
messageList.init(toChatUsername, chatType, chatFragmentHelper != null ?
chatFragmentHelper.onSetCustomChatRowProvider() : null);
setListItemClickListener();
messageList.getListView().setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
hideKeyboard();
inputMenu.hideExtendMenuContainer();
return false;
}
});
isMessageListInited = true;
}
@SuppressLint("ClickableViewAccessibility")
private void showMembers(List<User> members) {
adapter = new GridAdapter(this, members);
gridview.setAdapter(adapter);
// 设置OnTouchListener,为了让群主方便地推出删除模》
gridview.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (adapter.isInDeleteMode) {
adapter.isInDeleteMode = false;
adapter.notifyDataSetChanged();
return true;
}
break;
default:
break;
}
return false;
}
});
}
protected void onMessageListInit(){
messageList.init(toChatUsername, chatType, chatFragmentListener != null ?
chatFragmentListener.onSetCustomChatRowProvider() : null);
//设置list item里的控件的点击事件
setListItemClickListener();
messageList.getListView().setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
hideKeyboard();
return false;
}
});
isMessageListInited = true;
}
@Override
protected void initRefreshView() {
super.initRefreshView();
mFeedsListView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
checkWhetherExecuteAnimation(event);
if (mCommentLayout.isShown()) {
hideCommentLayoutAndInputMethod();
return true;
}
return false;
}
});
mSlop = ViewConfiguration.get(getActivity()).getScaledTouchSlop();
}
/**
* 初始化view</br>
*/
private void initViews() {
initTitleLayout();
mRootView = findViewById(ResFinder.getId("umeng_comm_feed_detail_root"));
mBaseView = (BaseView) findViewById(ResFinder.getId("umeng_comm_baseview"));
mBaseView.forceLayout();
findViewById(ResFinder.getId("umeng_comm_feed_container")).setOnTouchListener(
new OnTouchListener() {
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mCommentLayout != null) {
mCommentLayout.setVisibility(View.GONE);
hideInputMethod(mCommentEditText);
return true;
}
return false;
}
});
}
/**
* Hides keyboard when clicking elsewhere
*
* @param view
*/
private void hideKeyboardOnClick(View view) {
// Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText) && !(view instanceof Button)) {
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null) {
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
return false;
}
});
}
// If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
hideKeyboardOnClick(innerView);
}
}
}
/**
* Hides keyboard when clicking elsewhere
*/
private void hideKeyboardOnClick(View view) {
// Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText) && !(view instanceof Button)) {
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null) {
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
return false;
}
});
}
// If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
hideKeyboardOnClick(innerView);
}
}
}
private void initListView() {
friendsList = (ListView) getView().findViewById(R.id.list_friends);
LayoutInflater mInflater = LayoutInflater.from(context);
RelativeLayout headView = (RelativeLayout) mInflater.inflate(
R.layout.contact_include_new_friend, null);
msgTipsView = (ImageView) headView.findViewById(R.id.iv_msg_tips);
newFriendLayout = (LinearLayout) headView.findViewById(R.id.layout_new);
newFriendLayout.setOnClickListener(this);
friendsList.addHeaderView(headView);
userAdapter = new UserFriendAdapter(getActivity(), friends);
friendsList.setAdapter(userAdapter);
friendsList.setOnItemClickListener(this);
friendsList.setOnItemLongClickListener(this);
friendsList.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Utils.hideSoftInputView(getActivity());
return false;
}
});
}
private void initClick(){
markImageView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
// Log.i(TAG, "x=="+x+",,y=="+y);
setView(Math.round(x), Math.round(y));
// if (!point) {
// dispTagChoose();
// }else {
// hideTagChoose();
// }
return false;
}
});
}
private void setOnTouchListener(final Context context, final WindowView windowView, final int type) {
windowView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
if ((System.currentTimeMillis() - exitTime) < CHANGE_DELAY) {
createWindow(context, type);
return true;
} else {
exitTime = System.currentTimeMillis();
}
break;
default:
break;
}
return false;
}
});
}
@Override
public void initWidget() {
super.initWidget();
initWebView();
initBarAnim();
mGestureDetector = new GestureDetector(aty, new MyGestureListener());
mWebView.loadUrl(mCurrentUrl);
mWebView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return mGestureDetector.onTouchEvent(event);
}
});
}
public BasePopupWindowForListView(View contentView, int width, int height,
boolean focusable, List<T> mDatas, Object... params)
{
super(contentView, width, height, focusable);
this.mContentView = contentView;
context = contentView.getContext();
if (mDatas != null)
this.mDatas = mDatas;
if (params != null && params.length > 0)
{
beforeInitWeNeedSomeParams(params);
}
setBackgroundDrawable(new BitmapDrawable());
setTouchable(true);
setOutsideTouchable(true);
setTouchInterceptor(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_OUTSIDE)
{
dismiss();
return true;
}
return false;
}
});
initViews();
initEvents();
init();
}
public OnTouchListener getOnTouchListener() {
return new OnTouchListener() {
private Map<Integer, Integer> finger2pitch = new HashMap<Integer, Integer>();
public boolean onTouch(View v, MotionEvent e) {
if (!v.hasFocus()) v.requestFocus();
if (autoPlay || h.done || h.score.gameOver) return false;
int pitch;
// Normal multi-touch
int actionmask = e.getAction() & MotionEvent.ACTION_MASK;
@SuppressWarnings("deprecation")
int actionpid = e.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT;
switch (actionmask) {
case MotionEvent.ACTION_DOWN:
actionpid = 0;
//fallthru
case MotionEvent.ACTION_POINTER_DOWN:
pitch = h.onTouch_Down(e.getX(actionpid), e.getY(actionpid));
if (pitch > 0) finger2pitch.put(actionpid, pitch);
return pitch > 0;
case MotionEvent.ACTION_POINTER_UP:
h.onTouch_Up(e.getX(actionpid), e.getY(actionpid));
if (finger2pitch.containsKey(actionpid)) {
return h.onTouch_Up(finger2pitch.get(actionpid));
} else {
return h.onTouch_Up(0xF);
}
case MotionEvent.ACTION_UP:
h.onTouch_Up(e.getX(actionpid), e.getY(actionpid));
return h.onTouch_Up(0xF);
default:
return false;
}
}
};
}
@SuppressLint("RtlHardcoded")
private void show() {
Log.v(TAG, "show()");
if (mView == null) {
mView = onCreateView(mRootView);
mView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return true;
}
});
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mView.getLayoutParams();
params.leftMargin = getMargin();
params.rightMargin = getMargin();
params.gravity = getOpenPosition().x < getScreenWidth() / 2 ? Gravity.LEFT : Gravity.RIGHT;
mRootView.addView(mView);
mView.measure(MeasureSpec.makeMeasureSpec(mRootView.getWidth() - getMargin(), MeasureSpec.AT_MOST),
MeasureSpec.makeMeasureSpec(mRootView.getHeight() - getMargin() - getOpenPosition().y, MeasureSpec.AT_MOST));
} else {
mView.setVisibility(View.VISIBLE);
}
// Adjust view location
if (!mIsDestroyed) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
mView.setTranslationX(-mDraggableIcon.getWidth());
mView.setTranslationY(getOpenPosition().y);
} else {
mView.setTranslationY(getOpenPosition().y + mDraggableIcon.getHeight());
}
}
// Animate calc in
mView.setAlpha(0);
mView.animate().setDuration(150).alpha(1).setListener(null);
onShow();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_dialog);
view = (RelativeLayout)findViewById(R.id.contentDialog);
backView = (RelativeLayout)findViewById(R.id.dialog_rootView);
backView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getX() < view.getLeft()
|| event.getX() >view.getRight()
|| event.getY() > view.getBottom()
|| event.getY() < view.getTop()) {
dismiss();
}
return false;
}
});
this.titleTextView = (TextView) findViewById(R.id.title);
setTitle(title);
if(progressColor != -1){
ProgressBarCircularIndeterminate progressBarCircularIndeterminate = (ProgressBarCircularIndeterminate) findViewById(R.id.progressBarCircularIndetermininate);
progressBarCircularIndeterminate.setBackgroundColor(progressColor);
}
}
/**
* hide soft keyboard on android after clicking outside EditText
*
* @param view
*/
public static void setHideIme(final Activity activity,View view) {
if(null==activity||null==view){
return;
}
// Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
ViewUtil.hideSoftKeyboard(activity);
return false;
}
});
}
// If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setHideIme(activity,innerView);
}
}
}
@Override
protected void initWidget() {
super.initWidget();
screenAdapter();
mMouseLeftKey.setOnLongClickListener(this);
mMouseRightKey.setOnLongClickListener(this);
mMouseLeftKey.setBackgroundResource(R.drawable.selector_mouse_left);
mMouseRightKey.setBackgroundResource(R.drawable.selector_mouse_right);
mMouseWheel.setBackgroundResource(R.drawable.ic_mouse_wheel);
/**
* 滚轮事件
*/
mMouseWheel.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
sPrevY = event.getY();
}
if (event.getAction() == MotionEvent.ACTION_UP) {
v.performClick();
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
float currentY = event.getY();
sMoveY = currentY - sPrevY;
sPrevY = currentY;
handleWheelEvent();
}
return true;
}
});
}
@Override
protected void setUpView() {
conversationList.addAll(loadConversationList());
conversationListView.init(conversationList);
if(listItemClickListener != null){
conversationListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
EMConversation conversation = conversationListView.getItem(position);
listItemClickListener.onListItemClicked(conversation);
}
});
}
EMChatManager.getInstance().addConnectionListener(connectionListener);
conversationListView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard();
return false;
}
});
}
@SuppressLint("ClickableViewAccessibility") // There's an accessibility delegate that handles
// interactions with the dropdown menu.
private void setUpDropdownShowHideBehavior(@NonNull final AutoCompleteTextView editText) {
// Set whole layout clickable.
editText.setOnTouchListener(
new OnTouchListener() {
@Override
public boolean onTouch(@NonNull View v, @NonNull MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (isDropdownPopupActive()) {
dropdownPopupDirty = false;
}
showHideDropdown(editText);
}
return false;
}
});
editText.setOnFocusChangeListener(onFocusChangeListener);
if (IS_LOLLIPOP) {
editText.setOnDismissListener(
new OnDismissListener() {
@Override
public void onDismiss() {
dropdownPopupDirty = true;
dropdownPopupActivatedAt = System.currentTimeMillis();
setEndIconChecked(false);
}
});
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
view = new FastImageProcessingView(this);
pipeline = new FastImageProcessingPipeline();
video = new VideoResourceInput(view, this, R.raw.image_processing_birds);
edgeDetect = new SobelEdgeDetectionFilter();
image = new JPGFileEndpoint(this, false, Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/outputImage", false);
screen = new ScreenEndpoint(pipeline);
video.addTarget(edgeDetect);
edgeDetect.addTarget(image);
edgeDetect.addTarget(screen);
pipeline.addRootRenderer(video);
view.setPipeline(pipeline);
setContentView(view);
pipeline.startRendering();
video.startWhenReady();
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent me) {
if (System.currentTimeMillis() - 100 > touchTime) {
touchTime = System.currentTimeMillis();
if (video.isPlaying()) {
video.stop();
} else {
video.startWhenReady();
}
}
return true;
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_dialog);
view = (RelativeLayout)findViewById(R.id.contentDialog);
backView = (RelativeLayout)findViewById(R.id.dialog_rootView);
backView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getX() < view.getLeft()
|| event.getX() >view.getRight()
|| event.getY() > view.getBottom()
|| event.getY() < view.getTop()) {
dismiss();
}
return false;
}
});
this.titleTextView = (TextView) findViewById(R.id.title);
setTitle(title);
if(progressColor != -1){
ProgressBarCircularIndeterminate progressBarCircularIndeterminate = (ProgressBarCircularIndeterminate) findViewById(R.id.progressBarCircularIndetermininate);
progressBarCircularIndeterminate.setBackgroundColor(progressColor);
}
}
private void initXListView() {
// 首先不允许加载更多
mListView.setPullLoadEnable(false);
// 允许下拉
mListView.setPullRefreshEnable(true);
// 设置监听器
mListView.setXListViewListener(this);
mListView.pullRefreshing();
mListView.setDividerHeight(0);
// 加载数据
initOrRefresh();
mListView.setSelection(mAdapter.getCount() - 1);
mListView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
hideSoftInputView();
layout_more.setVisibility(View.GONE);
layout_add.setVisibility(View.GONE);
btn_chat_voice.setVisibility(View.VISIBLE);
btn_chat_keyboard.setVisibility(View.GONE);
btn_chat_send.setVisibility(View.GONE);
return false;
}
});
// 重发按钮的点击事件
mAdapter.setOnInViewClickListener(R.id.iv_fail_resend, new MessageChatAdapter.onInternalClickListener() {
@Override
public void OnClickListener(View parentV, View v, Integer position, Object values) {
// 重发消息
showResendDialog(parentV, v, values);
}
});
}