Example usage for android.widget GridView setAdapter

List of usage examples for android.widget GridView setAdapter

Introduction

In this page you can find the example usage for android.widget GridView setAdapter.

Prototype

@Override
public void setAdapter(ListAdapter adapter) 

Source Link

Document

Sets the data behind this GridView.

Usage

From source file:com.haomee.chat.activity.ChatActivity.java

public View init_grid_viewpager_data(List<String> images_path_list, List<String> iamges_name_list,
        final int current_page, final int type_size, final String package_id, final int type) {

    View view = LayoutInflater.from(this).inflate(R.layout.express_grid, null);
    GridView grid = (GridView) view.findViewById(R.id.gridView1);
    grid.setSelector(new ColorDrawable(Color.TRANSPARENT));
    final NewExpressAdapter2 grid_adapter = new NewExpressAdapter2(ChatActivity.this);
    grid.setAdapter(grid_adapter);
    final List<String> current_page_path;
    final List<String> current_page_name;
    int total_page = 0;
    if (type_size == 1) {// 
        total_page = (images_path_list.size() - 1) / 10 + 1;
        page_size = 10;// w w  w .j  av  a 2 s  .com
    } else if (type_size == 2) {// ?
        total_page = (images_path_list.size() - 1) / 20 + 1;
        page_size = 20;
    }
    if (current_page < total_page - 1) {
        current_page_path = images_path_list.subList(current_page * page_size, (current_page + 1) * page_size);
        current_page_name = iamges_name_list.subList(current_page * page_size, (current_page + 1) * page_size);
    } else {
        current_page_path = images_path_list.subList(current_page * page_size, images_path_list.size());
        current_page_name = iamges_name_list.subList(current_page * page_size, images_path_list.size());
    }
    grid_adapter.setData(current_page_path, current_page_name, type_size);
    grid.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            String[] path_list = current_page_path.get(position).split("/");
            String[] file_name = path_list[path_list.length - 1].split("#");
            String[] current_id = file_name[0].split("\\.");
            String temp_type = "";
            if (type == TYPE_GIF) {
                temp_type = ".gif";
            } else {
                temp_type = ".png";
            }
            sendTextByExpression(type, package_id, current_id[0], current_page_name.get(position),
                    PathConst.URL_EXPRESS_PREFIX + package_id + "/" + current_id[0] + temp_type, type_size);
        }
    });
    return view;
}

From source file:net.bluehack.ui.Components.EmojiView.java

