Example usage for android.view View setTag

List of usage examples for android.view View setTag

Introduction

In this page you can find the example usage for android.view View setTag.

Prototype

public void setTag(final Object tag) 

Source Link

Document

Sets the tag associated with this view.

Usage

From source file:com.andreadec.musicplayer.adapters.PlaylistArrayAdapter.java

@Override
public View getView(int position, View view, ViewGroup parent) {
    Object value = values.get(position);
    ViewHolder viewHolder;//w w w .j  a  v  a  2 s  . c  o  m
    int type = getItemViewType(position);
    if (view == null) {
        viewHolder = new ViewHolder();
        if (type == TYPE_ACTION) {
            view = inflater.inflate(R.layout.action_item, parent, false);
            viewHolder.title = (TextView) view.findViewById(R.id.textView);
            viewHolder.image = (ImageView) view.findViewById(R.id.imageView);
        } else if (type == TYPE_PLAYLIST) {
            view = inflater.inflate(R.layout.folder_item, parent, false);
            viewHolder.title = (TextView) view.findViewById(R.id.textViewFolderItemFolder);
            viewHolder.image = (ImageView) view.findViewById(R.id.imageViewItemImage);
        } else if (type == TYPE_SONG) {
            view = inflater.inflate(R.layout.song_item, parent, false);
            viewHolder.title = (TextView) view.findViewById(R.id.textViewSongItemTitle);
            viewHolder.artist = (TextView) view.findViewById(R.id.textViewSongItemArtist);
            viewHolder.image = (ImageView) view.findViewById(R.id.imageViewItemImage);
            viewHolder.card = view.findViewById(R.id.card);
        }
    } else {
        viewHolder = (ViewHolder) view.getTag();
    }

    if (type == TYPE_ACTION) {
        Action action = (Action) value;
        viewHolder.title.setText(action.msg);
        if (action.action == Action.ACTION_GO_BACK) {
            viewHolder.image.setImageResource(R.drawable.back);
        } else if (action.action == Action.ACTION_NEW) {
            viewHolder.image.setImageResource(R.drawable.newcontent);
        }
    } else if (type == TYPE_PLAYLIST) {
        Playlist playlist = (Playlist) value;
        viewHolder.title.setText(playlist.getName());
        viewHolder.image.setImageResource(R.drawable.playlist);
    } else if (type == TYPE_SONG) {
        PlaylistSong song = (PlaylistSong) value;
        viewHolder.title.setText(song.getTitle());
        viewHolder.artist.setText(song.getArtist());

        if (song.equals(playingSong)) {
            viewHolder.card.setBackgroundResource(R.drawable.card_playing);
            viewHolder.image.setImageResource(R.drawable.play_orange);
        } else {
            viewHolder.card.setBackgroundResource(R.drawable.card);
            if (showSongImage) {
                viewHolder.image.setImageDrawable(songImage);
                if (song.hasImage()) {
                    Bitmap image;
                    synchronized (imagesCache) {
                        image = imagesCache.get(song.getPlayableUri());
                    }
                    if (image != null) {
                        viewHolder.image.setImageBitmap(image);
                    } else
                        new ImageLoaderTask(song, viewHolder.image, imagesCache, listImageSize).execute();
                }
            }
        }
    }

    view.setTag(viewHolder);
    return view;
}

From source file:com.mishiranu.dashchan.ui.navigator.DrawerForm.java

private View makeHeader(ViewGroup parent, boolean button, float density) {
    if (C.API_LOLLIPOP) {
        LinearLayout linearLayout = new LinearLayout(context);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        View divider = makeSimpleDivider();
        int paddingTop = divider.getPaddingBottom();
        divider.setPadding(divider.getPaddingLeft(), divider.getPaddingTop(), divider.getPaddingRight(), 0);
        linearLayout.addView(divider, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        LinearLayout linearLayout2 = new LinearLayout(context);
        linearLayout2.setOrientation(LinearLayout.HORIZONTAL);
        linearLayout.addView(linearLayout2, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        TextView textView = makeCommonTextView(true);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, (int) (32f * density), 1);
        layoutParams.setMargins((int) (16f * density), paddingTop, (int) (16f * density), (int) (8f * density));
        linearLayout2.addView(textView, layoutParams);
        ViewHolder holder = new ViewHolder();
        holder.text = textView;/*from w w  w  .j  a v  a  2  s  .  c o  m*/
        if (button) {
            ImageView imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER);
            imageView.setBackgroundResource(ResourceUtils.getResourceId(context,
                    android.R.attr.borderlessButtonStyle, android.R.attr.background, 0));
            imageView.setOnClickListener(headerButtonListener);
            imageView.setImageAlpha(0x5e);
            int size = (int) (48f * density);
            layoutParams = new LinearLayout.LayoutParams(size, size);
            layoutParams.rightMargin = (int) (4f * density);
            linearLayout2.addView(imageView, layoutParams);
            holder.extra = imageView;
            holder.icon = imageView;
        }
        linearLayout.setTag(holder);
        return linearLayout;
    } else {
        View view = LayoutInflater.from(context)
                .inflate(ResourceUtils.getResourceId(context, android.R.attr.preferenceCategoryStyle,
                        android.R.attr.layout, android.R.layout.preference_category), parent, false);
        ViewHolder holder = new ViewHolder();
        holder.text = (TextView) view.findViewById(android.R.id.title);
        if (button) {
            int measureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            view.measure(measureSpec, measureSpec);
            int size = view.getMeasuredHeight();
            if (size == 0) {
                size = (int) (32f * density);
            }
            FrameLayout frameLayout = new FrameLayout(context);
            frameLayout.addView(view);
            view = frameLayout;
            ImageView imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            int padding = (int) (4f * density);
            imageView.setPadding(padding, padding, padding, padding);
            frameLayout.addView(imageView,
                    new FrameLayout.LayoutParams((int) (48f * density), size, Gravity.END));
            View buttonView = new View(context);
            buttonView.setBackgroundResource(
                    ResourceUtils.getResourceId(context, android.R.attr.selectableItemBackground, 0));
            buttonView.setOnClickListener(headerButtonListener);
            frameLayout.addView(buttonView, FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT);
            holder.extra = buttonView;
            holder.icon = imageView;
        }
        view.setTag(holder);
        return view;
    }
}

