Example usage for android.view Gravity CENTER

List of usage examples for android.view Gravity CENTER

Introduction

In this page you can find the example usage for android.view Gravity CENTER.

Prototype

int CENTER

To view the source code for android.view Gravity CENTER.

Click Source Link

Document

Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.

Usage

From source file:com.ichi2.anki2.Reviewer.java

private void setInterface() {
    if (mCurrentCard == null) {
        return;/*from ww w .jav  a 2s .  c  o m*/
    }
    if (mSimpleInterface) {
        Note note = mCurrentCard.note();
        mCurrentSimpleInterface = true;
        for (String s : mSimpleInterfaceExcludeTags) {
            if (note.hasTag(s)) {
                mCurrentSimpleInterface = false;
                break;
            }
        }
    }
    if (mCurrentSimpleInterface) {
        if (mSimpleCard == null) {
            mSimpleCard = new ScrollTextView(this);
            Themes.setRegularFont(mSimpleCard);
            mSimpleCard.setTextSize(mSimpleCard.getTextSize() * mDisplayFontSize / 100);
            mSimpleCard.setGravity(Gravity.CENTER);
            try {
                mSetTextIsSelectable = TextView.class.getMethod("setTextIsSelectable", boolean.class);
            } catch (Throwable e) {
                Log.i(AnkiDroidApp.TAG,
                        "mSetTextIsSelectable could not be found due to a too low Android version (< 3.0)");
                mSetTextIsSelectable = null;
            }
            if (mSetTextIsSelectable != null) {
                try {
                    mSetTextIsSelectable.invoke(mSimpleCard, true);
                } catch (Exception e) {
                    Log.e(AnkiDroidApp.TAG, e.toString());
                }
            }
            mSimpleCard.setClickable(true);
            mCardFrame.addView(mSimpleCard);

            mSimpleCard.setBackgroundColor(mCurrentBackgroundColor);
            mSimpleCard.setTextColor(mForegroundColor);
        }
        if (mSimpleCard.getVisibility() != View.VISIBLE
                || (mCard != null && mCard.getVisibility() == View.VISIBLE)) {
            mSimpleCard.setVisibility(View.VISIBLE);
            mCard.setVisibility(View.GONE);
        }
    } else {
        if (mCard == null) {
            mCard = createWebView();
            mCardFrame.addView(mCard);
            if (mRefreshWebview) {
                mNextCard = createWebView();
                mNextCard.setVisibility(View.GONE);
                mCardFrame.addView(mNextCard, 0);
                mCard.setBackgroundColor(mCurrentBackgroundColor);

                mCustomFontStyle = getCustomFontsStyle() + getDefaultFontStyle();
            }
        }
        if (mCard.getVisibility() != View.VISIBLE
                || (mSimpleCard != null && mSimpleCard.getVisibility() == View.VISIBLE)) {
            mSimpleCard.setVisibility(View.GONE);
            mCard.setVisibility(View.VISIBLE);
        }
    }
}

From source file:com.hichinaschool.flashcards.anki.Reviewer.java