public EmojiView(boolean needStickers, boolean needGif, final Context context) {
    super(context);

    showGifs = needGif;//from   w w w .  j  a  va2s  .  co  m

    dotDrawable = context.getResources().getDrawable(R.drawable.bluecircle);

    if (Build.VERSION.SDK_INT >= 21) {
        outlineProvider = new ViewOutlineProvider() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setRoundRect(view.getPaddingLeft(), view.getPaddingTop(),
                        view.getMeasuredWidth() - view.getPaddingRight(),
                        view.getMeasuredHeight() - view.getPaddingBottom(), AndroidUtilities.dp(6));
            }
        };
    }

    for (int i = 0; i < EmojiData.dataColored.length + 1; i++) {
        GridView gridView = new GridView(context);
        if (AndroidUtilities.isTablet()) {
            gridView.setColumnWidth(AndroidUtilities.dp(60));
        } else {
            gridView.setColumnWidth(AndroidUtilities.dp(45));
        }
        gridView.setNumColumns(-1);
        EmojiGridAdapter emojiGridAdapter = new EmojiGridAdapter(i - 1);
        AndroidUtilities.setListViewEdgeEffectColor(gridView, 0xfff5f6f7);
        gridView.setAdapter(emojiGridAdapter);
        adapters.add(emojiGridAdapter);
        emojiGrids.add(gridView);
        FrameLayout frameLayout = new FrameLayout(context);
        frameLayout.addView(gridView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 48, 0, 0));

        views.add(frameLayout);
    }

    if (needStickers) {
        stickersWrap = new FrameLayout(context);

        StickersQuery.checkStickers(StickersQuery.TYPE_IMAGE);
        StickersQuery.checkFeaturedStickers();
        stickersGridView = new RecyclerListView(context) {
            @Override
            public boolean onInterceptTouchEvent(MotionEvent event) {
                boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event,
                        stickersGridView, EmojiView.this.getMeasuredHeight());
                return super.onInterceptTouchEvent(event) || result;
            }

            @Override
            public void setVisibility(int visibility) {
                if (gifsGridView != null && gifsGridView.getVisibility() == VISIBLE
                        || trendingGridView != null && trendingGridView.getVisibility() == VISIBLE) {
                    super.setVisibility(GONE);
                    return;
                }
                super.setVisibility(visibility);
            }
        };

        stickersGridView.setLayoutManager(stickersLayoutManager = new GridLayoutManager(context, 5));
        stickersLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == stickersGridAdapter.totalItems) {
                    return stickersGridAdapter.stickersPerRow;
                }
                return 1;
            }
        });
        stickersGridView.setPadding(0, AndroidUtilities.dp(4 + 48), 0, 0);
        stickersGridView.setClipToPadding(false);
        views.add(stickersWrap);
        stickersGridView.setAdapter(stickersGridAdapter = new StickersGridAdapter(context));
        stickersGridView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return StickerPreviewViewer.getInstance().onTouch(event, stickersGridView,
                        EmojiView.this.getMeasuredHeight(), stickersOnItemClickListener);
            }
        });
        stickersOnItemClickListener = new RecyclerListView.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (!(view instanceof StickerEmojiCell)) {
                    return;
                }
                StickerPreviewViewer.getInstance().reset();
                StickerEmojiCell cell = (StickerEmojiCell) view;
                if (cell.isDisabled()) {
                    return;
                }
                cell.disable();
                listener.onStickerSelected(cell.getSticker());
            }
        };
        stickersGridView.setOnItemClickListener(stickersOnItemClickListener);
        stickersGridView.setGlowColor(0xfff5f6f7);
        stickersWrap.addView(stickersGridView);

        trendingGridView = new RecyclerListView(context);
        trendingGridView.setItemAnimator(null);
        trendingGridView.setLayoutAnimation(null);
        trendingGridView.setLayoutManager(trendingLayoutManager = new GridLayoutManager(context, 5) {
            @Override
            public boolean supportsPredictiveItemAnimations() {
                return false;
            }
        });
        trendingLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (trendingGridAdapter.cache.get(position) instanceof Integer
                        || position == trendingGridAdapter.totalItems) {
                    return trendingGridAdapter.stickersPerRow;
                }
                return 1;
            }
        });
        trendingGridView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                checkStickersTabY(recyclerView, dy);
            }
        });
        trendingGridView.setClipToPadding(false);
        trendingGridView.setPadding(0, AndroidUtilities.dp(48), 0, 0);
        trendingGridView.setAdapter(trendingGridAdapter = new TrendingGridAdapter(context));
        trendingGridView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                TLRPC.StickerSetCovered pack = trendingGridAdapter.positionsToSets.get(position);
                if (pack != null) {
                    listener.onShowStickerSet(pack);
                }
            }
        });
        trendingGridAdapter.notifyDataSetChanged();
        trendingGridView.setGlowColor(0xfff5f6f7);
        trendingGridView.setVisibility(GONE);
        stickersWrap.addView(trendingGridView);

        if (needGif) {
            gifsGridView = new RecyclerListView(context);
            gifsGridView.setClipToPadding(false);
            gifsGridView.setPadding(0, AndroidUtilities.dp(48), 0, 0);
            gifsGridView.setLayoutManager(flowLayoutManager = new ExtendedGridLayoutManager(context, 100) {

                private Size size = new Size();

                @Override
                protected Size getSizeForItem(int i) {
                    TLRPC.Document document = recentGifs.get(i);
                    size.width = document.thumb != null && document.thumb.w != 0 ? document.thumb.w : 100;
                    size.height = document.thumb != null && document.thumb.h != 0 ? document.thumb.h : 100;
                    for (int b = 0; b < document.attributes.size(); b++) {
                        TLRPC.DocumentAttribute attribute = document.attributes.get(b);
                        if (attribute instanceof TLRPC.TL_documentAttributeImageSize
                                || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                            size.width = attribute.w;
                            size.height = attribute.h;
                            break;
                        }
                    }
                    return size;
                }
            });
            flowLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return flowLayoutManager.getSpanSizeForItem(position);
                }
            });
            gifsGridView.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(android.graphics.Rect outRect, View view, RecyclerView parent,
                        RecyclerView.State state) {
                    outRect.left = 0;
                    outRect.top = 0;
                    outRect.bottom = 0;
                    int position = parent.getChildAdapterPosition(view);
                    if (!flowLayoutManager.isFirstRow(position)) {
                        outRect.top = AndroidUtilities.dp(2);
                    }
                    outRect.right = flowLayoutManager.isLastInRow(position) ? 0 : AndroidUtilities.dp(2);
                }
            });
            gifsGridView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
            gifsGridView.setAdapter(gifsAdapter = new GifsAdapter(context));
            gifsGridView.setOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    checkStickersTabY(recyclerView, dy);
                }
            });
            gifsGridView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (position < 0 || position >= recentGifs.size() || listener == null) {
                        return;
                    }
                    listener.onGifSelected(recentGifs.get(position));
                }
            });
            gifsGridView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
                @Override
                public boolean onItemClick(View view, int position) {
                    if (position < 0 || position >= recentGifs.size()) {
                        return false;
                    }
                    final TLRPC.Document searchImage = recentGifs.get(position);
                    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                    builder.setMessage(LocaleController.getString("DeleteGif", R.string.DeleteGif));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK).toUpperCase(),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    StickersQuery.removeRecentGif(searchImage);
                                    recentGifs = StickersQuery.getRecentGifs();
                                    if (gifsAdapter != null) {
                                        gifsAdapter.notifyDataSetChanged();
                                    }
                                    if (recentGifs.isEmpty()) {
                                        updateStickerTabs();
                                    }
                                }
                            });
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    builder.show().setCanceledOnTouchOutside(true);
                    return true;
                }
            });
            gifsGridView.setVisibility(GONE);
            stickersWrap.addView(gifsGridView);
        }

        stickersEmptyView = new TextView(context);
        stickersEmptyView.setText(LocaleController.getString("NoStickers", R.string.NoStickers));
        stickersEmptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
        stickersEmptyView.setTextColor(0xff888888);
        stickersWrap.addView(stickersEmptyView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
                LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 48, 0, 0));
        stickersGridView.setEmptyView(stickersEmptyView);

        stickersTab = new ScrollSlidingTabStrip(context) {

            boolean startedScroll;
            float lastX;
            float lastTranslateX;
            boolean first = true;

            @Override
            public boolean onInterceptTouchEvent(MotionEvent ev) {
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                return super.onInterceptTouchEvent(ev);
            }

            @Override
            public boolean onTouchEvent(MotionEvent ev) {
                if (first) {
                    first = false;
                    lastX = ev.getX();
                }
                float newTranslationX = stickersTab.getTranslationX();
                if (stickersTab.getScrollX() == 0 && newTranslationX == 0) {
                    if (!startedScroll && lastX - ev.getX() < 0) {
                        if (pager.beginFakeDrag()) {
                            startedScroll = true;
                            lastTranslateX = stickersTab.getTranslationX();
                        }
                    } else if (startedScroll && lastX - ev.getX() > 0) {
                        if (pager.isFakeDragging()) {
                            pager.endFakeDrag();
                            startedScroll = false;
                        }
                    }
                }
                if (startedScroll) {
                    int dx = (int) (ev.getX() - lastX + newTranslationX - lastTranslateX);
                    try {
                        pager.fakeDragBy(dx);
                        lastTranslateX = newTranslationX;
                    } catch (Exception e) {
                        try {
                            pager.endFakeDrag();
                        } catch (Exception e2) {
                            //don't promt
                        }
                        startedScroll = false;
                        FileLog.e("tmessages", e);
                    }
                }
                lastX = ev.getX();
                if (ev.getAction() == MotionEvent.ACTION_CANCEL || ev.getAction() == MotionEvent.ACTION_UP) {
                    first = true;
                    if (startedScroll) {
                        pager.endFakeDrag();
                        startedScroll = false;
                    }
                }
                return startedScroll || super.onTouchEvent(ev);
            }
        };
        stickersTab.setUnderlineHeight(AndroidUtilities.dp(1));
        stickersTab.setIndicatorColor(0xffe2e5e7);
        stickersTab.setUnderlineColor(0xffe2e5e7);
        stickersTab.setBackgroundColor(0xfff5f6f7);
        stickersTab.setVisibility(INVISIBLE);
        addView(stickersTab,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP));
        stickersTab.setTranslationX(AndroidUtilities.displaySize.x);
        updateStickerTabs();
        stickersTab.setDelegate(new ScrollSlidingTabStrip.ScrollSlidingTabStripDelegate() {
            @Override
            public void onPageSelected(int page) {
                if (gifsGridView != null) {
                    if (page == gifTabNum + 1) {
                        if (gifsGridView.getVisibility() != VISIBLE) {
                            listener.onGifTab(true);
                            showGifTab();
                        }
                    } else if (page == trendingTabNum + 1) {
                        if (trendingGridView.getVisibility() != VISIBLE) {
                            showTrendingTab();
                        }
                    } else {
                        if (gifsGridView.getVisibility() == VISIBLE) {
                            listener.onGifTab(false);
                            gifsGridView.setVisibility(GONE);
                            stickersGridView.setVisibility(VISIBLE);
                            stickersEmptyView
                                    .setVisibility(stickersGridAdapter.getItemCount() != 0 ? GONE : VISIBLE);
                            saveNewPage();
                        } else if (trendingGridView.getVisibility() == VISIBLE) {
                            trendingGridView.setVisibility(GONE);
                            stickersGridView.setVisibility(VISIBLE);
                            stickersEmptyView
                                    .setVisibility(stickersGridAdapter.getItemCount() != 0 ? GONE : VISIBLE);
                            saveNewPage();
                        }
                    }
                }
                if (page == 0) {
                    pager.setCurrentItem(0);
                    return;
                } else {
                    if (page == gifTabNum + 1 || page == trendingTabNum + 1) {
                        return;
                    } else if (page == recentTabBum + 1) {
                        stickersLayoutManager.scrollToPositionWithOffset(0, 0);
                        checkStickersTabY(null, 0);
                        stickersTab.onPageScrolled(recentTabBum + 1,
                                (recentTabBum > 0 ? recentTabBum : stickersTabOffset) + 1);
                        return;
                    }
                }
                int index = page - 1 - stickersTabOffset;
                if (index >= stickerSets.size()) {
                    if (listener != null) {
                        listener.onStickersSettingsClick();
                    }
                    return;
                }
                if (index >= stickerSets.size()) {
                    index = stickerSets.size() - 1;
                }
                stickersLayoutManager.scrollToPositionWithOffset(
                        stickersGridAdapter.getPositionForPack(stickerSets.get(index)), 0);
                checkStickersTabY(null, 0);
                checkScroll();
            }
        });

        stickersGridView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                checkScroll();
                checkStickersTabY(recyclerView, dy);
            }
        });
    }

    pager = new ViewPager(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pager.setAdapter(new EmojiPagesAdapter());

    emojiTab = new LinearLayout(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    emojiTab.setOrientation(LinearLayout.HORIZONTAL);
    addView(emojiTab, LayoutHelper.createFrame(LayoutParams.MATCH_PARENT, 48));

    pagerSlidingTabStrip = new PagerSlidingTabStrip(context);
    pagerSlidingTabStrip.setViewPager(pager);
    pagerSlidingTabStrip.setShouldExpand(true);
    pagerSlidingTabStrip.setIndicatorHeight(AndroidUtilities.dp(2));
    pagerSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
    pagerSlidingTabStrip.setIndicatorColor(0xff2b96e2);
    pagerSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
    emojiTab.addView(pagerSlidingTabStrip, LayoutHelper.createLinear(0, 48, 1.0f));
    pagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            EmojiView.this.onPageScrolled(position, getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
                    positionOffsetPixels);
        }

        @Override
        public void onPageSelected(int position) {
            saveNewPage();
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    FrameLayout frameLayout = new FrameLayout(context);
    emojiTab.addView(frameLayout, LayoutHelper.createLinear(52, 48));

    backspaceButton = new ImageView(context) {
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                backspacePressed = true;
                backspaceOnce = false;
                postBackspaceRunnable(350);
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL
                    || event.getAction() == MotionEvent.ACTION_UP) {
                backspacePressed = false;
                if (!backspaceOnce) {
                    if (listener != null && listener.onBackspace()) {
                        backspaceButton.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
                    }
                }
            }
            super.onTouchEvent(event);
            return true;
        }
    };
    backspaceButton.setImageResource(R.drawable.ic_smiles_backspace);
    backspaceButton.setBackgroundResource(R.drawable.ic_emoji_backspace);
    backspaceButton.setScaleType(ImageView.ScaleType.CENTER);
    frameLayout.addView(backspaceButton, LayoutHelper.createFrame(52, 48));

    View view = new View(context);
    view.setBackgroundColor(0xffe2e5e7);
    frameLayout.addView(view, LayoutHelper.createFrame(52, 1, Gravity.LEFT | Gravity.BOTTOM));

    TextView textView = new TextView(context);
    textView.setText(LocaleController.getString("NoRecent", R.string.NoRecent));
    textView.setTextSize(18);
    textView.setTextColor(0xff888888);
    textView.setGravity(Gravity.CENTER);
    textView.setClickable(false);
    textView.setFocusable(false);
    ((FrameLayout) views.get(0)).addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 48, 0, 0));
    emojiGrids.get(0).setEmptyView(textView);

    addView(pager, 0, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
            Gravity.LEFT | Gravity.TOP));

    emojiSize = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 40 : 32);
    pickerView = new EmojiColorPickerView(context);
    pickerViewPopup = new EmojiPopupWindow(pickerView,
            popupWidth = AndroidUtilities.dp((AndroidUtilities.isTablet() ? 40 : 32) * 6 + 10 + 4 * 5),
            popupHeight = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 64 : 56));
    pickerViewPopup.setOutsideTouchable(true);
    pickerViewPopup.setClippingEnabled(true);
    pickerViewPopup.setInputMethodMode(EmojiPopupWindow.INPUT_METHOD_NOT_NEEDED);
    pickerViewPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
    pickerViewPopup.getContentView().setFocusableInTouchMode(true);
    pickerViewPopup.getContentView().setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0
                    && event.getAction() == KeyEvent.ACTION_UP && pickerViewPopup != null
                    && pickerViewPopup.isShowing()) {
                pickerViewPopup.dismiss();
                return true;
            }
            return false;
        }
    });
    currentPage = getContext().getSharedPreferences("emoji", Activity.MODE_PRIVATE).getInt("selected_page", 0);
    loadRecents();
}

