下面列出了android.view.View#setPressed ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
*
*/
@Override
public boolean onTouch(View view, MotionEvent event) {
HidPayload hidPayload = null;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
view.startAnimation(ViewUtils.getClickAnimation());
view.setPressed(true);
hidPayload = getPayloadDown(view.getId());
mSocketManager.sendPayload(hidPayload);
return true;
case MotionEvent.ACTION_UP:
hidPayload = getPayloadUp(view.getId());
mSocketManager.sendPayload(hidPayload);
view.setPressed(false);
return true;
}
return false;
}
@Override
public boolean onKeyUp( int keyCode, KeyEvent event ) {
switch ( keyCode ) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
if ( !isEnabled() ) {
return true;
}
if ( isClickable() && isPressed() &&
mSelectedPosition >= 0 && mAdapter != null &&
mSelectedPosition < mAdapter.getCount() ) {
final View view = getChildAt( mSelectedPosition - mFirstPosition );
if ( view != null ) {
performItemClick( view, mSelectedPosition, mSelectedColId );
view.setPressed( false );
}
setPressed( false );
return true;
}
break;
}
return super.onKeyUp( keyCode, event );
}
@Override
public void run() {
final int motionPosition = mMotionPosition;
final View child = getChildAt(motionPosition - mFirstPosition);
if (child != null) {
final int longPressPosition = mMotionPosition;
final long longPressId = mAdapter.getItemId(mMotionPosition);
boolean handled = false;
if (sameWindow() && !mDataChanged) {
handled = performLongPress(child, longPressPosition,
longPressId);
}
if (handled) {
mTouchMode = TOUCH_MODE_REST;
setPressed(false);
child.setPressed(false);
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
}
}
/**
* 把一个View的对象转换成bitmap
*
* @param view View
* @return Bitmap
*/
public static Bitmap getBitmapFromView2(View view) {
if (view == null) {
return null;
}
view.clearFocus();
view.setPressed(false);
// 能画缓存就返回false
boolean willNotCache = view.willNotCacheDrawing();
view.setWillNotCacheDrawing(false);
int color = view.getDrawingCacheBackgroundColor();
view.setDrawingCacheBackgroundColor(0);
if (color != 0) {
view.destroyDrawingCache();
}
view.buildDrawingCache();
Bitmap cacheBitmap = view.getDrawingCache();
if (cacheBitmap == null) {
XPrintUtils.e( "failed getViewBitmap(" + view + ") -->"+
new RuntimeException());
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// Restore the view
view.destroyDrawingCache();
view.setWillNotCacheDrawing(willNotCache);
view.setDrawingCacheBackgroundColor(color);
return bitmap;
}
public void run() {
if (mTouchMode == TOUCH_MODE_DOWN) {
mTouchMode = TOUCH_MODE_TAP;
final View child = getChildAt(mMotionPosition - mFirstPosition);
if (child != null && !child.hasFocusable()) {
mLayoutMode = LAYOUT_NORMAL;
if (!mDataChanged) {
layoutChildren();
child.setPressed(true);
positionSelector(child);
setPressed(true);
final int longPressTimeout = ViewConfiguration.getLongPressTimeout();
final boolean longClickable = isLongClickable();
if (mSelector != null) {
Drawable d = mSelector.getCurrent();
if (d != null && d instanceof TransitionDrawable) {
if (longClickable) {
((TransitionDrawable) d).startTransition(longPressTimeout);
} else {
((TransitionDrawable) d).resetTransition();
}
}
}
if (longClickable) {
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
}
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (v.isClickable()) {
/* handle press states */
if (event.getAction() == MotionEvent.ACTION_DOWN) {
v.setPressed(true);
timer = new Timer();
// Initial delay = length of a long press
timer.schedule(new IncrementTask(0, ViewConfiguration.getLongPressTimeout()), ViewConfiguration.getLongPressTimeout());
} else if (event.getAction() == MotionEvent.ACTION_UP) {
timer.cancel();
v.setPressed(false);
}
long lengthOfPress = event.getEventTime() - event.getDownTime();
// If the button has been "tapped" then handle normally
if (lengthOfPress < ViewConfiguration.getLongPressTimeout()
&& event.getAction() == MotionEvent.ACTION_UP) {
incrementListener.increment();
}
return true;
} else {
/* If the view isn't clickable, let the touch be handled by others. */
return false;
}
}
/**
* Reuses item views when it can
*/
public void updateMenuView(boolean cleared) {
final ViewGroup parent = (ViewGroup) mMenuView;
if (parent == null) return;
int childIndex = 0;
if (mMenu != null) {
mMenu.flagActionItems();
ArrayList<MenuItemImpl> visibleItems = mMenu.getVisibleItems();
final int itemCount = visibleItems.size();
for (int i = 0; i < itemCount; i++) {
MenuItemImpl item = visibleItems.get(i);
if (shouldIncludeItem(childIndex, item)) {
final View convertView = parent.getChildAt(childIndex);
final MenuItemImpl oldItem = convertView instanceof MenuView.ItemView ?
((MenuView.ItemView) convertView).getItemData() : null;
final View itemView = getItemView(item, convertView, parent);
if (item != oldItem) {
// Don't let old states linger with new data.
itemView.setPressed(false);
if (IS_HONEYCOMB) itemView.jumpDrawablesToCurrentState();
}
if (itemView != convertView) {
addItemView(itemView, childIndex);
}
childIndex++;
}
}
}
// Remove leftover views.
while (childIndex < parent.getChildCount()) {
if (!filterLeftoverView(parent, childIndex)) {
childIndex++;
}
}
}
private void setPressedItem(@NonNull View child, int position, float x, float y) {
mDrawsInPressedState = true;
// Ordering is essential. First, update the container's pressed state.
drawableHotspotChanged(x, y);
if (!isPressed()) {
setPressed(true);
}
// Next, run layout if we need to stabilize child positions.
if (mDataChanged) {
layoutChildren();
}
// Manage the pressed view based on motion position. This allows us to
// play nicely with actual touch and scroll events.
final View motionView = getChildAt(mMotionPosition - mFirstPosition);
if (motionView != null && motionView != child && motionView.isPressed()) {
motionView.setPressed(false);
}
mMotionPosition = position;
// Offset for child coordinates.
final float childX = x - child.getLeft();
final float childY = y - child.getTop();
child.drawableHotspotChanged(childX, childY);
if (!child.isPressed()) {
child.setPressed(true);
}
// Ensure that keyboard focus starts from the last touched position.
setSelectedPositionInt(position);
positionSelectorLikeTouch(position, child, x, y);
// Refresh the drawable state to reflect the new pressed state,
// which will also update the selector state.
refreshDrawableState();
}
/**
* Draw the view into a bitmap.
*/
private Bitmap getViewBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
// Reset the drawing cache background color to fully transparent
// for the duration of this operation
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
Log.e(TAG, "failed getViewBitmap(" + v + ")", new RuntimeException());
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// Restore the view
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
private void thumbNailScaleAnimation(View view) {
view.setDrawingCacheEnabled(true);
view.setPressed(false);
view.refreshDrawableState();
Bitmap bitmap = view.getDrawingCache();
ActivityOptionsCompat opts = ActivityOptionsCompat.makeThumbnailScaleUpAnimation(
view, bitmap, 0, 0);
// Request the activity be started, using the custom animation options.
startActivity(new Intent(MainServiceActivity.this, AppsPreferencesActivity.class),
opts.toBundle());
view.setDrawingCacheEnabled(false);
}
public static Bitmap loadBitmapFromViewCache(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
// Reset the drawing cache background color to fully transparent
// for the duration of this operation
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (null == cacheBitmap) return null;
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// Restore the view
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
/**
* 通过 View Cache 绘制为 Bitmap
* @param view {@link View}
* @return {@link Bitmap}
*/
public static Bitmap snapshotByViewCache(final View view) {
if (view == null) return null;
try {
// 清除视图焦点
view.clearFocus();
// 将视图设为不可点击
view.setPressed(false);
// 获取视图是否可以保存画图缓存
boolean willNotCache = view.willNotCacheDrawing();
view.setWillNotCacheDrawing(false);
// 获取绘制缓存位图的背景颜色
int color = view.getDrawingCacheBackgroundColor();
// 设置绘图背景颜色
view.setDrawingCacheBackgroundColor(0);
if (color != 0) { // 获取的背景不是黑色的则释放以前的绘图缓存
view.destroyDrawingCache(); // 释放绘图资源所使用的缓存
}
// 重新创建绘图缓存, 此时的背景色是黑色
view.buildDrawingCache();
// 获取绘图缓存, 注意这里得到的只是一个图像的引用
Bitmap cacheBitmap = view.getDrawingCache();
if (cacheBitmap == null) return null;
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// 释放位图内存
view.destroyDrawingCache();
// 回滚以前的缓存设置、缓存颜色设置
view.setWillNotCacheDrawing(willNotCache);
view.setDrawingCacheBackgroundColor(color);
return bitmap;
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "snapshotByViewCache");
}
return null;
}
public void run() {
if (mTouchMode == TOUCH_MODE_DOWN) {
mTouchMode = TOUCH_MODE_TAP;
final View child = getChildAt(mMotionPosition - mFirstPosition);
if (child != null && !child.hasFocusable()) {
mLayoutMode = LAYOUT_NORMAL;
if (!mDataChanged) {
layoutChildren();
child.setPressed(true);
positionSelector(child);
setPressed(true);
final int longPressTimeout = ViewConfiguration.getLongPressTimeout();
final boolean longClickable = isLongClickable();
if (mSelector != null) {
Drawable d = mSelector.getCurrent();
if (d != null && d instanceof TransitionDrawable) {
if (longClickable) {
((TransitionDrawable) d).startTransition(longPressTimeout);
} else {
((TransitionDrawable) d).resetTransition();
}
}
}
if (longClickable) {
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
}
}
}
private boolean startScrollIfNeeded( int x ) {
// Check if we have moved far enough that it looks more like a
// scroll than a tap
final int deltaX = x - mMotionX;
final int distance = Math.abs( deltaX );
final boolean overscroll = getScrollX() != 0;
if ( overscroll || distance > mTouchSlop ) {
createScrollingCache();
if ( overscroll ) {
mTouchMode = TOUCH_MODE_OVERSCROLL;
mMotionCorrection = 0;
} else {
mTouchMode = TOUCH_MODE_SCROLL;
mMotionCorrection = deltaX > 0 ? mTouchSlop : -mTouchSlop;
}
final Handler handler = getHandler();
// Handler should not be null unless the AbsListView is not attached to a
// window, which would make it very hard to scroll it... but the monkeys
// say it's possible.
if ( handler != null ) {
handler.removeCallbacks( mPendingCheckForLongPress );
}
setPressed( false );
View motionView = getChildAt( mMotionPosition - mFirstPosition );
if ( motionView != null ) {
motionView.setPressed( false );
}
reportScrollStateChange( OnScrollListener.SCROLL_STATE_TOUCH_SCROLL );
// Time to start stealing events! Once we've stolen them, don't let anyone
// steal from us
final ViewParent parent = getParent();
if ( parent != null ) {
parent.requestDisallowInterceptTouchEvent( true );
}
scrollIfNeeded( x );
return true;
}
return false;
}
private void highlightAuthenticatedToken(String signResult) {
String credentialId;
try {
JSONObject signResultJson = new JSONObject(signResult);
JSONObject credentialJson = signResultJson.getJSONObject(KEY_CREDENTIAL);
credentialId = credentialJson.getString(KEY_CREDENTIAL_ID);
} catch (JSONException e) {
Log.e(TAG, "Error extracting information from JSON sign result", e);
return;
}
int whichToken = -1;
Log.i(TAG, "Successfully authenticated credential Id: " + credentialId);
for (int position = 0; position < securityTokens.size(); position++) {
Map<String, String> tokenMap = securityTokens.get(position);
Log.d(TAG, "token map at position " + position + " is " + tokenMap.toString());
Log.i(
TAG,
"highlightAuthenticatedToken registered public_key: " + tokenMap.get(KEY_KEY_HANDLE));
if (credentialId.equals(tokenMap.get(KEY_KEY_HANDLE))) {
whichToken = position;
break;
}
}
if (whichToken >= 0) {
Log.i(TAG, "highlightAuthenticatedToken whichToken: " + whichToken);
View card =
recyclerView
.getLayoutManager()
.findViewByPosition(whichToken)
.findViewById(R.id.information);
card.setPressed(true);
card.setPressed(false);
}
}
private boolean onTouchUpTap(final MotionEvent event) {
final int motionPosition = mMotionPosition;
if (motionPosition >= 0) {
final View child = getChildAt(motionPosition);
if (child != null && !child.hasFocusable()) {
if (mTouchMode != TOUCH_MODE_DOWN) {
child.setPressed(false);
}
if (mPerformClick == null) {
invalidate();
mPerformClick = new PerformClick();
}
final PerformClick performClick = mPerformClick;
performClick.mClickMotionPosition = motionPosition;
performClick.rememberWindowAttachCount();
// mResurrectToPosition = motionPosition;
if (mTouchMode == TOUCH_MODE_DOWN || mTouchMode == TOUCH_MODE_TAP) {
final Handler handler = getHandler();
if (handler != null) {
handler.removeCallbacks(mTouchMode == TOUCH_MODE_DOWN ?
mPendingCheckForTap : mPendingCheckForLongPress);
}
mLayoutMode = LAYOUT_NORMAL;
if (!mDataChanged && motionPosition >= 0 && mAdapter.isEnabled(motionPosition)) {
mTouchMode = TOUCH_MODE_TAP;
layoutChildren();
child.setPressed(true);
setPressed(true);
postDelayed(new Runnable() {
public void run() {
child.setPressed(false);
setPressed(false);
if (!mDataChanged) {
post(performClick);
}
mTouchMode = TOUCH_MODE_IDLE;
}
}, ViewConfiguration.getPressedStateDuration());
} else {
mTouchMode = TOUCH_MODE_IDLE;
}
return true;
} else if (!mDataChanged && motionPosition >= 0 && mAdapter.isEnabled(motionPosition)) {
post(performClick);
}
}
}
mTouchMode = TOUCH_MODE_IDLE;
return true;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (mLocked) {
return false;
}
final int action = event.getAction();
float x = event.getX();
float y = event.getY();
final Rect frame = mFrame;
final View handle = mHandle;
handle.getHitRect(frame);
if (!mTracking && !frame.contains((int) x, (int) y)) {
return false;
}
if (action == MotionEvent.ACTION_DOWN) {
mTracking = true;
handle.setPressed(true);
// Must be called before prepareTracking()
prepareContent();
// Must be called after prepareContent()
if (mOnDrawerScrollListener != null) {
mOnDrawerScrollListener.onScrollStarted();
}
if (mVertical) {
final int top = mHandle.getTop();
mTouchDelta = (int) y - top;
prepareTracking(top);
} else {
final int left = mHandle.getLeft();
mTouchDelta = (int) x - left;
prepareTracking(left);
}
mVelocityTracker.addMovement(event);
}
return true;
}
/**
* Add a view as a child and make sure it is measured (if necessary) and
* positioned properly.
*
* @param child The view to add
* @param position The position of the view
* @param x The x position relative to which this view will be positioned
* @param flow if true, align left edge to x. If false, align right edge
* to x.
* @param childrenTop Top edge where children should be positioned
* @param selected Is this position selected?
* @param recycled Has this view been pulled from the recycle bin? If so it
* does not need to be remeasured.
* @param where Where to add the item in the list
*
*/
private void setupChild(View child, int position, int x, boolean flow, int childrenTop,
boolean selected, boolean recycled, int where) {
boolean isSelected = selected && shouldShowSelector();
final boolean updateChildSelected = isSelected != child.isSelected();
final int mode = mTouchMode;
final boolean isPressed = mode > TOUCH_MODE_DOWN && mode < TOUCH_MODE_SCROLL &&
mMotionPosition == position;
final boolean updateChildPressed = isPressed != child.isPressed();
boolean needToMeasure = !recycled || updateChildSelected || child.isLayoutRequested();
// Respect layout params that are already in the view. Otherwise make
// some up...
TwoWayAbsListView.LayoutParams p = (TwoWayAbsListView.LayoutParams)child.getLayoutParams();
if (p == null) {
p = new TwoWayAbsListView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.FILL_PARENT, 0);
}
p.viewType = mAdapter.getItemViewType(position);
if (recycled && !p.forceAdd) {
attachViewToParent(child, where, p);
} else {
p.forceAdd = false;
addViewInLayout(child, where, p, true);
}
if (updateChildSelected) {
child.setSelected(isSelected);
if (isSelected) {
requestFocus();
}
}
if (updateChildPressed) {
child.setPressed(isPressed);
}
if (needToMeasure) {
int childWidthSpec = ViewGroup.getChildMeasureSpec(
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 0, p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(
MeasureSpec.makeMeasureSpec(mRowHeight, MeasureSpec.EXACTLY), 0, p.height);
child.measure(childWidthSpec, childHeightSpec);
} else {
cleanupLayoutState(child);
}
final int w = child.getMeasuredWidth();
final int h = child.getMeasuredHeight();
final int childLeft = flow ? x : x - w;
int childTop;
switch (mGravity & Gravity.VERTICAL_GRAVITY_MASK) {
case Gravity.TOP:
childTop = childrenTop;
break;
case Gravity.CENTER_HORIZONTAL:
childTop = childrenTop + ((mRowHeight - h) / 2);
break;
case Gravity.RIGHT:
childTop = childrenTop + mRowHeight - h;
break;
default:
childTop = childrenTop;
break;
}
if (needToMeasure) {
final int childRight = childLeft + w;
final int childBottom = childTop + h;
child.layout(childLeft, childTop, childRight, childBottom);
} else {
child.offsetLeftAndRight(childLeft - child.getLeft());
child.offsetTopAndBottom(childTop - child.getTop());
}
if (mCachingStarted) {
child.setDrawingCacheEnabled(true);
}
}
protected void onChildPressed(View child, boolean pressed)
{
child.setPressed(pressed);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
if(!mRegion.contains((int)event.getX(),(int) event.getY())) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
if (mTouched) {
v.requestFocus();
v.requestFocusFromTouch();
if (mClickListener != null) {
mClickListener.onClick(v);
}
}
v.setPressed(false);
mTouched = false;
}
return true;
} else {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
v.setPressed(true);
mTouched = true;
return true;
case MotionEvent.ACTION_UP:
if (mTouched && ViewUtils.isInsideView(v, (int)event.getRawX(), (int)event.getRawY())) {
v.requestFocus();
v.requestFocusFromTouch();
if (mClickListener != null) {
mClickListener.onClick(v);
}
}
v.setPressed(false);
mTouched = false;
return true;
case MotionEvent.ACTION_MOVE:
return true;
case MotionEvent.ACTION_CANCEL:
v.setPressed(false);
mTouched = false;
return true;
}
return false;
}
}