From source file:io.coldstart.android.EditOIDActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_oid);

    // Show the Up button in the action bar.
    getActionBar().setDisplayHomeAsUpEnabled(true);

    oidDescList = (LinearLayout) findViewById(R.id.OIDDescriptionHolder);

    //((TextView) findViewById(R.id.textView)).setText(getIntent().getStringExtra("payload"));
    JSONObject oidDescriptions = null;//w  w w. j a  v  a2  s . co m
    int i = 0;
    try {
        oidDescriptions = new JSONObject(getIntent().getStringExtra("payload"));

        Iterator<String> iter = oidDescriptions.keys();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                View convertView = inflater.inflate(R.layout.oid_edit, null);

                ((TextView) convertView.findViewById(R.id.OID)).setText(key);
                ((EditText) convertView.findViewById(R.id.OIDDescription))
                        .setText((String) oidDescriptions.get(key));
                ((EditText) convertView.findViewById(R.id.OIDDescription)).setTag("e_" + key);

                ((Button) convertView.findViewById(R.id.submitDescriptionButton)).setTag(key);
                ((Button) convertView.findViewById(R.id.submitDescriptionButton))
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(final View view) {
                                //Log.e("onClick", ((EditText) ((View) oidDescList.findViewWithTag(view.getTag())).findViewWithTag("e_"+view.getTag())).getText().toString());

                                ((Thread) new Thread() {
                                    public void run() {
                                        try {
                                            if (api.submitOIDEdit((String) view.getTag(),
                                                    ((EditText) ((View) oidDescList
                                                            .findViewWithTag(view.getTag()))
                                                                    .findViewWithTag("e_" + view.getTag()))
                                                                            .getText().toString())) {
                                                runOnUiThread(new Runnable() {
                                                    public void run() {
                                                        Toast.makeText(getApplicationContext(),
                                                                "OID suggestion successful.",
                                                                Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                            } else {
                                                runOnUiThread(new Runnable() {
                                                    public void run() {
                                                        Toast.makeText(getApplicationContext(),
                                                                "OID suggestion was not successful.",
                                                                Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }).start();
                            }
                        });
                convertView.setTag(key);
                oidDescList.addView(convertView);
                i++;
            } catch (Exception e) {
                // Something went wrong!
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:cn.suishen.email.activity.MessageViewFragmentBase.java

/**
 * Copy data from a cursor-refreshed attachment into the UI.  Called from UI thread.
 *
 * @param attachment A single attachment loaded from the provider
 */// w w  w .ja v  a 2s. c o m
private void addAttachment(Attachment attachment) {
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.message_view_attachment, null);

    TextView attachmentName = (TextView) UiUtilities.getView(view, R.id.attachment_name);
    TextView attachmentInfoView = (TextView) UiUtilities.getView(view, R.id.attachment_info);
    ImageView attachmentIcon = (ImageView) UiUtilities.getView(view, R.id.attachment_icon);
    Button openButton = (Button) UiUtilities.getView(view, R.id.open);
    Button saveButton = (Button) UiUtilities.getView(view, R.id.save);
    Button loadButton = (Button) UiUtilities.getView(view, R.id.load);
    Button infoButton = (Button) UiUtilities.getView(view, R.id.info);
    Button cancelButton = (Button) UiUtilities.getView(view, R.id.cancel);
    ProgressBar attachmentProgress = (ProgressBar) UiUtilities.getView(view, R.id.progress);

    MessageViewAttachmentInfo attachmentInfo = new MessageViewAttachmentInfo(mContext, attachment,
            attachmentProgress);

    // Check whether the attachment already exists
    if (Utility.attachmentExists(mContext, attachment)) {
        attachmentInfo.loaded = true;
    }

    attachmentInfo.openButton = openButton;
    attachmentInfo.saveButton = saveButton;
    attachmentInfo.loadButton = loadButton;
    attachmentInfo.infoButton = infoButton;
    attachmentInfo.cancelButton = cancelButton;
    attachmentInfo.iconView = attachmentIcon;

    updateAttachmentButtons(attachmentInfo);

    view.setTag(attachmentInfo);
    openButton.setOnClickListener(this);
    saveButton.setOnClickListener(this);
    loadButton.setOnClickListener(this);
    infoButton.setOnClickListener(this);
    cancelButton.setOnClickListener(this);

    attachmentName.setText(attachmentInfo.mName);
    attachmentInfoView.setText(UiUtilities.formatSize(mContext, attachmentInfo.mSize));

    mAttachments.addView(view);
    mAttachments.setVisibility(View.VISIBLE);
}

From source file:com.freeme.filemanager.view.FileViewFragment.java

private View createStorageVolumeItem(final String volumPath, String volumDescription) {

    View listItem = LayoutInflater.from(mActivity).inflate(R.layout.dropdown_item, null);
    View listContent = listItem.findViewById(R.id.list_item);
    ImageView img = (ImageView) listItem.findViewById(R.id.item_icon);
    TextView text = (TextView) listItem.findViewById(R.id.path_name);
    text.setText(volumDescription);/* w  w w.java2s . c  om*/

    //*/ freeme.liuhaoran , 20160728 , volumeItem image
    /*/
    img.setImageResource(getStorageVolumeIconByDescription(volumDescription));
    //*/
    Log.i("liuhaoran3", "storageVolume.getPath() = " + storageVolume.getPath());
    Log.i("liuhaoran3", "internalPath = " + internalPath);
    if (storageVolume.getPath().equals(internalPath)) {
        img.setImageDrawable((getResources().getDrawable(R.drawable.storage_internal_n)));
    } else if ((storageVolume.getDescription(mActivity).toString()).contains("SD")) {
        img.setImageDrawable((getResources().getDrawable(R.drawable.storage_sd_card_n)));
    } else if (storageVolume.getDescription(mActivity).toString().contains("usbotg")) {
        img.setImageDrawable((getResources().getDrawable(R.drawable.storage_usb_n)));
    }
    //*/

    //modigy by droi heqianqian if the stroage device is not phone memeory, then set the storage could be unmoumt
    ImageView unmount_btn = (ImageView) listItem.findViewById(R.id.unmount_btn);
    if (volumPath.equals(Util.SD_DIR)) {
        //*/ freeme.liuhaoran , 20160802 , judge whether there is a SD card operation permissions
        if (ContextCompat.checkSelfPermission(mActivity,
                "android.permission.MOUNT_UNMOUNT_FILESYSTEMS") == PackageManager.PERMISSION_GRANTED) {
            unmount_btn.setVisibility(View.VISIBLE);
            unmount_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    MountHelper.getInstance(mActivity).unMount(volumPath);
                    showVolumesList(false);
                    mVolumeSwitch.setVisibility(View.GONE);
                    int mounedCount = StorageHelper.getInstance(mActivity).getMountedVolumeCount();
                }
            });
        } else {
            unmount_btn.setVisibility(View.INVISIBLE);
        }
        //*/
    }
    listItem.setOnClickListener(mStorageVolumeClick);
    listItem.setTag(new Pair(volumPath, volumDescription));
    return listItem;
}

From source file:cc.flydev.launcher.Page.java

@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (DISABLE_TOUCH_INTERACTION) {
        return false;
    }/*from  w ww  . j  av  a  2  s. com*/

    super.onTouchEvent(ev);

    // Skip touch handling if there are no pages to swipe
    if (getChildCount() <= 0)
        return super.onTouchEvent(ev);

    acquireVelocityTrackerAndAddMovement(ev);

    final int action = ev.getAction();

    switch (action & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN:
        /*
         * If being flinged and user touches, stop the fling. isFinished
         * will be false if being flinged.
         */
        if (!mScroller.isFinished()) {
            mScroller.abortAnimation();
        }

        // Remember where the motion event started
        mDownMotionX = mLastMotionX = ev.getX();
        mDownMotionY = mLastMotionY = ev.getY();
        mDownScrollX = getScrollX();
        float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
        mParentDownMotionX = p[0];
        mParentDownMotionY = p[1];
        mLastMotionXRemainder = 0;
        mTotalMotionX = 0;
        mActivePointerId = ev.getPointerId(0);

        if (mTouchState == TOUCH_STATE_SCROLLING) {
            pageBeginMoving();
        }
        break;

    case MotionEvent.ACTION_MOVE:
        if (mTouchState == TOUCH_STATE_SCROLLING) {
            // Scroll to follow the motion event
            final int pointerIndex = ev.findPointerIndex(mActivePointerId);

            if (pointerIndex == -1)
                return true;

            final float x = ev.getX(pointerIndex);
            final float deltaX = mLastMotionX + mLastMotionXRemainder - x;

            mTotalMotionX += Math.abs(deltaX);

            // Only scroll and update mLastMotionX if we have moved some discrete amount.  We
            // keep the remainder because we are actually testing if we've moved from the last
            // scrolled position (which is discrete).
            if (Math.abs(deltaX) >= 1.0f) {
                mTouchX += deltaX;
                mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
                if (!mDeferScrollUpdate) {
                    scrollBy((int) deltaX, 0);
                    if (DEBUG)
                        Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
                } else {
                    invalidate();
                }
                mLastMotionX = x;
                mLastMotionXRemainder = deltaX - (int) deltaX;
            } else {
                awakenScrollBars();
            }
        } else if (mTouchState == TOUCH_STATE_REORDERING) {
            // Update the last motion position
            mLastMotionX = ev.getX();
            mLastMotionY = ev.getY();

            // Update the parent down so that our zoom animations take this new movement into
            // account
            float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
            mParentDownMotionX = pt[0];
            mParentDownMotionY = pt[1];
            updateDragViewTranslationDuringDrag();

            // Find the closest page to the touch point
            final int dragViewIndex = indexOfChild(mDragView);

            // Change the drag view if we are hovering over the drop target
            boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
                    (int) mParentDownMotionY);
            setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);

            if (DEBUG)
                Log.d(TAG, "mLastMotionX: " + mLastMotionX);
            if (DEBUG)
                Log.d(TAG, "mLastMotionY: " + mLastMotionY);
            if (DEBUG)
                Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
            if (DEBUG)
                Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);

            final int pageUnderPointIndex = getNearestHoverOverPageIndex();
            if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView)
                    && !isHoveringOverDelete) {
                mTempVisiblePagesRange[0] = 0;
                mTempVisiblePagesRange[1] = getPageCount() - 1;
                getOverviewModePages(mTempVisiblePagesRange);
                if (mTempVisiblePagesRange[0] <= pageUnderPointIndex
                        && pageUnderPointIndex <= mTempVisiblePagesRange[1]
                        && pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
                    mSidePageHoverIndex = pageUnderPointIndex;
                    mSidePageHoverRunnable = new Runnable() {
                        @Override
                        public void run() {
                            // Setup the scroll to the correct page before we swap the views
                            snapToPage(pageUnderPointIndex);

                            // For each of the pages between the paged view and the drag view,
                            // animate them from the previous position to the new position in
                            // the layout (as a result of the drag view moving in the layout)
                            int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
                            int lowerIndex = (dragViewIndex < pageUnderPointIndex) ? dragViewIndex + 1
                                    : pageUnderPointIndex;
                            int upperIndex = (dragViewIndex > pageUnderPointIndex) ? dragViewIndex - 1
                                    : pageUnderPointIndex;
                            for (int i = lowerIndex; i <= upperIndex; ++i) {
                                View v = getChildAt(i);
                                // dragViewIndex < pageUnderPointIndex, so after we remove the
                                // drag view all subsequent views to pageUnderPointIndex will
                                // shift down.
                                int oldX = getViewportOffsetX() + getChildOffset(i);
                                int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);

                                // Animate the view translation from its old position to its new
                                // position
                                AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
                                if (anim != null) {
                                    anim.cancel();
                                }

                                v.setTranslationX(oldX - newX);
                                anim = new AnimatorSet();
                                anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
                                anim.playTogether(ObjectAnimator.ofFloat(v, "translationX", 0f));
                                anim.start();
                                v.setTag(anim);
                            }

                            removeView(mDragView);
                            onRemoveView(mDragView, false);
                            addView(mDragView, pageUnderPointIndex);
                            onAddView(mDragView, pageUnderPointIndex);
                            mSidePageHoverIndex = -1;
                            mPageIndicator.setActiveMarker(getNextPage());
                        }
                    };
                    postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
                }
            } else {
                removeCallbacks(mSidePageHoverRunnable);
                mSidePageHoverIndex = -1;
            }
        } else {
            determineScrollingStart(ev);
        }
        break;

    case MotionEvent.ACTION_UP:
        if (mTouchState == TOUCH_STATE_SCROLLING) {
            final int activePointerId = mActivePointerId;
            final int pointerIndex = ev.findPointerIndex(activePointerId);
            final float x = ev.getX(pointerIndex);
            final VelocityTracker velocityTracker = mVelocityTracker;
            velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
            int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
            final int deltaX = (int) (x - mDownMotionX);
            final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
            boolean isSignificantMove = Math.abs(deltaX) > pageWidth * SIGNIFICANT_MOVE_THRESHOLD;

            mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);

            boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING
                    && Math.abs(velocityX) > mFlingThresholdVelocity;

            if (!mFreeScroll) {
                // In the case that the page is moved far to one direction and then is flung
                // in the opposite direction, we use a threshold to determine whether we should
                // just return to the starting page, or if we should skip one further.
                boolean returnToOriginalPage = false;
                if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD
                        && Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
                    returnToOriginalPage = true;
                }

                int finalPage;
                // We give flings precedence over large moves, which is why we short-circuit our
                // test for a large move if a fling has been registered. That is, a large
                // move to the left and fling to the right will register as a fling to the right.
                final boolean isRtl = isLayoutRtl();
                boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
                boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
                if (((isSignificantMove && !isDeltaXLeft && !isFling) || (isFling && !isVelocityXLeft))
                        && mCurrentPage > 0) {
                    finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
                    snapToPageWithVelocity(finalPage, velocityX);
                } else if (((isSignificantMove && isDeltaXLeft && !isFling) || (isFling && isVelocityXLeft))
                        && mCurrentPage < getChildCount() - 1) {
                    finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
                    snapToPageWithVelocity(finalPage, velocityX);
                } else {
                    snapToDestination();
                }
            } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
                // at this point we have not moved beyond the touch slop
                // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
                // we can just page
                int nextPage = Math.max(0, mCurrentPage - 1);
                if (nextPage != mCurrentPage) {
                    snapToPage(nextPage);
                } else {
                    snapToDestination();
                }
            } else {
                if (!mScroller.isFinished()) {
                    mScroller.abortAnimation();
                }

                float scaleX = getScaleX();
                int vX = (int) (-velocityX * scaleX);
                int initialScrollX = (int) (getScrollX() * scaleX);

                mScroller.fling(initialScrollX, getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0,
                        0);
                invalidate();
            }
        } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
            // at this point we have not moved beyond the touch slop
            // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
            // we can just page
            int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
            if (nextPage != mCurrentPage) {
                snapToPage(nextPage);
            } else {
                snapToDestination();
            }
        } else if (mTouchState == TOUCH_STATE_REORDERING) {
            // Update the last motion position
            mLastMotionX = ev.getX();
            mLastMotionY = ev.getY();

            // Update the parent down so that our zoom animations take this new movement into
            // account
            float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
            mParentDownMotionX = pt[0];
            mParentDownMotionY = pt[1];
            updateDragViewTranslationDuringDrag();
            boolean handledFling = false;
            if (!DISABLE_FLING_TO_DELETE) {
                // Check the velocity and see if we are flinging-to-delete
                PointF flingToDeleteVector = isFlingingToDelete();
                if (flingToDeleteVector != null) {
                    onFlingToDelete(flingToDeleteVector);
                    handledFling = true;
                }
            }
            if (!handledFling
                    && isHoveringOverDeleteDropTarget((int) mParentDownMotionX, (int) mParentDownMotionY)) {
                onDropToDelete();
            }
        } else {
            if (!mCancelTap) {
                onUnhandledTap(ev);
            }
        }

        // Remove the callback to wait for the side page hover timeout
        removeCallbacks(mSidePageHoverRunnable);
        // End any intermediate reordering states
        resetTouchState();
        break;

    case MotionEvent.ACTION_CANCEL:
        if (mTouchState == TOUCH_STATE_SCROLLING) {
            snapToDestination();
        }
        resetTouchState();
        break;

    case MotionEvent.ACTION_POINTER_UP:
        onSecondaryPointerUp(ev);
        releaseVelocityTracker();
        break;
    }

    return true;
}