From source file:kr.wdream.ui.Components.EmojiView.java

public EmojiView(boolean needStickers, boolean needGif, final Context context) {
    super(context);

    showGifs = needGif;//from ww  w .jav a 2s.c o  m

    dotDrawable = context.getResources().getDrawable(kr.wdream.storyshop.R.drawable.bluecircle);

    if (Build.VERSION.SDK_INT >= 21) {
        outlineProvider = new ViewOutlineProvider() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setRoundRect(view.getPaddingLeft(), view.getPaddingTop(),
                        view.getMeasuredWidth() - view.getPaddingRight(),
                        view.getMeasuredHeight() - view.getPaddingBottom(), AndroidUtilities.dp(6));
            }
        };
    }

    for (int i = 0; i < EmojiData.dataColored.length + 1; i++) {
        GridView gridView = new GridView(context);
        if (AndroidUtilities.isTablet()) {
            gridView.setColumnWidth(AndroidUtilities.dp(60));
        } else {
            gridView.setColumnWidth(AndroidUtilities.dp(45));
        }
        gridView.setNumColumns(-1);
        EmojiGridAdapter emojiGridAdapter = new EmojiGridAdapter(i - 1);
        AndroidUtilities.setListViewEdgeEffectColor(gridView, 0xfff5f6f7);
        gridView.setAdapter(emojiGridAdapter);
        adapters.add(emojiGridAdapter);
        emojiGrids.add(gridView);
        FrameLayout frameLayout = new FrameLayout(context);
        frameLayout.addView(gridView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 48, 0, 0));

        views.add(frameLayout);
    }

    if (needStickers) {
        stickersWrap = new FrameLayout(context);

        StickersQuery.checkStickers(StickersQuery.TYPE_IMAGE);
        StickersQuery.checkFeaturedStickers();
        stickersGridView = new RecyclerListView(context) {
            @Override
            public boolean onInterceptTouchEvent(MotionEvent event) {
                boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event,
                        stickersGridView, EmojiView.this.getMeasuredHeight());
                return super.onInterceptTouchEvent(event) || result;
            }

            @Override
            public void setVisibility(int visibility) {
                if (gifsGridView != null && gifsGridView.getVisibility() == VISIBLE
                        || trendingGridView != null && trendingGridView.getVisibility() == VISIBLE) {
                    super.setVisibility(GONE);
                    return;
                }
                super.setVisibility(visibility);
            }
        };

        stickersGridView.setLayoutManager(stickersLayoutManager = new GridLayoutManager(context, 5));
        stickersLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == stickersGridAdapter.totalItems) {
                    return stickersGridAdapter.stickersPerRow;
                }
                return 1;
            }
        });
        stickersGridView.setPadding(0, AndroidUtilities.dp(4 + 48), 0, 0);
        stickersGridView.setClipToPadding(false);
        views.add(stickersWrap);
        stickersGridView.setAdapter(stickersGridAdapter = new StickersGridAdapter(context));
        stickersGridView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return StickerPreviewViewer.getInstance().onTouch(event, stickersGridView,
                        EmojiView.this.getMeasuredHeight(), stickersOnItemClickListener);
            }
        });
        stickersOnItemClickListener = new RecyclerListView.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (!(view instanceof StickerEmojiCell)) {
                    return;
                }
                StickerPreviewViewer.getInstance().reset();
                StickerEmojiCell cell = (StickerEmojiCell) view;
                if (cell.isDisabled()) {
                    return;
                }
                cell.disable();
                listener.onStickerSelected(cell.getSticker());
            }
        };
        stickersGridView.setOnItemClickListener(stickersOnItemClickListener);
        stickersGridView.setGlowColor(0xfff5f6f7);
        stickersWrap.addView(stickersGridView);

        trendingGridView = new RecyclerListView(context);
        trendingGridView.setItemAnimator(null);
        trendingGridView.setLayoutAnimation(null);
        trendingGridView.setLayoutManager(trendingLayoutManager = new GridLayoutManager(context, 5) {
            @Override
            public boolean supportsPredictiveItemAnimations() {
                return false;
            }
        });
        trendingLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (trendingGridAdapter.cache.get(position) instanceof Integer
                        || position == trendingGridAdapter.totalItems) {
                    return trendingGridAdapter.stickersPerRow;
                }
                return 1;
            }
        });
        trendingGridView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                checkStickersTabY(recyclerView, dy);
            }
        });
        trendingGridView.setClipToPadding(false);
        trendingGridView.setPadding(0, AndroidUtilities.dp(48), 0, 0);
        trendingGridView.setAdapter(trendingGridAdapter = new TrendingGridAdapter(context));
        trendingGridView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                TLRPC.StickerSetCovered pack = trendingGridAdapter.positionsToSets.get(position);
                if (pack != null) {
                    listener.onShowStickerSet(pack);
                }
            }
        });
        trendingGridAdapter.notifyDataSetChanged();
        trendingGridView.setGlowColor(0xfff5f6f7);
        trendingGridView.setVisibility(GONE);
        stickersWrap.addView(trendingGridView);

        if (needGif) {
            gifsGridView = new RecyclerListView(context);
            gifsGridView.setClipToPadding(false);
            gifsGridView.setPadding(0, AndroidUtilities.dp(48), 0, 0);
            gifsGridView.setLayoutManager(flowLayoutManager = new ExtendedGridLayoutManager(context, 100) {

                private Size size = new Size();

                @Override
                protected Size getSizeForItem(int i) {
                    TLRPC.Document document = recentGifs.get(i);
                    size.width = document.thumb != null && document.thumb.w != 0 ? document.thumb.w : 100;
                    size.height = document.thumb != null && document.thumb.h != 0 ? document.thumb.h : 100;
                    for (int b = 0; b < document.attributes.size(); b++) {
                        TLRPC.DocumentAttribute attribute = document.attributes.get(b);
                        if (attribute instanceof TLRPC.TL_documentAttributeImageSize
                                || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                            size.width = attribute.w;
                            size.height = attribute.h;
                            break;
                        }
                    }
                    return size;
                }
            });
            flowLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return flowLayoutManager.getSpanSizeForItem(position);
                }
            });
            gifsGridView.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(android.graphics.Rect outRect, View view, RecyclerView parent,
                        RecyclerView.State state) {
                    outRect.left = 0;
                    outRect.top = 0;
                    outRect.bottom = 0;
                    int position = parent.getChildAdapterPosition(view);
                    if (!flowLayoutManager.isFirstRow(position)) {
                        outRect.top = AndroidUtilities.dp(2);
                    }
                    outRect.right = flowLayoutManager.isLastInRow(position) ? 0 : AndroidUtilities.dp(2);
                }
            });
            gifsGridView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
            gifsGridView.setAdapter(gifsAdapter = new GifsAdapter(context));
            gifsGridView.setOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    checkStickersTabY(recyclerView, dy);
                }
            });
            gifsGridView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (position < 0 || position >= recentGifs.size() || listener == null) {
                        return;
                    }
                    listener.onGifSelected(recentGifs.get(position));
                }
            });
            gifsGridView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
                @Override
                public boolean onItemClick(View view, int position) {
                    if (position < 0 || position >= recentGifs.size()) {
                        return false;
                    }
                    final TLRPC.Document searchImage = recentGifs.get(position);
                    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                    builder.setTitle(
                            LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                    builder.setMessage(
                            LocaleController.getString("DeleteGif", kr.wdream.storyshop.R.string.DeleteGif));
                    builder.setPositiveButton(
                            LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK).toUpperCase(),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    StickersQuery.removeRecentGif(searchImage);
                                    recentGifs = StickersQuery.getRecentGifs();
                                    if (gifsAdapter != null) {
                                        gifsAdapter.notifyDataSetChanged();
                                    }
                                    if (recentGifs.isEmpty()) {
                                        updateStickerTabs();
                                    }
                                }
                            });
                    builder.setNegativeButton(
                            LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel), null);
                    builder.show().setCanceledOnTouchOutside(true);
                    return true;
                }
            });
            gifsGridView.setVisibility(GONE);
            stickersWrap.addView(gifsGridView);
        }

        stickersEmptyView = new TextView(context);
        stickersEmptyView
                .setText(LocaleController.getString("NoStickers", kr.wdream.storyshop.R.string.NoStickers));
        stickersEmptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
        stickersEmptyView.setTextColor(0xff888888);
        stickersWrap.addView(stickersEmptyView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
                LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 48, 0, 0));
        stickersGridView.setEmptyView(stickersEmptyView);

        stickersTab = new ScrollSlidingTabStrip(context) {

            boolean startedScroll;
            float lastX;
            float lastTranslateX;
            boolean first = true;

            @Override
            public boolean onInterceptTouchEvent(MotionEvent ev) {
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                return super.onInterceptTouchEvent(ev);
            }

            @Override
            public boolean onTouchEvent(MotionEvent ev) {
                if (first) {
                    first = false;
                    lastX = ev.getX();
                }
                float newTranslationX = stickersTab.getTranslationX();
                if (stickersTab.getScrollX() == 0 && newTranslationX == 0) {
                    if (!startedScroll && lastX - ev.getX() < 0) {
                        if (pager.beginFakeDrag()) {
                            startedScroll = true;
                            lastTranslateX = stickersTab.getTranslationX();
                        }
                    } else if (startedScroll && lastX - ev.getX() > 0) {
                        if (pager.isFakeDragging()) {
                            pager.endFakeDrag();
                            startedScroll = false;
                        }
                    }
                }
                if (startedScroll) {
                    int dx = (int) (ev.getX() - lastX + newTranslationX - lastTranslateX);
                    try {
                        pager.fakeDragBy(dx);
                        lastTranslateX = newTranslationX;
                    } catch (Exception e) {
                        try {
                            pager.endFakeDrag();
                        } catch (Exception e2) {
                            //don't promt
                        }
                        startedScroll = false;
                        FileLog.e("tmessages", e);
                    }
                }
                lastX = ev.getX();
                if (ev.getAction() == MotionEvent.ACTION_CANCEL || ev.getAction() == MotionEvent.ACTION_UP) {
                    first = true;
                    if (startedScroll) {
                        pager.endFakeDrag();
                        startedScroll = false;
                    }
                }
                return startedScroll || super.onTouchEvent(ev);
            }
        };
        stickersTab.setUnderlineHeight(AndroidUtilities.dp(1));
        stickersTab.setIndicatorColor(0xffe2e5e7);
        stickersTab.setUnderlineColor(0xffe2e5e7);
        stickersTab.setBackgroundColor(0xfff5f6f7);
        stickersTab.setVisibility(INVISIBLE);
        addView(stickersTab,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP));
        stickersTab.setTranslationX(AndroidUtilities.displaySize.x);
        updateStickerTabs();
        stickersTab.setDelegate(new ScrollSlidingTabStrip.ScrollSlidingTabStripDelegate() {
            @Override
            public void onPageSelected(int page) {
                if (gifsGridView != null) {
                    if (page == gifTabNum + 1) {
                        if (gifsGridView.getVisibility() != VISIBLE) {
                            listener.onGifTab(true);
                            showGifTab();
                        }
                    } else if (page == trendingTabNum + 1) {
                        if (trendingGridView.getVisibility() != VISIBLE) {
                            showTrendingTab();
                        }
                    } else {
                        if (gifsGridView.getVisibility() == VISIBLE) {
                            listener.onGifTab(false);
                            gifsGridView.setVisibility(GONE);
                            stickersGridView.setVisibility(VISIBLE);
                            stickersEmptyView
                                    .setVisibility(stickersGridAdapter.getItemCount() != 0 ? GONE : VISIBLE);
                            saveNewPage();
                        } else if (trendingGridView.getVisibility() == VISIBLE) {
                            trendingGridView.setVisibility(GONE);
                            stickersGridView.setVisibility(VISIBLE);
                            stickersEmptyView
                                    .setVisibility(stickersGridAdapter.getItemCount() != 0 ? GONE : VISIBLE);
                            saveNewPage();
                        }
                    }
                }
                if (page == 0) {
                    pager.setCurrentItem(0);
                    return;
                } else {
                    if (page == gifTabNum + 1 || page == trendingTabNum + 1) {
                        return;
                    } else if (page == recentTabBum + 1) {
                        stickersLayoutManager.scrollToPositionWithOffset(0, 0);
                        checkStickersTabY(null, 0);
                        stickersTab.onPageScrolled(recentTabBum + 1,
                                (recentTabBum > 0 ? recentTabBum : stickersTabOffset) + 1);
                        return;
                    }
                }
                int index = page - 1 - stickersTabOffset;
                if (index >= stickerSets.size()) {
                    if (listener != null) {
                        listener.onStickersSettingsClick();
                    }
                    return;
                }
                if (index >= stickerSets.size()) {
                    index = stickerSets.size() - 1;
                }
                stickersLayoutManager.scrollToPositionWithOffset(
                        stickersGridAdapter.getPositionForPack(stickerSets.get(index)), 0);
                checkStickersTabY(null, 0);
                checkScroll();
            }
        });

        stickersGridView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                checkScroll();
                checkStickersTabY(recyclerView, dy);
            }
        });
    }

    pager = new ViewPager(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pager.setAdapter(new EmojiPagesAdapter());

    emojiTab = new LinearLayout(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    emojiTab.setOrientation(LinearLayout.HORIZONTAL);
    addView(emojiTab, LayoutHelper.createFrame(LayoutParams.MATCH_PARENT, 48));

    pagerSlidingTabStrip = new PagerSlidingTabStrip(context);
    pagerSlidingTabStrip.setViewPager(pager);
    pagerSlidingTabStrip.setShouldExpand(true);
    pagerSlidingTabStrip.setIndicatorHeight(AndroidUtilities.dp(0));
    pagerSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
    //?   ?
    pagerSlidingTabStrip.setIndicatorColor(0xff2b96e2);
    pagerSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
    emojiTab.addView(pagerSlidingTabStrip, LayoutHelper.createLinear(0, 48, 1.0f));
    pagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            EmojiView.this.onPageScrolled(position, getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
                    positionOffsetPixels);
        }

        @Override
        public void onPageSelected(int position) {
            saveNewPage();
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    FrameLayout frameLayout = new FrameLayout(context);
    emojiTab.addView(frameLayout, LayoutHelper.createLinear(52, 48));

    backspaceButton = new ImageView(context) {
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                backspacePressed = true;
                backspaceOnce = false;
                postBackspaceRunnable(350);
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL
                    || event.getAction() == MotionEvent.ACTION_UP) {
                backspacePressed = false;
                if (!backspaceOnce) {
                    if (listener != null && listener.onBackspace()) {
                        backspaceButton.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
                    }
                }
            }
            super.onTouchEvent(event);
            return true;
        }
    };
    backspaceButton.setImageResource(kr.wdream.storyshop.R.drawable.ic_smiles_backspace);
    backspaceButton.setBackgroundResource(kr.wdream.storyshop.R.drawable.ic_emoji_backspace);
    backspaceButton.setScaleType(ImageView.ScaleType.CENTER);
    frameLayout.addView(backspaceButton, LayoutHelper.createFrame(52, 48));

    View view = new View(context);
    view.setBackgroundColor(0xffe2e5e7);
    frameLayout.addView(view, LayoutHelper.createFrame(52, 1, Gravity.LEFT | Gravity.BOTTOM));

    TextView textView = new TextView(context);
    textView.setText(LocaleController.getString("NoRecent", kr.wdream.storyshop.R.string.NoRecent));
    textView.setTextSize(18);
    textView.setTextColor(0xff888888);
    textView.setGravity(Gravity.CENTER);
    textView.setClickable(false);
    textView.setFocusable(false);
    ((FrameLayout) views.get(0)).addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 48, 0, 0));
    emojiGrids.get(0).setEmptyView(textView);

    addView(pager, 0, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
            Gravity.LEFT | Gravity.TOP));

    emojiSize = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 40 : 32);
    pickerView = new EmojiColorPickerView(context);
    pickerViewPopup = new EmojiPopupWindow(pickerView,
            popupWidth = AndroidUtilities.dp((AndroidUtilities.isTablet() ? 40 : 32) * 6 + 10 + 4 * 5),
            popupHeight = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 64 : 56));
    pickerViewPopup.setOutsideTouchable(true);
    pickerViewPopup.setClippingEnabled(true);
    pickerViewPopup.setInputMethodMode(EmojiPopupWindow.INPUT_METHOD_NOT_NEEDED);
    pickerViewPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
    pickerViewPopup.getContentView().setFocusableInTouchMode(true);
    pickerViewPopup.getContentView().setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0
                    && event.getAction() == KeyEvent.ACTION_UP && pickerViewPopup != null
                    && pickerViewPopup.isShowing()) {
                pickerViewPopup.dismiss();
                return true;
            }
            return false;
        }
    });
    currentPage = getContext().getSharedPreferences("emoji", Activity.MODE_PRIVATE).getInt("selected_page", 0);
    loadRecents();
}