private void setInterface() {
    if (mCurrentCard == null) {
        return;/* ww w  . j a  v  a 2s.  c om*/
    }
    if (mSimpleInterface) {
        Note note = mCurrentCard.note();
        mCurrentSimpleInterface = true;
        for (String s : mSimpleInterfaceExcludeTags) {
            if (note.hasTag(s)) {
                mCurrentSimpleInterface = false;
                break;
            }
        }
    }
    if (mCurrentSimpleInterface) {
        if (mSimpleCard == null) {
            mSimpleCard = new ScrollTextView(this);
            Themes.setRegularFont(mSimpleCard);
            mSimpleCard.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10,
                    getResources().getDisplayMetrics()) * mDisplayFontSize / 100);
            mSimpleCard.setGravity(Gravity.CENTER);
            try {
                mSetTextIsSelectable = TextView.class.getMethod("setTextIsSelectable", boolean.class);
            } catch (Throwable e) {
                // Log.i(AnkiDroidApp.TAG, "mSetTextIsSelectable could not be found due to a too low Android version (< 3.0)");
                mSetTextIsSelectable = null;
            }
            if (mSetTextIsSelectable != null) {
                try {
                    mSetTextIsSelectable.invoke(mSimpleCard, true);
                } catch (Exception e) {
                    Log.e(AnkiDroidApp.TAG, e.toString());
                }
            }
            mSimpleCard.setClickable(true);
            mCardFrame.addView(mSimpleCard);

            mSimpleCard.setBackgroundColor(mCurrentBackgroundColor);
            mSimpleCard.setTextColor(mForegroundColor);
        }
        if (mSimpleCard.getVisibility() != View.VISIBLE
                || (mCard != null && mCard.getVisibility() == View.VISIBLE)) {
            mSimpleCard.setVisibility(View.VISIBLE);
            mCard.setVisibility(View.GONE);
        }
    } else {
        if (mCard == null) {
            mCard = createWebView();
            mCardFrame.addView(mCard);
            if (!mUseQuickUpdate) {
                mNextCard = createWebView();
                mNextCard.setVisibility(View.GONE);
                mCardFrame.addView(mNextCard, 0);
                mCard.setBackgroundColor(mCurrentBackgroundColor);

                mCustomFontStyle = getCustomFontsStyle() + getDefaultFontStyle();
            }
        }
        if (mCard.getVisibility() != View.VISIBLE
                || (mSimpleCard != null && mSimpleCard.getVisibility() == View.VISIBLE)) {
            mSimpleCard.setVisibility(View.GONE);
            mCard.setVisibility(View.VISIBLE);
        }
    }
}

From source file:com.stikyhive.stikyhive.ChattingActivity.java

@Override
public void onBackPressed() {
    if (flagRecord) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, 0);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutTalk.setLayoutParams(params);
        layoutTalk.setGravity(Gravity.CENTER);
        flagRecord = false;/*from  w w w  .ja  va  2  s . co m*/
    } else if (noti) {
        Intent intent = new Intent("com.arctech.BROWSEACTIVITY");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    } else {
        super.onBackPressed();
        StikyChatMoreActivity.flagStart = false;
        finish();
    }
}

From source file:brighton.uni.usmappedapp.Map.java