From source file:com.n2hsu.launcher.Page.java

@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (DISABLE_TOUCH_INTERACTION) {
        return false;
    }/* w ww .  j  ava 2s .c  om*/

    super.onTouchEvent(ev);

    // Skip touch handling if there are no pages to swipe
    if (getChildCount() <= 0)
        return super.onTouchEvent(ev);

    acquireVelocityTrackerAndAddMovement(ev);

    final int action = ev.getAction();

    switch (action & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN:
        /*
         * If being flinged and user touches, stop the fling. isFinished
         * will be false if being flinged.
         */
        if (!mScroller.isFinished()) {
            mScroller.abortAnimation();
        }

        // Remember where the motion event started
        mDownMotionX = mLastMotionX = ev.getX();
        mDownMotionY = mLastMotionY = ev.getY();
        mDownScrollX = getScrollX();
        float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
        mParentDownMotionX = p[0];
        mParentDownMotionY = p[1];
        mLastMotionXRemainder = 0;
        mTotalMotionX = 0;
        mActivePointerId = ev.getPointerId(0);

        if (mTouchState == TOUCH_STATE_SCROLLING) {
            pageBeginMoving();
        }
        break;

    case MotionEvent.ACTION_MOVE:
        if (mTouchState == TOUCH_STATE_SCROLLING) {
            // Scroll to follow the motion event
            final int pointerIndex = ev.findPointerIndex(mActivePointerId);

            if (pointerIndex == -1)
                return true;

            final float x = ev.getX(pointerIndex);
            final float deltaX = mLastMotionX + mLastMotionXRemainder - x;

            mTotalMotionX += Math.abs(deltaX);

            // Only scroll and update mLastMotionX if we have moved some
            // discrete amount. We
            // keep the remainder because we are actually testing if we've
            // moved from the last
            // scrolled position (which is discrete).
            if (Math.abs(deltaX) >= 1.0f) {
                mTouchX += deltaX;
                mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
                if (!mDeferScrollUpdate) {
                    scrollBy((int) deltaX, 0);
                    if (DEBUG)
                        Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
                } else {
                    invalidate();
                }
                mLastMotionX = x;
                mLastMotionXRemainder = deltaX - (int) deltaX;
            } else {
                awakenScrollBars();
            }
        } else if (mTouchState == TOUCH_STATE_REORDERING) {
            // Update the last motion position
            mLastMotionX = ev.getX();
            mLastMotionY = ev.getY();

            // Update the parent down so that our zoom animations take this
            // new movement into
            // account
            float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
            mParentDownMotionX = pt[0];
            mParentDownMotionY = pt[1];
            updateDragViewTranslationDuringDrag();

            // Find the closest page to the touch point
            final int dragViewIndex = indexOfChild(mDragView);

            // Change the drag view if we are hovering over the drop target
            boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
                    (int) mParentDownMotionY);
            setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);

            if (DEBUG)
                Log.d(TAG, "mLastMotionX: " + mLastMotionX);
            if (DEBUG)
                Log.d(TAG, "mLastMotionY: " + mLastMotionY);
            if (DEBUG)
                Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
            if (DEBUG)
                Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);

            final int pageUnderPointIndex = getNearestHoverOverPageIndex();
            if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView)
                    && !isHoveringOverDelete) {
                mTempVisiblePagesRange[0] = 0;
                mTempVisiblePagesRange[1] = getPageCount() - 1;
                getOverviewModePages(mTempVisiblePagesRange);
                if (mTempVisiblePagesRange[0] <= pageUnderPointIndex
                        && pageUnderPointIndex <= mTempVisiblePagesRange[1]
                        && pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
                    mSidePageHoverIndex = pageUnderPointIndex;
                    mSidePageHoverRunnable = new Runnable() {
                        @Override
                        public void run() {
                            // Setup the scroll to the correct page before
                            // we swap the views
                            snapToPage(pageUnderPointIndex);

                            // For each of the pages between the paged view
                            // and the drag view,
                            // animate them from the previous position to
                            // the new position in
                            // the layout (as a result of the drag view
                            // moving in the layout)
                            int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
                            int lowerIndex = (dragViewIndex < pageUnderPointIndex) ? dragViewIndex + 1
                                    : pageUnderPointIndex;
                            int upperIndex = (dragViewIndex > pageUnderPointIndex) ? dragViewIndex - 1
                                    : pageUnderPointIndex;
                            for (int i = lowerIndex; i <= upperIndex; ++i) {
                                View v = getChildAt(i);
                                // dragViewIndex < pageUnderPointIndex, so
                                // after we remove the
                                // drag view all subsequent views to
                                // pageUnderPointIndex will
                                // shift down.
                                int oldX = getViewportOffsetX() + getChildOffset(i);
                                int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);

                                // Animate the view translation from its old
                                // position to its new
                                // position
                                AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
                                if (anim != null) {
                                    anim.cancel();
                                }

                                v.setTranslationX(oldX - newX);
                                anim = new AnimatorSet();
                                anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
                                anim.playTogether(ObjectAnimator.ofFloat(v, "translationX", 0f));
                                anim.start();
                                v.setTag(anim);
                            }

                            removeView(mDragView);
                            onRemoveView(mDragView, false);
                            addView(mDragView, pageUnderPointIndex);
                            onAddView(mDragView, pageUnderPointIndex);
                            mSidePageHoverIndex = -1;
                            mPageIndicator.setActiveMarker(getNextPage());
                        }
                    };
                    postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
                }
            } else {
                removeCallbacks(mSidePageHoverRunnable);
                mSidePageHoverIndex = -1;
            }
        } else {
            determineScrollingStart(ev);
        }
        break;

    case MotionEvent.ACTION_UP:
        if (mTouchState == TOUCH_STATE_SCROLLING) {
            final int activePointerId = mActivePointerId;
            final int pointerIndex = ev.findPointerIndex(activePointerId);
            final float x = ev.getX(pointerIndex);
            final VelocityTracker velocityTracker = mVelocityTracker;
            velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
            int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
            final int deltaX = (int) (x - mDownMotionX);
            final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
            boolean isSignificantMove = Math.abs(deltaX) > pageWidth * SIGNIFICANT_MOVE_THRESHOLD;

            mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);

            boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING
                    && Math.abs(velocityX) > mFlingThresholdVelocity;

            if (!mFreeScroll) {
                // In the case that the page is moved far to one direction
                // and then is flung
                // in the opposite direction, we use a threshold to
                // determine whether we should
                // just return to the starting page, or if we should skip
                // one further.
                boolean returnToOriginalPage = false;
                if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD
                        && Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
                    returnToOriginalPage = true;
                }

                int finalPage;
                // We give flings precedence over large moves, which is why
                // we short-circuit our
                // test for a large move if a fling has been registered.
                // That is, a large
                // move to the left and fling to the right will register as
                // a fling to the right.
                final boolean isRtl = isLayoutRtl();
                boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
                boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
                if (((isSignificantMove && !isDeltaXLeft && !isFling) || (isFling && !isVelocityXLeft))
                        && mCurrentPage > 0) {
                    finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
                    snapToPageWithVelocity(finalPage, velocityX);
                } else if (((isSignificantMove && isDeltaXLeft && !isFling) || (isFling && isVelocityXLeft))
                        && mCurrentPage < getChildCount() - 1) {
                    finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
                    snapToPageWithVelocity(finalPage, velocityX);
                } else {
                    snapToDestination();
                }
            } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
                // at this point we have not moved beyond the touch slop
                // (otherwise mTouchState would be TOUCH_STATE_SCROLLING),
                // so
                // we can just page
                int nextPage = Math.max(0, mCurrentPage - 1);
                if (nextPage != mCurrentPage) {
                    snapToPage(nextPage);
                } else {
                    snapToDestination();
                }
            } else {
                if (!mScroller.isFinished()) {
                    mScroller.abortAnimation();
                }

                float scaleX = getScaleX();
                int vX = (int) (-velocityX * scaleX);
                int initialScrollX = (int) (getScrollX() * scaleX);

                mScroller.fling(initialScrollX, getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0,
                        0);
                invalidate();
            }
        } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
            // at this point we have not moved beyond the touch slop
            // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
            // we can just page
            int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
            if (nextPage != mCurrentPage) {
                snapToPage(nextPage);
            } else {
                snapToDestination();
            }
        } else if (mTouchState == TOUCH_STATE_REORDERING) {
            // Update the last motion position
            mLastMotionX = ev.getX();
            mLastMotionY = ev.getY();

            // Update the parent down so that our zoom animations take this
            // new movement into
            // account
            float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
            mParentDownMotionX = pt[0];
            mParentDownMotionY = pt[1];
            updateDragViewTranslationDuringDrag();
            boolean handledFling = false;
            if (!DISABLE_FLING_TO_DELETE) {
                // Check the velocity and see if we are flinging-to-delete
                PointF flingToDeleteVector = isFlingingToDelete();
                if (flingToDeleteVector != null) {
                    onFlingToDelete(flingToDeleteVector);
                    handledFling = true;
                }
            }
            if (!handledFling
                    && isHoveringOverDeleteDropTarget((int) mParentDownMotionX, (int) mParentDownMotionY)) {
                onDropToDelete();
            }
        } else {
            if (!mCancelTap) {
                onUnhandledTap(ev);
            }
        }

        // Remove the callback to wait for the side page hover timeout
        removeCallbacks(mSidePageHoverRunnable);
        // End any intermediate reordering states
        resetTouchState();
        break;

    case MotionEvent.ACTION_CANCEL:
        if (mTouchState == TOUCH_STATE_SCROLLING) {
            snapToDestination();
        }
        resetTouchState();
        break;

    case MotionEvent.ACTION_POINTER_UP:
        onSecondaryPointerUp(ev);
        releaseVelocityTracker();
        break;
    }

    return true;
}