From source file:com.fbbackup.TagMeImageGridFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View v = inflater.inflate(R.layout.album_photo_grid, container, false);
    final GridView mGridView = (GridView) v.findViewById(R.id.gridView);

    TextView tx_user_name = (TextView) v.findViewById(R.id.tx_album_name);

    tx_user_name.setText(albumName);//from  w w w.j a  v  a  2 s.c  om

    btn_tag_me = (ImageButton) v.findViewById(R.id.btn_tag_me);
    btn_photo = (ImageButton) v.findViewById(R.id.btn_photo);

    btn_tag_me.setVisibility(View.VISIBLE);
    btn_photo.setVisibility(View.VISIBLE);
    tx_user_name.setVisibility(View.GONE);

    btn_tag_me.setBackgroundResource(R.drawable.tagme);

    btn_photo.setOnClickListener(new ImageButton.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            getFragmentManager().popBackStack();

            MyFriendFragmentActivity.controlPanelHandler
                    .sendEmptyMessage(MyFriendFragmentActivity.SHOW_CONTROL_PANEL);
        }

    });

    cb_all = (CheckBox) v.findViewById(R.id.cb_all_photo);

    cb_all.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton v, boolean choose) {
            // TODO Auto-generated method stub

            if (choose) {

                // Toast.makeText(getActivity(), "choose:" + choose,
                // Toast.LENGTH_SHORT).show();

            } else {
                // Toast.makeText(getActivity(), "choose:" + choose,
                // Toast.LENGTH_SHORT).show();
            }
            setSelectedData(choose);

            mAdapter.notifyDataSetChanged();

        }

    });

    btn_download_photo = (ImageButton) v.findViewById(R.id.btn_download_photo);

    btn_download_photo.setOnClickListener(new ImageButton.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            String dir = Utils.getDirName(albumName);
            int select = 0;

            // QarrayU
            for (int i = 0; i < isSelected.size(); i++) {

                if (isSelected.get(i)) {
                    DownloadList.downloadPhotoAlbumQueue.add(dir);
                    DownloadList.downloadPhotoQueue.add(tagMePicture[i]);
                    DownloadList.downloadUserNameQueue.add(name);
                    select++;
                }

            }

            DownloadList.setAddNumber(select);

            DownloadList.setUserName(name);

            MyFriendFragmentActivity.downloadHandler.sendMessage(MyFriendFragmentActivity.downloadHandler
                    .obtainMessage(MyFriendFragmentActivity.DOWNLOAD_PRB, 0, 0));
        }

    });
    isSelected = new HashMap<Integer, Boolean>();

    initSelectedData();

    mGridView.setAdapter(mAdapter);
    mGridView.setOnItemClickListener(this);
    mGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView absListView, int scrollState) {
            // Pause fetcher to ensure smoother scrolling when flinging
            if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
                mImageFetcher.setPauseWork(true);
            } else {
                mImageFetcher.setPauseWork(false);
            }
        }

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

    // This listener is used to get the final width of the GridView and then
    // calculate the
    // number of columns and the width of each column. The width of each
    // column is variable
    // as the GridView has stretchMode=columnWidth. The column width is used
    // to set the height
    // of each view so we get nice square thumbnails.
    mGridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (mAdapter.getNumColumns() == 0) {
                final int numColumns = (int) Math
                        .floor(mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing));
                if (numColumns > 0) {
                    final int columnWidth = (mGridView.getWidth() / numColumns) - mImageThumbSpacing;
                    mAdapter.setNumColumns(numColumns);
                    mAdapter.setItemHeight(columnWidth);
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "onCreateView - numColumns set to " + numColumns);
                    }
                }
            }
        }
    });

    return v;
}