private void AboutPopupWindow() {
    try {/*ww w.  ja v  a  2  s  . c  o m*/
        // We need to get the instance of the LayoutInflater
        LayoutInflater inflater = (LayoutInflater) Map.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //
        View layout = inflater.inflate(R.layout.popup_layout, (ViewGroup) findViewById(R.id.popup_element)); //
        String pp = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(this); //Retrieves a information set from google
        pwindo = new PopupWindow(layout, 400, 700, true); // creates and sets the valuse of the popup window
        pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0); // sets the location
        pwindo.setOutsideTouchable(true);
        pwindo.setTouchable(true);

        // create button to be able to close the popup
        btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
        btnClosePopup.setOnClickListener(close_bnt_CL);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:brighton.uni.usmappedapp.Map.java

private void HowToPopupWindow() {
    try {// ww w  .  ja v  a 2s .  co m
        // We need to get the instance of the LayoutInflater
        LayoutInflater inflater = (LayoutInflater) Map.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.popup_layout2, (ViewGroup) findViewById(R.id.popup_element));
        pwindo2 = new PopupWindow(layout, 500, 870, true);
        pwindo2.showAtLocation(layout, Gravity.CENTER, 0, 0);
        pwindo2.setOutsideTouchable(true);
        pwindo2.setTouchable(true);

        //
        btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
        btnClosePopup.setOnClickListener(close_bnt_CL_2);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.android.tv.MainActivity.java

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    /*//  w ww . j  a v a 2s  .c  om
     * The following keyboard keys map to these remote keys or "debug actions"
     *  - --------
     *  A KEYCODE_MEDIA_AUDIO_TRACK
     *  D debug: show debug options
     *  E updateChannelBannerAndShowIfNeeded
     *  I KEYCODE_TV_INPUT
     *  O debug: show display mode option
     *  P debug: togglePipView
     *  S KEYCODE_CAPTIONS: select subtitle
     *  W debug: toggle screen size
     *  V KEYCODE_MEDIA_RECORD debug: record the current channel for 30 sec
     *  X KEYCODE_BUTTON_X KEYCODE_PROG_BLUE debug: record current channel for a few minutes
     *  Y KEYCODE_BUTTON_Y KEYCODE_PROG_GREEN debug: Play a recording
     */
    if (SystemProperties.LOG_KEYEVENT.getValue()) {
        Log.d(TAG, "onKeyUp(" + keyCode + ", " + event + ")");
    }
    // If we are in the middle of channel change, finish it before showing overlays.
    finishChannelChangeIfNeeded();

    if (event.getKeyCode() == KeyEvent.KEYCODE_SEARCH) {
        showSearchActivity();
        return true;
    }
    switch (mOverlayManager.onKeyUp(keyCode, event)) {
    case KEY_EVENT_HANDLER_RESULT_DISPATCH_TO_OVERLAY:
        return super.onKeyUp(keyCode, event);
    case KEY_EVENT_HANDLER_RESULT_HANDLED:
        return true;
    case KEY_EVENT_HANDLER_RESULT_NOT_HANDLED:
        return false;
    case KEY_EVENT_HANDLER_RESULT_PASSTHROUGH:
    default:
        // pass through
    }
    if (mSearchFragment.isVisible()) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            getFragmentManager().popBackStack();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // When the event is from onUnhandledInputEvent, onBackPressed is not automatically
        // called. Therefore, we need to explicitly call onBackPressed().
        onBackPressed();
        return true;
    }

    if (!mChannelTuner.areAllChannelsLoaded()) {
        // Now channel map is under loading.
    } else if (mChannelTuner.getBrowsableChannelCount() == 0) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_CHANNEL_UP:
        case KeyEvent.KEYCODE_DPAD_UP:
        case KeyEvent.KEYCODE_CHANNEL_DOWN:
        case KeyEvent.KEYCODE_DPAD_DOWN:
        case KeyEvent.KEYCODE_NUMPAD_ENTER:
        case KeyEvent.KEYCODE_DPAD_CENTER:
        case KeyEvent.KEYCODE_E:
        case KeyEvent.KEYCODE_MENU:
            showSettingsFragment();
            return true;
        }
    } else {
        if (KeypadChannelSwitchView.isChannelNumberKey(keyCode)) {
            showKeypadChannelSwitchView(keyCode);
            return true;
        }
        switch (keyCode) {
        case KeyEvent.KEYCODE_DPAD_RIGHT:
            if (!PermissionUtils.hasModifyParentalControls(this)) {
                // TODO: support this feature for non-system LC app. b/23939816
                return true;
            }
            PinDialogFragment dialog = null;
            if (mTvView.isScreenBlocked()) {
                dialog = new PinDialogFragment(PinDialogFragment.PIN_DIALOG_TYPE_UNLOCK_CHANNEL,
                        new PinDialogFragment.ResultListener() {
                            @Override
                            public void done(boolean success) {
                                if (success) {
                                    unblockScreen(mTvView);
                                    mIsCurrentChannelUnblockedByUser = true;
                                }
                            }
                        });
            } else if (mTvView.getBlockedContentRating() != null) {
                final TvContentRating rating = mTvView.getBlockedContentRating();
                dialog = new PinDialogFragment(PinDialogFragment.PIN_DIALOG_TYPE_UNLOCK_PROGRAM,
                        new PinDialogFragment.ResultListener() {
                            @Override
                            public void done(boolean success) {
                                if (success) {
                                    mLastAllowedRatingForCurrentChannel = rating;
                                    mTvView.unblockContent(rating);
                                }
                            }
                        });
            }
            if (dialog != null) {
                mOverlayManager.showDialogFragment(PinDialogFragment.DIALOG_TAG, dialog, false);
            }
            return true;

        case KeyEvent.KEYCODE_ENTER:
        case KeyEvent.KEYCODE_NUMPAD_ENTER:
        case KeyEvent.KEYCODE_E:
        case KeyEvent.KEYCODE_DPAD_CENTER:
        case KeyEvent.KEYCODE_MENU:
            if (event.isCanceled()) {
                // Ignore canceled key.
                // Note that if there's a TIS granted RECEIVE_INPUT_EVENT,
                // fallback keys not blacklisted will have FLAG_CANCELED.
                // See dispatchKeyEvent() for detail.
                return true;
            }
            if (keyCode != KeyEvent.KEYCODE_MENU) {
                updateChannelBannerAndShowIfNeeded(UPDATE_CHANNEL_BANNER_REASON_FORCE_SHOW);
            }
            if (keyCode != KeyEvent.KEYCODE_E) {
                mOverlayManager.showMenu(
                        mTvView.isRecordingPlayback() ? Menu.REASON_RECORDING_PLAYBACK : Menu.REASON_NONE);
            }
            return true;
        case KeyEvent.KEYCODE_CHANNEL_UP:
        case KeyEvent.KEYCODE_DPAD_UP:
        case KeyEvent.KEYCODE_CHANNEL_DOWN:
        case KeyEvent.KEYCODE_DPAD_DOWN:
            // Channel change is already done in the head of this method.
            return true;
        case KeyEvent.KEYCODE_S:
            if (!SystemProperties.USE_DEBUG_KEYS.getValue()) {
                break;
            }
        case KeyEvent.KEYCODE_CAPTIONS: {
            mOverlayManager.getSideFragmentManager().show(new ClosedCaptionFragment());
            return true;
        }
        case KeyEvent.KEYCODE_A:
            if (!SystemProperties.USE_DEBUG_KEYS.getValue()) {
                break;
            }
        case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK: {
            mOverlayManager.getSideFragmentManager().show(new MultiAudioFragment());
            return true;
        }
        case KeyEvent.KEYCODE_GUIDE: {
            mOverlayManager.showProgramGuide();
            return true;
        }
        case KeyEvent.KEYCODE_INFO: {
            mOverlayManager.showBanner();
            return true;
        }
        }
    }
    if (SystemProperties.USE_DEBUG_KEYS.getValue()) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_W: {
            mDebugNonFullSizeScreen = !mDebugNonFullSizeScreen;
            if (mDebugNonFullSizeScreen) {
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mTvView.getLayoutParams();
                params.width = 960;
                params.height = 540;
                params.gravity = Gravity.START;
                mTvView.setLayoutParams(params);
            } else {
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mTvView.getLayoutParams();
                params.width = ViewGroup.LayoutParams.MATCH_PARENT;
                params.height = ViewGroup.LayoutParams.MATCH_PARENT;
                params.gravity = Gravity.CENTER;
                mTvView.setLayoutParams(params);
            }
            return true;
        }
        case KeyEvent.KEYCODE_P: {
            togglePipView();
            return true;
        }
        case KeyEvent.KEYCODE_CTRL_LEFT:
        case KeyEvent.KEYCODE_CTRL_RIGHT: {
            mUseKeycodeBlacklist = !mUseKeycodeBlacklist;
            return true;
        }
        case KeyEvent.KEYCODE_O: {
            mOverlayManager.getSideFragmentManager().show(new DisplayModeFragment());
            return true;
        }

        case KeyEvent.KEYCODE_D:
            mOverlayManager.getSideFragmentManager().show(new DebugOptionFragment());
            return true;

        case KeyEvent.KEYCODE_MEDIA_RECORD: // TODO(DVR) handle with debug_keys set
        case KeyEvent.KEYCODE_V: {
            DvrManager dvrManager = TvApplication.getSingletons(this).getDvrManager();
            long startTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(5);
            long endTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(35);
            dvrManager.addSchedule(getCurrentChannel(), startTime, endTime);
            return true;
        }
        case KeyEvent.KEYCODE_PROG_BLUE:
        case KeyEvent.KEYCODE_BUTTON_X:
        case KeyEvent.KEYCODE_X: {
            if (CommonFeatures.DVR.isEnabled(this)) {
                Channel channel = mTvView.getCurrentChannel();
                long channelId = channel.getId();
                Program p = mProgramDataManager.getCurrentProgram(channelId);
                if (p == null) {
                    long now = System.currentTimeMillis();
                    mDvrManager.addSchedule(channel, now, now + TimeUnit.MINUTES.toMillis(1));
                } else {
                    mDvrManager.addSchedule(p, mDvrManager.getScheduledRecordingsThatConflict(p));
                }
                return true;
            }
        }
        case KeyEvent.KEYCODE_PROG_YELLOW:
        case KeyEvent.KEYCODE_BUTTON_Y:
        case KeyEvent.KEYCODE_Y: {
            if (CommonFeatures.DVR.isEnabled(this) && BuildCompat.isAtLeastN()) {
                // TODO(DVR) only get finished recordings.
                List<RecordedProgram> recordedPrograms = mDvrDataManager.getRecordedPrograms();
                Log.d(TAG, "Found " + recordedPrograms.size() + "  recordings");
                if (recordedPrograms.isEmpty()) {
                    Toast.makeText(this, "No finished recording to play", Toast.LENGTH_LONG).show();
                } else {
                    RecordedProgram r = recordedPrograms.get(0);
                    Intent intent = new Intent(this, DvrPlayActivity.class);
                    intent.putExtra(ScheduledRecording.RECORDING_ID_EXTRA, r.getId());
                    startActivity(intent);
                }
                return true;
            }
        }
        }
    }
    return super.onKeyUp(keyCode, event);
}

