Search in sources :

Example 1 with StoryPagerFragment

use of net.iGap.story.StoryPagerFragment in project iGap-Android by KianIranian-STDG.

the class MyStatusStoryListFragment method onViewCreated.

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getEventManager().addObserver(EventManager.STORY_LIST_FETCHED, this);
    getEventManager().addObserver(EventManager.STORY_USER_ADD_NEW, this);
    getEventManager().addObserver(EventManager.STORY_USER_ADD_VIEW, this);
    getEventManager().addObserver(EventManager.STORY_DELETED, this);
    getEventManager().addObserver(EventManager.STORY_UPLOADED_FAILED, this);
    getEventManager().addObserver(EventManager.STORY_UPLOAD, this);
    getEventManager().addObserver(EventManager.STORY_SENDING, this);
    getEventManager().addObserver(EventManager.STORY_USER_INFO, this);
    getEventManager().addObserver(EventManager.STORY_STATUS_UPLOAD, this);
    getEventManager().addObserver(EventManager.STORY_ROOM_IMAGE_UPLOAD, this);
    getEventManager().addObserver(EventManager.STORY_ROOM_UPLOAD, this);
    progressBar.setVisibility(View.VISIBLE);
    sendRoomStory();
    loadStories();
    AbstractObject req = null;
    IG_RPC.Story_Get_Own_Story_Views story_get_own_story_views = new IG_RPC.Story_Get_Own_Story_Views();
    story_get_own_story_views.offset = 0;
    story_get_own_story_views.limit = 50;
    req = story_get_own_story_views;
    getRequestManager().sendRequest(req, (response, error) -> {
        if (error == null) {
            IG_RPC.Res_Story_Get_Own_Story_Views res = (IG_RPC.Res_Story_Get_Own_Story_Views) response;
            getMessageDataStorage().updateOwnViews(res.groupedViews);
        // G.runOnUiThread(() -> loadStories());
        } else {
            progressBar.setVisibility(View.GONE);
        }
    });
    floatActionLayout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            if (listMode == 1) {
                new HelperFragment(getActivity().getSupportFragmentManager(), new StoryPagerFragment(true, roomId, 1, roomTitle)).setReplace(false).load();
            } else {
                new HelperFragment(getActivity().getSupportFragmentManager(), new StoryPagerFragment(false)).setReplace(false).load();
            }
        }
    });
    customStatusActionLayout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            if (listMode == 1) {
                new HelperFragment(getActivity().getSupportFragmentManager(), new StatusTextFragment(true, roomId, 1, roomTitle)).setReplace(false).load();
            } else {
                new HelperFragment(getActivity().getSupportFragmentManager(), new StatusTextFragment(false)).setReplace(false).load();
            }
        }
    });
    mOffset = 0;
    recyclerListView.addOnScrollListener(new RecyclerView.OnScrollListener() {

        private boolean scrollUpdated;

        private boolean scrollingManually;

        private int prevTop;

        private int prevPosition;

        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            scrollingManually = newState == RecyclerView.SCROLL_STATE_DRAGGING;
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
            View view = layoutManager.getChildAt(0);
            if (firstVisibleItemPosition > 0 && view != null) {
                firstVisibleItemPositionOffset = view.getTop();
            }
            if (!storyListFetched) {
                if (mOffset > 0) {
                    int lastVisiblePosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
                    if (lastVisiblePosition + 10 >= mOffset) {
                    // GetStoryList(mOffset, 50);
                    }
                }
            }
            int firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
            if (firstVisibleItem != RecyclerView.NO_POSITION) {
                RecyclerView.ViewHolder holder = recyclerView.findViewHolderForAdapterPosition(firstVisibleItem);
                if (holder != null && holder.getAdapterPosition() != 0) {
                    int firstViewTop = holder.itemView.getTop();
                    boolean goingDown;
                    boolean changed = true;
                    if (prevPosition == firstVisibleItem) {
                        final int topDelta = prevTop - firstViewTop;
                        goingDown = firstViewTop < prevTop;
                        changed = Math.abs(topDelta) > 1;
                    } else {
                        goingDown = firstVisibleItem > prevPosition;
                    }
                    if (changed && scrollUpdated && (goingDown || scrollingManually)) {
                        hideFloatingButton(goingDown);
                    }
                    prevPosition = firstVisibleItem;
                    prevTop = firstViewTop;
                    scrollUpdated = true;
                }
            }
        }
    });
}
Also used : IG_RPC(net.iGap.network.IG_RPC) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) RecyclerListView(net.iGap.module.customView.RecyclerListView) IconView(net.iGap.messenger.ui.components.IconView) StatusTextFragment(net.iGap.story.StatusTextFragment) AbstractObject(net.iGap.network.AbstractObject) RecyclerView(androidx.recyclerview.widget.RecyclerView) HelperFragment(net.iGap.helper.HelperFragment) StoryPagerFragment(net.iGap.story.StoryPagerFragment)