From source file:com.ramsofttech.adpushlibrary.fragment.GridFragment.java

/**
 * onActivityCreated/* w  w w.j av  a  2s  . c  o  m*/
 * When the activity is created, divide the usable space into columns
 * and put a grid of images in that area.
 */

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Activity a = getActivity();
    Resources res = a.getResources();

    View rootView = getView();
    GridView gridview = (GridView) rootView.findViewById(R.id.grid);

    DisplayMetrics metrics = new DisplayMetrics();
    a.getWindowManager().getDefaultDisplay().getMetrics(metrics);

    // From the resource files, determine how many rows and columns are to be displayed.
    int numRows = res.getInteger(R.integer.grid_num_rows);
    int numCols = res.getInteger(R.integer.grid_num_cols);
    AppDataHolder dataHolder = ((AppDataHolder) getActivity().getApplicationContext());
    if (dataHolder.getNumCols() != 0)
        numCols = dataHolder.getNumCols();
    if (dataHolder.getNumRows() != 0)
        numRows = dataHolder.getNumRows();
    // Figure out how much space is available for the N rows and M columns to be displayed.
    // We start with the root view for the fragment and adjust for the title, padding, etc.
    int titleHeight = res.getDimensionPixelSize(R.dimen.topic_title_height);
    int titlePadding = res.getDimensionPixelSize(R.dimen.topic_title_padding);
    int buttonAreaHeight = res.getDimensionPixelSize(R.dimen.button_area_height);
    int titleBarHeight = res.getDimensionPixelSize(R.dimen.title_bar_height);
    int gridHspacing = res.getDimensionPixelSize(R.dimen.image_grid_hspacing);
    int gridVSpacing = res.getDimensionPixelSize(R.dimen.image_grid_vspacing);
    int otherGridH = res.getDimensionPixelSize(R.dimen.other_grid_h);
    int otherGridW = res.getDimensionPixelSize(R.dimen.other_grid_w);
    int heightUsed = 2 * titleBarHeight + (numRows + 2) * gridVSpacing + (titleHeight + 2 * titlePadding)
            + otherGridH + buttonAreaHeight;

    int widthUsed = 40; // just a guess for now.
    int availableHeight = metrics.heightPixels - heightUsed;
    int availableWidth = metrics.widthPixels - widthUsed;
    int cellWidth = availableWidth / numCols;
    if (availableWidth > 1000) {
        cellWidth -= 20;
    }

    float cellHeight = numRows * (availableHeight / numRows) / 6;
    if (dataHolder.getCellHeight() != 0) {
        cellHeight = numRows * (availableHeight / numRows) / dataHolder.getCellHeight();
    }

    // Put this back in to check the calculations for cell height and width.
    Log.d("Debug", "--- metrics h: " + metrics.heightPixels + "  w: " + metrics.widthPixels);
    Log.d("Debug", "    available h: " + availableHeight + "  w: " + availableWidth);
    Log.d("Debug", "    already used h: " + heightUsed + "  w: " + widthUsed);
    Log.d("Debug", "    cell h: " + cellHeight + "  w: " + cellWidth);
    Log.d("Debug", "--- num rows: " + numRows + "  cols: " + numCols);
    Log.d("Debug", "--- firstImage: " + mFirstImage + " image count: " + mImageCount);

    if (gridview == null)
        Log.d("DEBUG", "Unable to locate the gridview.");
    else {
        Log.i("Adapter", "--inside call appadapter");
        //  AppDataHolder dataHolder = ((AppDataHolder) getActivity().getApplication());
        gridview.setNumColumns(numCols);
        // Connect the gridview with an adapter that fills up the space.
        //     gridview.setAdapter (new GridImageAdapter (a, mTopicList, mFirstImage, mImageCount, cellWidth, cellHeight));
        gridview.setAdapter(new AppAdapter(a, dataHolder.getApplicationList(), mFirstImage, mImageCount,
                cellWidth, cellHeight));

        // Arrange it so a long click on an item in the grid shows the topic associated with the image.
        gridview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                // TODO Auto-generated method stub
                //showTopic(mFirstImage + position);
                Toast.makeText(getActivity(), "" + (mFirstImage + position), Toast.LENGTH_LONG).show();

                clickAsyncTask clickAsynctask = new clickAsyncTask(getActivity());
                clickAsynctask.execute("" + (mFirstImage + position));

                AppDataHolder dataHolder = ((AppDataHolder) getActivity().getApplication());
                List<ApplicationData> applicationList = dataHolder.getApplicationList();
                ApplicationData application = applicationList.get(mFirstImage + position);
                startActivity(new Intent(Intent.ACTION_VIEW,
                        Uri.parse("market://details?id=" + application.getPackageName())));
            }
        });

    }
}