From source file:com.guardtrax.ui.screens.HomeScreen.java

private void displaytourInfo() {
    String message = "";
    int i = 0;//  w w w .  j  a  v  a2s .c  om
    int tagCount = 0;
    boolean singleDisplay = false; //indicates that only 1 item is to be displayed in the tour list
    List<Boolean> tourtagsIncluded = new ArrayList<Boolean>();
    List<Boolean> tourtagsScanned = new ArrayList<Boolean>();
    List<Integer> tourOrder = new ArrayList<Integer>();
    List<String> messageList = new ArrayList<String>();

    //check if this is a single display (second last character of tour name is a space)
    singleDisplay = isSingleRandomTour();
    tourDB.open();

    Cursor c = tourDB.getRecordByTour(GTConstants.tourName);

    if (c != null && c.moveToFirst()) {
        tourtagsScanned = refreshtourtagList(c.getCount(), false, true, false, false);
        tourtagsIncluded = refreshtourtagList(c.getCount(), false, false, true, false);
        tourOrder = gettourOrder(c.getCount());

        //initialize the message array which wil be used to display the messages in the random order
        while (messageList.size() < c.getCount())
            messageList.add("");

        for (i = 0; i < c.getCount(); i++) {
            if (tourtagsScanned.get(i) && tourtagsIncluded.get(i) && !singleDisplay)
                messageList.add(tourOrder.get(i),
                        "<br><font color='#00FF00'>" + c.getString(2) + "</font><br/>");
            else if (!tourtagsScanned.get(i) && !Utility.istourOntime(tourEnd)
                    && Utility.getcurrentState().equals(GTConstants.onShift) && tourtagsIncluded.get(i)
                    && !singleDisplay)
                messageList.add(tourOrder.get(i),
                        "<br><font color='#FF0000'>" + c.getString(2) + "</font><br/>");
            else if (!tourtagsScanned.get(i) && tourtagsIncluded.get(i) && !singleDisplay)
                messageList.add(tourOrder.get(i),
                        "<br><font color='#FFFFFF'>" + c.getString(2) + "</font><br/>");
            else if (singleDisplay && i == touritemNumber)
                messageList.add(tourOrder.get(i),
                        "<br><font color='#FFFFFF'>" + c.getString(2) + "</font><br/>");

            //get the number of tags included
            if (tourtagsIncluded.get(i))
                tagCount++;
            c.moveToNext();
        }
    }

    tourDB.close();

    //create the message string
    for (i = 0; i < messageList.size(); i++)
        if (messageList.get(i).length() > 1)
            message = message + messageList.get(i);

    LayoutInflater inflater = LayoutInflater.from(HomeScreen.this);
    View view = inflater.inflate(R.layout.scroll_dialog, null);

    TextView textview = (TextView) view.findViewById(R.id.dialogtext);
    textview.setText(Html.fromHtml(message));
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(HomeScreen.this);

    //create custom title
    TextView title = new TextView(HomeScreen.this);

    //if this is a single display tour then do not indicate how many tags are in the tour
    if (isSingleRandomTour()) //this is a single display tour
        title.setText(GTConstants.tourName + CRLF + tourTime + CRLF);
    else
        title.setText(GTConstants.tourName + CRLF + tourTime + CRLF + String.valueOf(tagCount) + " Tags");
    title.setPadding(10, 10, 10, 10);
    title.setGravity(Gravity.CENTER);
    title.setTextColor(Color.parseColor("#79ABFF"));
    title.setTextSize(20);
    alertDialog.setCustomTitle(title);

    //alertDialog.setTitle(tourName + CRLF + String.valueOf(i-1) + " Tags"); 
    alertDialog.setView(view);
    alertDialog.setPositiveButton("OK", null);
    AlertDialog alert = alertDialog.create();
    alert.show();
}

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()];
        }//from  w ww  .jav  a 2 s.c  o m

        @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();
    }
}