From source file:com.jtschohl.androidfirewall.MainActivity.java

/**
 * Show the list of applications/*w ww. j  a  v  a  2  s  . c o  m*/
 * 
 * Thanks to Ukanth for the Search code so I didn't have to reinvent the
 * wheel
 * 
 */
private void createListView(final String searching) {
    this.dirty = false;
    List<DroidApp> namesearch = new ArrayList<DroidApp>();
    final List<DroidApp> appnames = Api.getApps(this);
    boolean isResultsFound = false;
    if (searching != null && searching.length() > 1) {
        for (DroidApp app : appnames) {
            for (String str : app.names) {
                if (str.contains(searching.toLowerCase())
                        || str.toLowerCase().contains(searching.toLowerCase())) {
                    namesearch.add(app);
                    isResultsFound = true;
                }
            }
        }
    }
    final List<DroidApp> apps = isResultsFound ? namesearch
            : searching.equals("") ? appnames : new ArrayList<Api.DroidApp>();
    // Sort applications - selected first, then alphabetically
    Collections.sort(apps, new sortList());

    final LayoutInflater inflater = getLayoutInflater();
    final ListAdapter adapter = new ArrayAdapter<DroidApp>(this, R.layout.listitem, R.id.itemtext, apps) {
        SharedPreferences prefs = getSharedPreferences(Api.PREFS_NAME, 0);
        boolean vpnenabled = prefs.getBoolean(Api.PREF_VPNENABLED, false);
        boolean roamenabled = prefs.getBoolean(Api.PREF_ROAMENABLED, false);
        boolean lanenabled = prefs.getBoolean(Api.PREF_LANENABLED, false);
        boolean inputwifienabled = prefs.getBoolean(Api.PREF_INPUTENABLED, false);

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ListEntry entry;
            if (convertView == null) {
                // Inflate a new view
                convertView = inflater.inflate(R.layout.listitem, parent, false);
                Log.d(TAG, ">> inflate(" + convertView + ")");
                entry = new ListEntry();
                entry.box_wifi = (CheckBox) convertView.findViewById(R.id.itemcheck_wifi);
                entry.box_3g = (CheckBox) convertView.findViewById(R.id.itemcheck_3g);
                entry.box_roaming = (CheckBox) convertView.findViewById(R.id.itemcheck_roam);
                entry.box_vpn = (CheckBox) convertView.findViewById(R.id.itemcheck_vpn);
                entry.box_lan = (CheckBox) convertView.findViewById(R.id.itemcheck_lan);
                entry.box_input_wifi = (CheckBox) convertView.findViewById(R.id.itemcheck_input_wifi);
                if (vpnenabled) {
                    entry.box_vpn.setVisibility(View.VISIBLE);
                }
                if (roamenabled) {
                    entry.box_roaming.setVisibility(View.VISIBLE);
                }
                if (lanenabled) {
                    entry.box_lan.setVisibility(View.VISIBLE);
                }
                if (inputwifienabled) {
                    entry.box_input_wifi.setVisibility(View.VISIBLE);
                }
                entry.text = (TextView) convertView.findViewById(R.id.itemtext);
                entry.icon = (ImageView) convertView.findViewById(R.id.itemicon);
                entry.box_wifi.setOnCheckedChangeListener(MainActivity.this);
                entry.box_3g.setOnCheckedChangeListener(MainActivity.this);
                entry.box_roaming.setOnCheckedChangeListener(MainActivity.this);
                entry.box_vpn.setOnCheckedChangeListener(MainActivity.this);
                entry.box_lan.setOnCheckedChangeListener(MainActivity.this);
                entry.box_input_wifi.setOnCheckedChangeListener(MainActivity.this);
                convertView.setTag(entry);
            } else {
                // Convert an existing view
                entry = (ListEntry) convertView.getTag();
                entry.box_wifi = (CheckBox) convertView.findViewById(R.id.itemcheck_wifi);
                entry.box_3g = (CheckBox) convertView.findViewById(R.id.itemcheck_3g);
                if (vpnenabled) {
                    entry.box_vpn.setVisibility(View.VISIBLE);
                }
                if (roamenabled) {
                    entry.box_roaming.setVisibility(View.VISIBLE);
                }
                if (lanenabled) {
                    entry.box_lan.setVisibility(View.VISIBLE);
                }
                if (inputwifienabled) {
                    entry.box_input_wifi.setVisibility(View.VISIBLE);
                }
                entry.box_roaming = (CheckBox) convertView.findViewById(R.id.itemcheck_roam);
                entry.box_vpn = (CheckBox) convertView.findViewById(R.id.itemcheck_vpn);
                entry.box_lan = (CheckBox) convertView.findViewById(R.id.itemcheck_lan);
                entry.box_input_wifi = (CheckBox) convertView.findViewById(R.id.itemcheck_input_wifi);
            }
            entry.app = apps.get(position);
            entry.text.setText(entry.app.toString());
            entry.icon.setImageDrawable(entry.app.cached_icon);
            if (!entry.app.icon_loaded && entry.app.appinfo != null) {
                // this icon has not been loaded yet - load it on a
                // separated thread
                try {
                    new LoadIconTask().execute(entry.app, getPackageManager(), convertView);
                } catch (RejectedExecutionException r) {

                }
            }
            final CheckBox box_wifi = entry.box_wifi;
            box_wifi.setTag(entry.app);
            box_wifi.setChecked(entry.app.selected_wifi);
            final CheckBox box_3g = entry.box_3g;
            box_3g.setTag(entry.app);
            box_3g.setChecked(entry.app.selected_3g);
            final CheckBox box_roaming = entry.box_roaming;
            box_roaming.setTag(entry.app);
            box_roaming.setChecked(entry.app.selected_roaming);
            final CheckBox box_vpn = entry.box_vpn;
            box_vpn.setTag(entry.app);
            box_vpn.setChecked(entry.app.selected_vpn);
            final CheckBox box_lan = entry.box_lan;
            box_lan.setTag(entry.app);
            box_lan.setChecked(entry.app.selected_lan);
            final CheckBox box_input_wifi = entry.box_input_wifi;
            box_input_wifi.setTag(entry.app);
            box_input_wifi.setChecked(entry.app.selected_input_wifi);
            return convertView;
        }
    };
    if (listview == null) {
        Api.applications = null;
        showOrLoadApplications();
    } else {
        this.listview.setAdapter(adapter);
    }
}