From source file:eu.geopaparazzi.library.core.dialogs.ColorStrokeDialogFragment.java

@Override
public Dialog onCreateDialog(Bundle bundle) {

    // create the dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    View colorStrokeDialogView = getActivity().getLayoutInflater()
            .inflate(R.layout.fragment_dialog_color_stroke, null);
    builder.setView(colorStrokeDialogView); // add GUI to dialog

    /*//from  w  w w. j  a  v a  2 s  . c o  m
     * the shape size image
     */
    if (!mCurrentColorStrokeObject.hasShape) {
        View shapeSizeView = colorStrokeDialogView.findViewById(R.id.shapeSizeDialogGridLayout);
        shapeSizeView.setVisibility(View.GONE);
    } else {
        //            mShapeSizeImageView = (ImageView) colorStrokeDialogView.findViewById(R.id.shapeSizeImageView);
        mShapeSizeTextView = (TextView) colorStrokeDialogView.findViewById(R.id.shapeSizeTextView);
        mShapeSizeSeekBar = (SeekBar) colorStrokeDialogView.findViewById(R.id.shapeSizeSeekBar);

        mShapeSizeSeekBar.setOnSeekBarChangeListener(shapeSizeChanged);
        mShapeSizeSeekBar.setProgress(mCurrentColorStrokeObject.shapeSize);
        mShapeSizeTextView.setText(String.valueOf(mCurrentColorStrokeObject.shapeSize));

        mShapeSpinner = (Spinner) colorStrokeDialogView.findViewById(R.id.shape_spinner);
        int count = mShapeSpinner.getCount();
        for (int i = 0; i < count; i++) {
            if (mShapeSpinner.getItemAtPosition(i).equals(mCurrentColorStrokeObject.shapeWKT)) {
                mShapeSpinner.setSelection(i);
                break;
            }
        }
        mShapeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Object selectedItem = mShapeSpinner.getSelectedItem();
                String shapeStr = selectedItem.toString();
                mCurrentColorStrokeObject.shapeWKT = shapeStr;
            }

            public void onNothingSelected(AdapterView<?> arg0) {
                // ignore
            }
        });

    }

    /*
     * the stroke width image
     */
    if (!mCurrentColorStrokeObject.hasStrokeWidth) {
        View lineWidthView = colorStrokeDialogView.findViewById(R.id.lineWidthDialogGridLayout);
        lineWidthView.setVisibility(View.GONE);
    } else {
        mWidthImageView = (ImageView) colorStrokeDialogView.findViewById(R.id.widthImageView);
        mWidthTextView = (TextView) colorStrokeDialogView.findViewById(R.id.widthTextView);
        mWidthSeekBar = (SeekBar) colorStrokeDialogView.findViewById(R.id.widthSeekBar);

        mWidthSeekBar.setOnSeekBarChangeListener(lineWidthChanged);
        mWidthSeekBar.setProgress(mCurrentColorStrokeObject.strokeWidth);
        mWidthTextView.setText(String.valueOf(mCurrentColorStrokeObject.strokeWidth));
    }

    RadioButton fillRadioButton = (RadioButton) colorStrokeDialogView.findViewById(R.id.doFillRadioButton);
    fillRadioButton.setChecked(true);
    RadioGroup radioGroup = (RadioGroup) colorStrokeDialogView.findViewById(R.id.radioDo);
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            onRadioButtonClicked(checkedId);
        }
    });

    /*
     * The fill/stroke color picker part
     */
    TextView title2 = (TextView) colorStrokeDialogView.findViewById(R.id.title2);
    if (!mCurrentColorStrokeObject.hasFill && !mCurrentColorStrokeObject.hasStroke) {
        View colorView = colorStrokeDialogView.findViewById(R.id.colorDialogGridLayout);
        colorView.setVisibility(View.GONE);
    } else {
        if (!mCurrentColorStrokeObject.hasFill || !mCurrentColorStrokeObject.hasStroke) {
            View radioView = colorStrokeDialogView.findViewById(R.id.radioDoLayout);
            radioView.setVisibility(View.GONE);
        }
        handlingFillColor = mCurrentColorStrokeObject.hasFill;
        String title = "";
        if (mCurrentColorStrokeObject.hasFill && mCurrentColorStrokeObject.hasStroke) {
            title = getActivity().getString(R.string.fill_and_stroke_color_title);
        } else if (mCurrentColorStrokeObject.hasFill) {
            title = getActivity().getString(R.string.fill_color_title);
        } else {
            title = getActivity().getString(R.string.stroke_color_title);
        }
        title2.setText(title);

        // get the color SeekBars and set their onChange listeners
        mAlphaSeekBar = (SeekBar) colorStrokeDialogView.findViewById(R.id.alphaSeekBar);
        mRedSeekBar = (SeekBar) colorStrokeDialogView.findViewById(R.id.redSeekBar);
        mGreenSeekBar = (SeekBar) colorStrokeDialogView.findViewById(R.id.greenSeekBar);
        mBlueSeekBar = (SeekBar) colorStrokeDialogView.findViewById(R.id.blueSeekBar);
        mColorView = colorStrokeDialogView.findViewById(R.id.colorView);

        // register SeekBar event listeners
        mAlphaSeekBar.setOnSeekBarChangeListener(colorChangedListener);
        mRedSeekBar.setOnSeekBarChangeListener(colorChangedListener);
        mGreenSeekBar.setOnSeekBarChangeListener(colorChangedListener);
        mBlueSeekBar.setOnSeekBarChangeListener(colorChangedListener);

        int color = 0;
        int alpha = 0;
        if (handlingFillColor) {
            color = mCurrentColorStrokeObject.fillColor;
            alpha = mCurrentColorStrokeObject.fillAlpha;
        } else {
            color = mCurrentColorStrokeObject.strokeColor;
            alpha = mCurrentColorStrokeObject.strokeAlpha;
        }
        // use current drawing color to set SeekBar values
        mAlphaSeekBar.setProgress(alpha);
        mRedSeekBar.setProgress(Color.red(color));
        mGreenSeekBar.setProgress(Color.green(color));
        mBlueSeekBar.setProgress(Color.blue(color));

        final ColorUtilities[] availableColors = ColorUtilities.values();

        GridView gridview = (GridView) colorStrokeDialogView.findViewById(R.id.availableColors);
        ArrayAdapter<ColorUtilities> colorsAdapter = new ArrayAdapter<ColorUtilities>(getActivity(),
                android.R.layout.simple_list_item_1, availableColors) {
            class ViewHolder {
                Button button;
            }

            @Override
            public View getView(final int position, View cView, ViewGroup parent) {
                ViewHolder holder;
                View rowView = cView;
                if (rowView == null) {
                    LayoutInflater inflater = getActivity().getLayoutInflater();
                    rowView = inflater.inflate(R.layout.fragment_dialog_color_stroke_row, parent, false);
                    holder = new ViewHolder();
                    holder.button = (Button) rowView.findViewById(R.id.button);
                    rowView.setTag(holder);
                } else {
                    holder = (ViewHolder) rowView.getTag();
                }
                String hex = availableColors[position].getHex();
                int color = ColorUtilities.toColor(hex);
                holder.button.setBackgroundColor(color);
                final Button b = holder.button;
                holder.button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int color = Color.TRANSPARENT;
                        Drawable background = b.getBackground();
                        if (background instanceof ColorDrawable)
                            color = ((ColorDrawable) background).getColor();

                        int red = Color.red(color);
                        int green = Color.green(color);
                        int blue = Color.blue(color);
                        int argb = Color.argb(red, green, blue, mAlphaSeekBar.getProgress());
                        mColorView.setBackgroundColor(argb);
                        mRedSeekBar.setProgress(red);
                        mGreenSeekBar.setProgress(green);
                        mBlueSeekBar.setProgress(blue);
                        if (handlingFillColor) {
                            mCurrentColorStrokeObject.fillColor = Color.rgb(mRedSeekBar.getProgress(),
                                    mGreenSeekBar.getProgress(), mBlueSeekBar.getProgress());
                            mCurrentColorStrokeObject.fillAlpha = mAlphaSeekBar.getProgress();
                        } else {
                            mCurrentColorStrokeObject.strokeColor = Color.rgb(mRedSeekBar.getProgress(),
                                    mGreenSeekBar.getProgress(), mBlueSeekBar.getProgress());
                            mCurrentColorStrokeObject.strokeAlpha = mAlphaSeekBar.getProgress();
                        }
                    }
                });

                return rowView;
            }

        };
        gridview.setAdapter(colorsAdapter);

    }

    // add Set Line Width Button
    builder.setPositiveButton(R.string.set_properties, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            if (colorStrokePropertiesChangeListener != null) {
                colorStrokePropertiesChangeListener.onPropertiesChanged(mCurrentColorStrokeObject);
            }
        }
    });
    builder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
        }
    });

    return builder.create(); // return dialog
}

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  w  w.ja v  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();
    }
}