Example 2 with StoryPagerFragment

use of net.iGap.story.StoryPagerFragment in project iGap-Android by KianIranian-STDG.

the class FragmentChat method initComponent.

@SuppressLint("ClickableViewAccessibility")
private void initComponent() {
    final RealmRoom realmRoom = getRoom();
    ll_attach_text = rootView.findViewById(R.id.ac_ll_attach_text);
    txtFileNameForSend = rootView.findViewById(R.id.ac_txt_file_neme_for_sending);
    btnCancelSendingFile = rootView.findViewById(R.id.ac_btn_cancel_sending_file);
    btnCancelSendingFile.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            ll_attach_text.setVisibility(View.GONE);
            edtChat.setFilters(new InputFilter[] {});
            edtChat.setText(EmojiManager.getInstance().replaceEmoji(edtChat.getText(), edtChat.getPaint().getFontMetricsInt(), LayoutCreator.dp(22), false));
            edtChat.setSelection(edtChat.getText().length());
            if (edtChat.getText().length() == 0) {
                sendButtonVisibility(false);
            }
        }
    });
    // final int screenWidth = (int) (getResources().getDisplayMetrics().widthPixels / 1.2);
    imvSmileButton = rootView.findViewById(R.id.tv_chatRoom_emoji);
    edtChat.requestFocus();
    edtChat.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (isEmojiSHow) {
                imvSmileButton.performClick();
            }
            if (botInit != null)
                botInit.close();
        }
    });
    if (viewAttachFile != null) {
    // LinearLayout linearLayout = (LinearLayout) viewAttachFile;
    // voiceHintTextView = new HintView(G.context, 9);
    }
    imvAttachFileButton = rootView.findViewById(R.id.vtn_chatRoom_attach);
    layoutAttachBottom = rootView.findViewById(R.id.ll_chatRoom_send);
    imvMicButton = rootView.findViewById(R.id.btn_chatRoom_mic);
    imvAddStoryButton = rootView.findViewById(R.id.btn_chatRoom_add_story);
    actionButtonsRootView = rootView.findViewById(R.id.chat_action_buttons_root_view);
    customStatusActionLayout = rootView.findViewById(R.id.custom_status_action_root);
    floatActionLayout = rootView.findViewById(R.id.add_story_action_root);
    customStatusActionLayout.setBackground(Theme.createSimpleSelectorCircleDrawable(LayoutCreator.dp(56), Theme.getInstance().getToolbarBackgroundColor(context), Theme.getInstance().getAccentColor(context)));
    floatActionLayout.setBackground(Theme.createSimpleSelectorCircleDrawable(LayoutCreator.dp(56), Theme.getInstance().getToolbarBackgroundColor(context), Theme.getInstance().getAccentColor(context)));
    hideFloatingButton(true);
    if (isBot) {
        botInit = new BotInit(rootView, false);
        sendButtonVisibility(false);
        RealmRoomMessage rm = null;
        String lastMessage = "";
        boolean backToMenu = true;
        RealmResults<RealmRoomMessage> result = DbManager.getInstance().doRealmTask(realm -> {
            return realm.where(RealmRoomMessage.class).equalTo("roomId", mRoomId).notEqualTo("authorHash", RealmUserInfo.getCurrentUserAuthorHash()).findAll();
        });
        if (result.size() > 0) {
            rm = result.last();
            if (rm.getMessage() != null) {
                lastMessage = rm.getMessage();
            }
        }
        try {
            if (rm.getRealmAdditional() != null && rm.getRealmAdditional().getAdditionalType() == AdditionalType.UNDER_KEYBOARD_BUTTON) {
                botInit.updateCommandList(false, lastMessage, getActivity(), backToMenu, rm, rm.getRoomId());
            }
        } catch (Exception e) {
        }
    }
    mAdapter = new MessagesAdapter<>(managedRoom, this, this, this, avatarHandler, compositeDisposable, isCloudRoom);
    mAdapter.getItemFilter().withFilterPredicate(new IItemAdapter.Predicate<AbstractMessage>() {

        @Override
        public boolean filter(AbstractMessage item, CharSequence constraint) {
            return !item.messageObject.message.toLowerCase().contains(constraint.toString().toLowerCase());
        }
    });
    // FragmentMain.PreCachingLayoutManager layoutManager = new FragmentMain.PreCachingLayoutManager(ActivityChat.this, 7500);
    MyLinearLayoutManager layoutManager = new MyLinearLayoutManager(G.fragmentActivity);
    layoutManager.setStackFromEnd(true);
    if (recyclerView == null) {
        recyclerView = rootView.findViewById(R.id.chl_recycler_view_chat);
    }
    recyclerView.setItemAnimator(null);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(mAdapter);
    recyclerView.setItemViewCacheSize(20);
    if (realmRoom != null && !realmRoom.getReadOnly()) {
        ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return true;
            }

            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                try {
                    // TODO: 12/28/20  MESSAGE_REFACTOR
                    MessageObject message_ = (mAdapter.getItem(viewHolder.getAdapterPosition())).messageObject;
                    if (message_ != null && message_.status != ProtoGlobal.RoomMessageStatus.SENDING_VALUE && message_.status != ProtoGlobal.RoomMessageStatus.FAILED_VALUE) {
                        if (isReply)
                            reply((mAdapter.getItem(viewHolder.getAdapterPosition())).messageObject, false);
                    }
                } catch (Exception ignored) {
                    ignored.printStackTrace();
                }
                isReply = false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            }

            @Override
            public void onChildDraw(@NotNull Canvas c, @NotNull RecyclerView recyclerView, @NotNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
                if (actionState == ACTION_STATE_SWIPE && isCurrentlyActive) {
                    setTouchListener(recyclerView, dX);
                }
                dX = dX + ViewMaker.dpToPixel(25);
                if (dX > 0)
                    dX = 0;
                if (dX < -ViewMaker.dpToPixel(150)) {
                    dX = -ViewMaker.dpToPixel(150);
                }
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }

            @Override
            public float getSwipeThreshold(@NonNull RecyclerView.ViewHolder viewHolder) {
                return super.getSwipeThreshold(viewHolder);
            }

            @Override
            public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                // TODO: 12/28/20 MESSAGE_REFACTOR
                MessageObject message_ = null;
                try {
                    message_ = (mAdapter.getItem(viewHolder.getAdapterPosition())).messageObject;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (message_ != null && (message_.status == ProtoGlobal.RoomMessageStatus.SENDING_VALUE || message_.status == ProtoGlobal.RoomMessageStatus.FAILED_VALUE)) {
                    return 0;
                } else if (viewHolder instanceof VoiceItem.ViewHolder) {
                    return 0;
                } else if (viewHolder instanceof AudioItem.ViewHolder) {
                    return 0;
                } else if (viewHolder instanceof NewChatItemHolder) {
                    return super.getSwipeDirs(recyclerView, viewHolder);
                }
                // we disable swipe with returning Zero
                return 0;
            }

            @Override
            public int convertToAbsoluteDirection(int flags, int layoutDirection) {
                if (swipeBack) {
                    swipeBack = false;
                    return 0;
                }
                return super.convertToAbsoluteDirection(flags, layoutDirection);
            }

            @Override
            public boolean isItemViewSwipeEnabled() {
                return !FragmentChat.isInSelectionMode;
            }
        };
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
        itemTouchHelper.attachToRecyclerView(recyclerView);
    }
    /**
     * load message , use handler for load async
     */
    visibilityTextEmptyMessages();
    mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            visibilityTextEmptyMessages();
        }

        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            super.onItemRangeRemoved(positionStart, itemCount);
            visibilityTextEmptyMessages();
        }
    });
    // added run time -> counter of un read messages
    llScrollNavigate = rootView.findViewById(R.id.ac_ll_scrool_navigate);
    txtNewUnreadMessage = new BadgeView(getContext());
    txtNewUnreadMessage.getTextView().setTypeface(ResourcesCompat.getFont(txtNewUnreadMessage.getContext(), R.font.main_font));
    txtNewUnreadMessage.getTextView().setSingleLine();
    // set max length
    txtNewUnreadMessage.getTextView().setFilters(new InputFilter[] { new InputFilter.LengthFilter(5) });
    txtNewUnreadMessage.setBadgeColor(new Theme().getPrimaryDarkColor(txtNewUnreadMessage.getContext()));
    llScrollNavigate.addView(txtNewUnreadMessage, LayoutCreator.createFrame(LayoutCreator.WRAP_CONTENT, LayoutCreator.WRAP_CONTENT, Gravity.CENTER | Gravity.TOP));
    G.handler.post(() -> {
        AndroidUtils.globalQueue.postRunnable(this::getMessages);
        manageForwardedMessage(false);
    });
    MaterialDesignTextView txtNavigationLayout = rootView.findViewById(R.id.ac_txt_down_navigation);
    llScrollNavigate.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            cancelAllRequestFetchHistory();
            // Todo : also needed: block future Request
            latestButtonClickTime = System.currentTimeMillis();
            /**
             * have unread
             */
            if (countNewMessage > 0 && getFirstUnreadMessage() != null) {
                if (!getFirstUnreadMessage().isValid() || getFirstUnreadMessage().isDeleted()) {
                    resetAndGetFromEnd();
                    return;
                }
                int position = mAdapter.findPositionByMessageId(getFirstUnreadMessage().getMessageId());
                String m = getFirstUnreadMessage().getMessage();
                if (position > 0) {
                    mAdapter.add(position, new UnreadMessage(mAdapter, FragmentChat.this).setMessage(MessageObject.create(makeUnreadMessage(countNewMessage))).withIdentifier(SUID.id().get()));
                    isShowLayoutUnreadMessage = true;
                    LinearLayoutManager linearLayout = (LinearLayoutManager) recyclerView.getLayoutManager();
                    linearLayout.scrollToPositionWithOffset(position, 0);
                } else {
                    resetMessagingValue();
                    unreadCount = countNewMessage;
                    getMessages();
                    if (getFirstUnreadMessage() == null) {
                        resetAndGetFromEnd();
                        return;
                    }
                    int position1 = mAdapter.findPositionByMessageId(getFirstUnreadMessage().getMessageId());
                    if (position1 > 0) {
                        LinearLayoutManager linearLayout = (LinearLayoutManager) recyclerView.getLayoutManager();
                        linearLayout.scrollToPositionWithOffset(position1 - 1, 0);
                    }
                }
                setCountNewMessageZero();
            } else {
                if (!addToView) {
                    resetMessagingValue();
                    getMessages();
                } else {
                    scrollToEnd();
                }
            }
        }
    });
    recyclerView.setOnFlingListener(new RecyclerView.OnFlingListener() {

        @Override
        public boolean onFling(int velocityX, int velocityY) {
            return false;
        }
    });
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                G.imageLoader.resume();
            } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                G.imageLoader.pause();
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int visibleItemCount = recyclerView.getLayoutManager().getChildCount();
            int totalItemCount = recyclerView.getLayoutManager().getItemCount();
            int pastVisibleItems = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
            cardFloatingTime.setVisibility(View.VISIBLE);
            long item = mAdapter.getItemByPosition(layoutManager.findFirstVisibleItemPosition());
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(item);
            if (item != 0L) {
                txtFloatingTime.setText(TimeUtils.getChatSettingsTimeAgo(G.fragmentActivity, calendar.getTime()));
            }
            gongingHandler.removeCallbacks(gongingRunnable);
            gongingHandler.postDelayed(gongingRunnable, 1000);
            if (totalItemCount - pastVisibleItems <= 2 && !isAnimateStart) {
                isAnimateStart = true;
                isAnimateStart = false;
                setDownBtnGone();
            // llScrollNavigate.animate()
            // .alpha(0.0f)
            // .translationY(llScrollNavigate.getHeight() / 2)
            // .setDuration(200)
            // .setListener(new AnimatorListenerAdapter() {
            // @Override
            // public void onAnimationEnd(Animator animation) {
            // super.onAnimationEnd(animation);
            // }
            // });
            } else if (!isScrollEnd && !isAnimateStart) {
                isAnimateStart = true;
                setDownBtnVisible();
                isAnimateStart = false;
                // llScrollNavigate.animate()
                // .alpha(1.0f)
                // .translationY(0)
                // .setDuration(200)
                // .setListener(new AnimatorListenerAdapter() {
                // @Override
                // public void onAnimationEnd(Animator animation) {
                // super.onAnimationEnd(animation);
                // }
                // });
                txtNewUnreadMessage.getTextView().setText(countNewMessage + "");
                if (countNewMessage == 0) {
                    txtNewUnreadMessage.setVisibility(View.GONE);
                } else {
                    txtNewUnreadMessage.setVisibility(View.VISIBLE);
                }
            }
        }
    });
    /*       if (event.getAction() == MotionEvent.ACTION_CANCEL) {
            card.setCardBackgroundColor(Color.parseColor("#ffffff"));
        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            //    event.addBatch(0,0,0,0,0,0);
            //            card.setCardBackgroundColor(Color.parseColor("#ffffff"));
        } else if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {

            card.setCardBackgroundColor(Color.parseColor("#20000000"));

        } else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
            */
    /* Reset Color */
    /*
            card.setCardBackgroundColor(Color.parseColor("#ffffff"));
            //  card.setOnClickListener(clickListener);

        }
        return false;
*/
    recyclerView.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return false;
        }
    });
    imvSendButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            lastChar = null;
            if (!addToView) {
                resetAndGetFromEnd();
            }
            if (suggestedLayout != null) {
                if (suggestedLayout.getVisibility() == View.VISIBLE)
                    suggestedLayout.setVisibility(View.GONE);
                lastChar = null;
            }
            if (isShowLayoutUnreadMessage) {
                removeLayoutUnreadMessage();
            }
            HelperSetAction.setCancel(mRoomId);
            clearDraftRequest();
            if (hasForward) {
                manageForwardedMessage(false);
                if (edtChat.getText().length() == 0) {
                    return;
                }
            }
            if (ll_attach_text.getVisibility() == View.VISIBLE) {
                if (listPathString.size() == 0) {
                    return;
                }
                sendMessage(latestRequestCode, listPathString.get(0));
                listPathString.clear();
                ll_attach_text.setVisibility(View.GONE);
                edtChat.setFilters(new InputFilter[] {});
                edtChat.setText("");
                clearReplyView();
                return;
            }
            if (edtChat.getTag() != null && edtChat.getTag() instanceof MessageObject) {
                final MessageObject messageInfo = (MessageObject) edtChat.getTag();
                final String message = getWrittenMessage();
                if (!message.equals(messageInfo.message) && edtChat.getText().toString().trim().length() > 0) {
                    if (G.connectionState == ConnectionState.WAITING_FOR_NETWORK) {
                        Toast.makeText(getContext(), getResources().getString(R.string.please_check_your_connenction), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    chatRoom_send_container.setVisibility(View.VISIBLE);
                    imvSendButton.setVisibility(View.GONE);
                    editTextProgress.setVisibility(View.VISIBLE);
                    getMessageController().editMessage(messageInfo.id, messageInfo.documentId, mRoomId, message, chatType.getNumber());
                } else {
                    removeEditedMessage();
                }
            } else {
                // new message has written
                sendNewMessage(getWrittenMessage());
                scrollToEnd();
            }
            oldMessageLentghCounter = 0;
            messageLentghCounter = 0;
        }
    });
    G.openBottomSheetItem = new OpenBottomSheetItem() {

        @Override
        public void openBottomSheet(boolean isNew) {
            if (mAttachmentPopup != null)
                mAttachmentPopup.setIsNewDialog(isNew);
            imvAttachFileButton.performClick();
            if (mAttachmentPopup != null)
                mAttachmentPopup.notifyRecyclerView();
        }
    };
    FragmentEditImage.completeEditImage = new FragmentEditImage.CompleteEditImage() {

        @Override
        public void result(String path, String message, HashMap<String, StructBottomSheet> textImageList) {
            listPathString = null;
            listPathString = new ArrayList<>();
            if (textImageList.size() == 0) {
                return;
            }
            ArrayList<StructBottomSheet> itemList = new ArrayList<StructBottomSheet>();
            for (Map.Entry<String, StructBottomSheet> items : textImageList.entrySet()) {
                itemList.add(items.getValue());
            }
            Collections.sort(itemList);
            for (StructBottomSheet item : itemList) {
                edtChat.setText(EmojiManager.getInstance().replaceEmoji(item.getText(), edtChat.getPaint().getFontMetricsInt(), LayoutCreator.dp(22), false));
                listPathString.add(item.getPath());
                latestRequestCode = AttachFile.requestOpenGalleryForImageMultipleSelect;
                ll_attach_text.setVisibility(View.VISIBLE);
                imvSendButton.performClick();
            }
        }
    };
    imvAttachFileButton.setOnClickListener(view -> {
        if (getActivity() == null)
            return;
        if (mAttachmentPopup == null)
            initPopupAttachment();
        mAttachmentPopup.setMessagesLayoutHeight(recyclerView.getMeasuredHeight());
        hideKeyboard();
        mAttachmentPopup.show();
    });
    sendMoney.setOnClickListener(view -> {
        if ((chatType == CHAT) && !isCloudRoom && !isBot) {
            showSelectItem();
        } else {
            showCardToCard();
        }
        if (keyboardViewVisible) {
            hideKeyboard();
        }
    });
    customStatusActionLayout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            if (getActivity() != null) {
                hideFloatingButton(true);
                new HelperFragment(getActivity().getSupportFragmentManager(), new StatusTextFragment(true, mRoomId, 0, title)).setReplace(false).load();
            }
        }
    });
    floatActionLayout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            if (getActivity() != null) {
                hideFloatingButton(true);
                new HelperFragment(getActivity().getSupportFragmentManager(), new StoryPagerFragment(true, mRoomId, 0, title)).setReplace(false).load();
            }
        }
    });
    imvAddStoryButton.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View view) {
            if (keyboardViewVisible) {
                hideKeyboard();
            }
            if (!MessageController.isSendingRoomStory && !MessageController.isSendingStory) {
                hideFloatingButton(false);
            }
            return true;
        }
    });
    imvAddStoryButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            hideFloatingButton(true);
            micAndAddStoryAnimateVisible(false);
        }
    });
    imvMicButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            if (chatType == CHANNEL) {
                if (channelRole == ChannelChatRole.OWNER && !isRecording) {
                    micAndAddStoryAnimateVisible(true);
                }
            }
        }
    });
    Runnable recordVoiceRunnable = new Runnable() {

        @Override
        public void run() {
            isLongPress = true;
            if (isLongPress) {
                Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(100);
                if (mustCheckPermission()) {
                    if (currentRoomAccess != null && !currentRoomAccess.getRealmPostMessageRights().isCanSendMedia()) {
                        Toast.makeText(getContext(), getResources().getString(R.string.restrictions_on_sending_multimedia_messages), Toast.LENGTH_SHORT).show();
                        isLongPress = false;
                    }
                }
                if (keyboardViewVisible)
                    hideKeyboard();
                if (ContextCompat.checkSelfPermission(G.fragmentActivity, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                    try {
                        HelperPermission.getMicroPhonePermission(G.fragmentActivity, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    isRecording = true;
                    voiceRecord.setItemTag("ivVoice");
                    viewMicRecorder.setVisibility(View.VISIBLE);
                    AppUtils.setVibrator(50);
                    voiceRecord.startVoiceRecord();
                }
            }
        }
    };
    imvMicButton.setOnTouchListener((v, event) -> {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            G.runOnUiThread(recordVoiceRunnable, longClickDuration);
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            G.cancelRunOnUiThread(recordVoiceRunnable);
            isLongPress = false;
        }
        return isLongPress;
    });
    imvSmileButton.setOnClickListener(v -> onEmojiButtonClick());
    edtChat.addTextChangedListener(new TextWatcher() {

        boolean processChange = false;

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence text, int start, int before, int count) {
            if (text.length() > 0) {
                HelperSetAction.setActionTyping(mRoomId, chatType);
            }
            // if in the seeting page send by enter is on message send by enter key
            if (text.toString().endsWith(System.getProperty("line.separator"))) {
                if (sendByEnter)
                    imvSendButton.performClick();
            }
            messageLentghCounter = ((int) Math.ceil((float) text.length() / (float) Config.MAX_TEXT_LENGTH));
            if (messageLentghCounter > 1 && messageLentghCounter != oldMessageLentghCounter && getContext() != null) {
                oldMessageLentghCounter = messageLentghCounter;
                Toast.makeText(getContext(), getString(R.string.message_is_long) + " " + messageLentghCounter + " " + getString(R.string.message), Toast.LENGTH_SHORT).show();
            }
            if ((count - before) > 1) {
                processChange = true;
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (ll_attach_text.getVisibility() == View.GONE && !hasForward) {
                if (edtChat.getText() != null && edtChat.getText().length() > 0) {
                    sendButtonVisibility(true);
                } else {
                    if (!isEditMessage) {
                        sendButtonVisibility(false);
                    }
                }
                if (processChange) {
                    ImageSpan[] spans = editable.getSpans(0, editable.length(), ImageSpan.class);
                    for (ImageSpan span : spans) {
                        editable.removeSpan(span);
                    }
                    EmojiManager.getInstance().replaceEmoji(editable, edtChat.getPaint().getFontMetricsInt(), LayoutCreator.dp(20), false);
                    processChange = false;
                }
            }
            if (edtChat.getText() != null && !EmojiManager.getInstance().isValidEmoji(edtChat.getText()) && suggestedLayout != null && suggestedLayout.getVisibility() == View.VISIBLE) {
                suggestedLayout.setVisibility(View.GONE);
                lastChar = null;
            } else if (lastChar != null) {
                lastChar = null;
            }
        }
    });
}
Also used : ArrayList(java.util.ArrayList) RealmString(net.iGap.realm.RealmString) HelperString(net.iGap.helper.HelperString) MyLinearLayoutManager(net.iGap.module.MyLinearLayoutManager) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) MaterialDesignTextView(net.iGap.module.MaterialDesignTextView) UnreadMessage(net.iGap.adapter.items.chat.UnreadMessage) RealmRoomMessage.makeUnreadMessage(net.iGap.realm.RealmRoomMessage.makeUnreadMessage) NonNull(androidx.annotation.NonNull) IItemAdapter(com.mikepenz.fastadapter.IItemAdapter) RealmRoom(net.iGap.realm.RealmRoom) BotInit(net.iGap.module.BotInit) StoryPagerFragment(net.iGap.story.StoryPagerFragment) InputFilter(android.text.InputFilter) AbstractMessage(net.iGap.adapter.items.chat.AbstractMessage) Canvas(android.graphics.Canvas) BadgeView(net.iGap.adapter.items.chat.BadgeView) NewChatItemHolder(net.iGap.adapter.items.chat.NewChatItemHolder) RealmRoomMessage(net.iGap.realm.RealmRoomMessage) HelperFragment(net.iGap.helper.HelperFragment) ImageSpan(android.text.style.ImageSpan) MyLinearLayoutManager(net.iGap.module.MyLinearLayoutManager) NotNull(org.jetbrains.annotations.NotNull) ItemTouchHelper(androidx.recyclerview.widget.ItemTouchHelper) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) OpenBottomSheetItem(net.iGap.observers.interfaces.OpenBottomSheetItem) Calendar(java.util.Calendar) StructBottomSheet(net.iGap.module.structs.StructBottomSheet) IOException(java.io.IOException) NumberTextView(net.iGap.messenger.ui.toolBar.NumberTextView) KeyboardView(net.iGap.libs.emojiKeyboard.KeyboardView) RecyclerView(androidx.recyclerview.widget.RecyclerView) AppCompatTextView(androidx.appcompat.widget.AppCompatTextView) EmojiView(net.iGap.libs.emojiKeyboard.EmojiView) BadgeView(net.iGap.adapter.items.chat.BadgeView) MaterialDesignTextView(net.iGap.module.MaterialDesignTextView) ImageView(android.widget.ImageView) CardView(androidx.cardview.widget.CardView) FontIconTextView(net.iGap.module.FontIconTextView) StructWebView(net.iGap.module.structs.StructWebView) AppCompatImageView(androidx.appcompat.widget.AppCompatImageView) View(android.view.View) WebView(android.webkit.WebView) TextView(android.widget.TextView) IOException(java.io.IOException) JsonSyntaxException(com.google.gson.JsonSyntaxException) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) StatusTextFragment(net.iGap.story.StatusTextFragment) VoiceItem(net.iGap.adapter.items.chat.VoiceItem) Theme(net.iGap.module.Theme) RecyclerView(androidx.recyclerview.widget.RecyclerView) Vibrator(android.os.Vibrator) MessageObject(net.iGap.structs.MessageObject) SuppressLint(android.annotation.SuppressLint)