From source file:com.klinker.android.launcher.launcher3.Launcher.java

public void startDrag(View dragView, ItemInfo dragInfo, DragSource source) {
    dragView.setTag(dragInfo);
    mWorkspace.onExternalDragStartedWithItem(dragView);
    mWorkspace.beginExternalDragShared(dragView, source);
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

@SuppressLint("InlinedApi")
private void openGridGallery() {
    final int tnSize = resources.getDimensionPixelSize(R.dimen.post_thumbnail_size);

    class GridGalleryAdapter extends ArrayAdapter<Triple<AttachmentModel, String, String>>
            implements View.OnClickListener, AbsListView.OnScrollListener {
        private final GridView view;
        private boolean selectingMode = false;
        private boolean[] isSelected = null;
        private volatile boolean isBusy = false;

        public GridGalleryAdapter(GridView view, List<Triple<AttachmentModel, String, String>> list) {
            super(activity, 0, list);
            this.view = view;
            this.isSelected = new boolean[list.size()];
        }//w  ww.j av  a  2  s  . com

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                if (isBusy)
                    setNonBusy();
                isBusy = false;
            } else
                isBusy = true;
        }

        private void setNonBusy() {
            if (!downloadThumbnails())
                return;
            for (int i = 0; i < view.getChildCount(); ++i) {
                View v = view.getChildAt(i);
                Object tnTag = v.findViewById(R.id.post_thumbnail_image).getTag();
                if (tnTag == null || tnTag == Boolean.FALSE)
                    fill(view.getPositionForView(v), v, false);
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = new FrameLayout(activity);
                convertView.setLayoutParams(new AbsListView.LayoutParams(tnSize, tnSize));
                ImageView tnImage = new ImageView(activity);
                tnImage.setLayoutParams(new FrameLayout.LayoutParams(tnSize, tnSize, Gravity.CENTER));
                tnImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                tnImage.setId(R.id.post_thumbnail_image);
                ((FrameLayout) convertView).addView(tnImage);
            }
            convertView.setTag(getItem(position).getLeft());
            safeRegisterForContextMenu(convertView);
            convertView.setOnClickListener(this);
            fill(position, convertView, isBusy);
            if (isSelected[position]) {
                /*ImageView overlay = new ImageView(activity);
                overlay.setImageResource(android.R.drawable.checkbox_on_background);*/
                FrameLayout overlay = new FrameLayout(activity);
                overlay.setBackgroundColor(Color.argb(128, 0, 255, 0));
                if (((FrameLayout) convertView).getChildCount() < 2)
                    ((FrameLayout) convertView).addView(overlay);

            } else {
                if (((FrameLayout) convertView).getChildCount() > 1)
                    ((FrameLayout) convertView).removeViewAt(1);
            }
            return convertView;
        }

        private void safeRegisterForContextMenu(View view) {
            try {
                view.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
                    @Override
                    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
                        if (presentationModel == null) {
                            Fragment currentFragment = MainApplication
                                    .getInstance().tabsSwitcher.currentFragment;
                            if (currentFragment instanceof BoardFragment) {
                                currentFragment.onCreateContextMenu(menu, v, menuInfo);
                            }
                        } else {
                            BoardFragment.this.onCreateContextMenu(menu, v, menuInfo);
                        }
                    }
                });
            } catch (Exception e) {
                Logger.e(TAG, e);
            }
        }

        @Override
        public void onClick(View v) {
            if (selectingMode) {
                int position = view.getPositionForView(v);
                isSelected[position] = !isSelected[position];
                notifyDataSetChanged();
            } else {
                BoardFragment fragment = BoardFragment.this;
                if (presentationModel == null) {
                    Fragment currentFragment = MainApplication.getInstance().tabsSwitcher.currentFragment;
                    if (currentFragment instanceof BoardFragment)
                        fragment = (BoardFragment) currentFragment;
                }
                fragment.openAttachment((AttachmentModel) v.getTag());
            }
        }

        private void fill(int position, View view, boolean isBusy) {
            AttachmentModel attachment = getItem(position).getLeft();
            String attachmentHash = getItem(position).getMiddle();
            ImageView tnImage = (ImageView) view.findViewById(R.id.post_thumbnail_image);
            if (attachment.thumbnail == null || attachment.thumbnail.length() == 0) {
                tnImage.setTag(Boolean.TRUE);
                tnImage.setImageResource(Attachments.getDefaultThumbnailResId(attachment.type));
                return;
            }
            tnImage.setTag(Boolean.FALSE);
            CancellableTask imagesDownloadTask = BoardFragment.this.imagesDownloadTask;
            ExecutorService imagesDownloadExecutor = BoardFragment.this.imagesDownloadExecutor;
            if (presentationModel == null) {
                Fragment currentFragment = MainApplication.getInstance().tabsSwitcher.currentFragment;
                if (currentFragment instanceof BoardFragment) {
                    imagesDownloadTask = ((BoardFragment) currentFragment).imagesDownloadTask;
                    imagesDownloadExecutor = ((BoardFragment) currentFragment).imagesDownloadExecutor;
                }
            }
            bitmapCache.asyncGet(attachmentHash, attachment.thumbnail, tnSize, chan, localFile,
                    imagesDownloadTask, tnImage, imagesDownloadExecutor, Async.UI_HANDLER,
                    downloadThumbnails() && !isBusy,
                    downloadThumbnails() ? (isBusy ? 0 : R.drawable.thumbnail_error)
                            : Attachments.getDefaultThumbnailResId(attachment.type));
        }

        public void setSelectingMode(boolean selectingMode) {
            this.selectingMode = selectingMode;
            if (!selectingMode) {
                Arrays.fill(isSelected, false);
                notifyDataSetChanged();
            }
        }

        public void selectAll() {
            if (selectingMode) {
                Arrays.fill(isSelected, true);
                notifyDataSetChanged();
            }
        }

        public void downloadSelected(final Runnable onFinish) {
            final Dialog progressDialog = ProgressDialog.show(activity,
                    resources.getString(R.string.grid_gallery_dlg_title),
                    resources.getString(R.string.grid_gallery_dlg_message), true, false);
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    BoardFragment fragment = BoardFragment.this;
                    if (fragment.presentationModel == null) {
                        Fragment currentFragment = MainApplication.getInstance().tabsSwitcher.currentFragment;
                        if (currentFragment instanceof BoardFragment)
                            fragment = (BoardFragment) currentFragment;
                    }
                    boolean flag = false;
                    for (int i = 0; i < isSelected.length; ++i)
                        if (isSelected[i])
                            if (!fragment.downloadFile(getItem(i).getLeft(), true))
                                flag = true;
                    final boolean toast = flag;
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (toast)
                                Toast.makeText(activity, R.string.notification_download_exists_or_in_queue,
                                        Toast.LENGTH_LONG).show();
                            progressDialog.dismiss();
                            onFinish.run();
                        }
                    });
                }
            });
        }
    }

    try {
        List<Triple<AttachmentModel, String, String>> list = presentationModel.getAttachments();
        if (list == null) {
            Toast.makeText(activity, R.string.notifacation_updating_now, Toast.LENGTH_LONG).show();
            return;
        }

        GridView grid = new GridView(activity);
        final GridGalleryAdapter gridAdapter = new GridGalleryAdapter(grid, list);
        grid.setNumColumns(GridView.AUTO_FIT);
        grid.setColumnWidth(tnSize);
        int spacing = (int) (resources.getDisplayMetrics().density * 5 + 0.5f);
        grid.setVerticalSpacing(spacing);
        grid.setHorizontalSpacing(spacing);
        grid.setPadding(spacing, spacing, spacing, spacing);
        grid.setAdapter(gridAdapter);
        grid.setOnScrollListener(gridAdapter);
        grid.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));

        final Button btnToSelecting = new Button(activity);
        btnToSelecting.setText(R.string.grid_gallery_select);
        CompatibilityUtils.setTextAppearance(btnToSelecting, android.R.style.TextAppearance_Small);
        btnToSelecting.setSingleLine();
        btnToSelecting.setVisibility(View.VISIBLE);
        btnToSelecting.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));

        final LinearLayout layoutSelectingButtons = new LinearLayout(activity);
        layoutSelectingButtons.setOrientation(LinearLayout.HORIZONTAL);
        layoutSelectingButtons.setWeightSum(10f);
        Button btnDownload = new Button(activity);
        btnDownload.setLayoutParams(
                new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3.25f));
        btnDownload.setText(R.string.grid_gallery_download);
        CompatibilityUtils.setTextAppearance(btnDownload, android.R.style.TextAppearance_Small);
        btnDownload.setSingleLine();
        Button btnSelectAll = new Button(activity);
        btnSelectAll.setLayoutParams(
                new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3.75f));
        btnSelectAll.setText(android.R.string.selectAll);
        CompatibilityUtils.setTextAppearance(btnSelectAll, android.R.style.TextAppearance_Small);
        btnSelectAll.setSingleLine();
        Button btnCancel = new Button(activity);
        btnCancel.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f));
        btnCancel.setText(android.R.string.cancel);
        CompatibilityUtils.setTextAppearance(btnCancel, android.R.style.TextAppearance_Small);
        btnCancel.setSingleLine();
        layoutSelectingButtons.addView(btnDownload);
        layoutSelectingButtons.addView(btnSelectAll);
        layoutSelectingButtons.addView(btnCancel);
        layoutSelectingButtons.setVisibility(View.GONE);
        layoutSelectingButtons.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

        btnToSelecting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnToSelecting.setVisibility(View.GONE);
                layoutSelectingButtons.setVisibility(View.VISIBLE);
                gridAdapter.setSelectingMode(true);
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnToSelecting.setVisibility(View.VISIBLE);
                layoutSelectingButtons.setVisibility(View.GONE);
                gridAdapter.setSelectingMode(false);
            }
        });

        btnSelectAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gridAdapter.selectAll();
            }
        });

        btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gridAdapter.downloadSelected(new Runnable() {
                    @Override
                    public void run() {
                        btnToSelecting.setVisibility(View.VISIBLE);
                        layoutSelectingButtons.setVisibility(View.GONE);
                        gridAdapter.setSelectingMode(false);
                    }
                });
            }
        });

        LinearLayout dlgLayout = new LinearLayout(activity);
        dlgLayout.setOrientation(LinearLayout.VERTICAL);
        dlgLayout.addView(btnToSelecting);
        dlgLayout.addView(layoutSelectingButtons);
        dlgLayout.addView(grid);

        Dialog gridDialog = new Dialog(activity);
        gridDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        gridDialog.setContentView(dlgLayout);
        gridDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        gridDialog.show();
    } catch (OutOfMemoryError oom) {
        MainApplication.freeMemory();
        Logger.e(TAG, oom);
        Toast.makeText(activity, R.string.error_out_of_memory, Toast.LENGTH_LONG).show();
    }
}