From source file:org.brandroid.openmanager.activities.OpenExplorer.java

private void onClipboardDropdown(View anchor) {
    ViewUtils.setViewsVisible(mStaticButtons, true, R.id.title_paste);
    if (anchor == null)
        anchor = ViewUtils.getFirstView(this, R.id.title_paste, R.id.title_icon, R.id.frag_holder);

    final BetterPopupWindow clipdrop = new BetterPopupWindow(this, anchor);
    View root = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE))
            .inflate(R.layout.multiselect, null);
    GridView mGridCommands = (GridView) root.findViewById(R.id.multiselect_command_grid);
    final ListView mListClipboard = (ListView) root.findViewById(R.id.multiselect_item_list);
    mListClipboard.setAdapter(getClipboard());
    mListClipboard.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> list, View view, final int pos, long id) {
            //OpenPath file = mClipboard.get(pos);
            //if(file.getParent().equals(mLastPath))
            Animation anim = AnimationUtils.loadAnimation(OpenExplorer.this, R.anim.slide_out_left);
            //anim.setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));
            list.getChildAt(pos).startAnimation(anim);
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    getClipboard().remove(pos);
                    mListClipboard.invalidate();
                    if (getClipboard().getCount() == 0)
                        clipdrop.dismiss();
                }//from   w w w . j  a  va  2 s .co  m
            }, anim.getDuration());
            //else
            //getEventHandler().copyFile(file, mLastPath, OpenExplorer.this);
        }
    });
    final Menu menu = IconContextMenu.newMenu(this, R.menu.multiselect);
    MenuUtils.setMenuChecked(menu, getClipboard().isMultiselect(), R.id.menu_multi);
    MenuUtils.setMenuEnabled(menu, getClipboard().hasPastable(), R.id.menu_multi_all_copy,
            R.id.menu_multi_all_copy, R.id.menu_multi_all_move);
    final IconContextMenuAdapter cmdAdapter = new IconContextMenuAdapter(this, menu);
    cmdAdapter.setTextLayout(R.layout.context_item);
    mGridCommands.setAdapter(cmdAdapter);
    mGridCommands.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> list, View view, int pos, long id) {
            MenuItem item = menu.getItem(pos);
            onClick(item.getItemId(), item, view);
            clipdrop.dismiss();
        }
    });

    float w = getResources().getDimension(R.dimen.popup_width) * (3 / 2);
    if (w > getWindowWidth())
        w = getWindowWidth() - 20;
    clipdrop.setPopupWidth((int) w);
    clipdrop.setContentView(root);

    clipdrop.showLikePopDownMenu();
    //dropdown.setAdapter(this, new IconContextMenuAdapter(context, menu))
    //BetterPopupWindow win = new BetterPopupWindow(this, anchor);
    //ListView list = ((LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.multiselect, null);
    //win.setContentView(root)
}