Example 3 with StoryPagerFragment

use of net.iGap.story.StoryPagerFragment in project iGap-Android by KianIranian-STDG.

the class StoryFragment method onViewCreated.

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getEventManager().addObserver(EventManager.STORY_LIST_FETCHED, this);
    getEventManager().addObserver(EventManager.STORY_DELETED, this);
    getEventManager().addObserver(EventManager.STORY_ALL_SEEN, this);
    getEventManager().addObserver(EventManager.STORY_USER_ADD_NEW, this);
    getEventManager().addObserver(EventManager.STORY_SENDING, this);
    getEventManager().addObserver(EventManager.STORY_UPLOAD, this);
    getEventManager().addObserver(EventManager.STORY_UPLOADED_FAILED, this);
    getEventManager().addObserver(EventManager.STORY_USER_INFO, this);
    getEventManager().addObserver(EventManager.STORY_STATUS_UPLOAD, this);
    getEventManager().addObserver(EventManager.STORY_ROOM_UPLOAD, this);
    getEventManager().addObserver(EventManager.STORY_ROOM_IMAGE_UPLOAD, this);
    mOffset = 0;
    userIdList = new ArrayList<>();
    displayNameList = new ArrayList<>();
    progressBar.setVisibility(View.VISIBLE);
    loadStories();
    floatActionLayout.setOnClickListener(view1 -> {
        HelperTracker.sendTracker(HelperTracker.TRACKER_MOMENTS_CREATE_PICTURE_PAGE);
        new HelperFragment(getActivity().getSupportFragmentManager(), new StoryPagerFragment(false)).setReplace(false).load();
    });
    customStatusActionLayout.setOnClickListener(view12 -> {
        HelperTracker.sendTracker(HelperTracker.TRACKER_MOMENTS_CREATE_TEXT_PAGE);
        new HelperFragment(StoryFragment.this.getActivity().getSupportFragmentManager(), new StatusTextFragment(false)).setReplace(false).load();
    });
    swipeRefreshLayout.setOnRefreshListener(() -> {
        swipeRefreshLayout.setRefreshing(false);
        DbManager.getInstance().doRealmTransaction(realm -> {
            MessageController.getInstance(AccountManager.selectedAccount).getStories(realm.where(RealmContacts.class).findAll().size());
        });
    });
    recyclerListView.addOnScrollListener(new RecyclerView.OnScrollListener() {

        private boolean scrollUpdated;

        private boolean scrollingManually;

        private int prevTop;

        private int prevPosition;

        private int currentScrollPosition = 0;

        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            scrollingManually = newState == RecyclerView.SCROLL_STATE_DRAGGING;
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            currentScrollPosition += dy;
            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
            View view = layoutManager.getChildAt(0);
            if (firstVisibleItemPosition > 0 && view != null) {
                firstVisibleItemPositionOffset = view.getTop();
            }
            if (!storyListFetched) {
                if (mOffset > 0) {
                    int lastVisiblePosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
                    if (lastVisiblePosition + 10 >= mOffset) {
                    // GetStoryList(mOffset, 50);
                    }
                }
            }
            // if (currentScrollPosition == 0) {
            // swipeRefreshLayout.setRefreshing(true);
            // }
            int firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
            if (firstVisibleItem != RecyclerView.NO_POSITION) {
                RecyclerView.ViewHolder holder = recyclerView.findViewHolderForAdapterPosition(firstVisibleItem);
                if (holder != null && holder.getAdapterPosition() != 0) {
                    int firstViewTop = holder.itemView.getTop();
                    boolean goingDown;
                    boolean changed = true;
                    if (prevPosition == firstVisibleItem) {
                        final int topDelta = prevTop - firstViewTop;
                        goingDown = firstViewTop < prevTop;
                        changed = Math.abs(topDelta) > 1;
                    } else {
                        goingDown = firstVisibleItem > prevPosition;
                    }
                    if (changed && scrollUpdated && (goingDown || scrollingManually)) {
                        hideFloatingButton(goingDown);
                    }
                    prevPosition = firstVisibleItem;
                    prevTop = firstViewTop;
                    scrollUpdated = true;
                }
            }
        }
    });
    AbstractObject req = null;
    IG_RPC.Story_Get_Own_Story_Views story_get_own_story_views = new IG_RPC.Story_Get_Own_Story_Views();
    story_get_own_story_views.offset = 0;
    story_get_own_story_views.limit = 50;
    req = story_get_own_story_views;
    getRequestManager().sendRequest(req, (response, error) -> {
        if (error == null) {
            IG_RPC.Res_Story_Get_Own_Story_Views res = (IG_RPC.Res_Story_Get_Own_Story_Views) response;
            getMessageDataStorage().updateOwnViews(res.groupedViews);
        } else {
        }
    });
}
Also used : IG_RPC(net.iGap.network.IG_RPC) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) RecyclerListView(net.iGap.module.customView.RecyclerListView) IconView(net.iGap.messenger.ui.components.IconView) StatusTextFragment(net.iGap.story.StatusTextFragment) AbstractObject(net.iGap.network.AbstractObject) RecyclerView(androidx.recyclerview.widget.RecyclerView) HelperFragment(net.iGap.helper.HelperFragment) StoryPagerFragment(net.iGap.story.StoryPagerFragment) RealmContacts(net.iGap.realm.RealmContacts)

Aggregations

View (android.view.View)3 LinearLayoutManager (androidx.recyclerview.widget.LinearLayoutManager)3 RecyclerView (androidx.recyclerview.widget.RecyclerView)3 HelperFragment (net.iGap.helper.HelperFragment)3 StatusTextFragment (net.iGap.story.StatusTextFragment)3 StoryPagerFragment (net.iGap.story.StoryPagerFragment)3 IconView (net.iGap.messenger.ui.components.IconView)2 SuppressLint (android.annotation.SuppressLint)1 Canvas (android.graphics.Canvas)1 Vibrator (android.os.Vibrator)1 Editable (android.text.Editable)1 InputFilter (android.text.InputFilter)1 TextWatcher (android.text.TextWatcher)1 ImageSpan (android.text.style.ImageSpan)1 MotionEvent (android.view.MotionEvent)1 WebView (android.webkit.WebView)1 ImageView (android.widget.ImageView)1 TextView (android.widget.TextView)1 NonNull (androidx.annotation.NonNull)1 AppCompatImageView (androidx.appcompat.widget.AppCompatImageView)1