List of usage examples for android.widget FrameLayout addView
public void addView(View child, int index)
From source file:org.telegram.ui.ProfileActivity.java
@Override public View createView(Context context) { hasOwnBackground = true;/*from www. j a v a 2 s . co m*/ extraHeight = AndroidUtilities.dp(88); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(final int id) { if (getParentActivity() == null) { return; } if (id == -1) { finishFragment(); } else if (id == block_contact) { TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (user == null) { return; } if (!user.bot) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); if (!userBlocked) { builder.setMessage(LocaleController.getString("AreYouSureBlockContact", R.string.AreYouSureBlockContact)); } else { builder.setMessage(LocaleController.getString("AreYouSureUnblockContact", R.string.AreYouSureUnblockContact)); } builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (!userBlocked) { MessagesController.getInstance().blockUser(user_id); } else { MessagesController.getInstance().unblockUser(user_id); } } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } else { if (!userBlocked) { MessagesController.getInstance().blockUser(user_id); } else { MessagesController.getInstance().unblockUser(user_id); SendMessagesHelper.getInstance().sendMessage("/start", user_id, null, null, false, null, null, null); finishFragment(); } } } else if (id == add_contact) { TLRPC.User user = MessagesController.getInstance().getUser(user_id); Bundle args = new Bundle(); args.putInt("user_id", user.id); args.putBoolean("addContact", true); presentFragment(new ContactAddActivity(args)); } else if (id == share_contact) { Bundle args = new Bundle(); args.putBoolean("onlySelect", true); args.putInt("dialogsType", 1); args.putString("selectAlertString", LocaleController.getString("SendContactTo", R.string.SendContactTo)); args.putString("selectAlertStringGroup", LocaleController.getString("SendContactToGroup", R.string.SendContactToGroup)); DialogsActivity fragment = new DialogsActivity(args); fragment.setDelegate(ProfileActivity.this); presentFragment(fragment); } else if (id == edit_contact) { Bundle args = new Bundle(); args.putInt("user_id", user_id); presentFragment(new ContactAddActivity(args)); } else if (id == delete_contact) { final TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (user == null || getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setMessage(LocaleController.getString("AreYouSureDeleteContact", R.string.AreYouSureDeleteContact)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ArrayList<TLRPC.User> arrayList = new ArrayList<>(); arrayList.add(user); ContactsController.getInstance().deleteContact(arrayList); } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } else if (id == leave_group) { leaveChatPressed(); } else if (id == edit_name) { Bundle args = new Bundle(); args.putInt("chat_id", chat_id); presentFragment(new ChangeChatNameActivity(args)); } else if (id == edit_channel) { Bundle args = new Bundle(); args.putInt("chat_id", chat_id); ChannelEditActivity fragment = new ChannelEditActivity(args); fragment.setInfo(info); presentFragment(fragment); } else if (id == invite_to_group) { final TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (user == null) { return; } Bundle args = new Bundle(); args.putBoolean("onlySelect", true); args.putInt("dialogsType", 2); args.putString("addToGroupAlertString", LocaleController.formatString("AddToTheGroupTitle", R.string.AddToTheGroupTitle, UserObject.getUserName(user), "%1$s")); DialogsActivity fragment = new DialogsActivity(args); fragment.setDelegate(new DialogsActivity.DialogsActivityDelegate() { @Override public void didSelectDialog(DialogsActivity fragment, long did, boolean param) { Bundle args = new Bundle(); args.putBoolean("scrollToTopOnResume", true); args.putInt("chat_id", -(int) did); if (!MessagesController.checkCanOpenChat(args, fragment)) { return; } NotificationCenter.getInstance().removeObserver(ProfileActivity.this, NotificationCenter.closeChats); NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); MessagesController.getInstance().addUserToChat(-(int) did, user, null, 0, null, ProfileActivity.this); presentFragment(new ChatActivity(args), true); removeSelfFromStack(); } }); presentFragment(fragment); } else if (id == share) { try { TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (user == null) { return; } Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); String about = MessagesController.getInstance().getUserAbout(botInfo.user_id); if (botInfo != null && about != null) { intent.putExtra(Intent.EXTRA_TEXT, String.format("%s https://telegram.me/%s", about, user.username)); } else { intent.putExtra(Intent.EXTRA_TEXT, String.format("https://telegram.me/%s", user.username)); } startActivityForResult(Intent.createChooser(intent, LocaleController.getString("BotShare", R.string.BotShare)), 500); } catch (Exception e) { FileLog.e("tmessages", e); } } else if (id == set_admins) { Bundle args = new Bundle(); args.putInt("chat_id", chat_id); SetAdminsActivity fragment = new SetAdminsActivity(args); fragment.setChatInfo(info); presentFragment(fragment); } else if (id == convert_to_supergroup) { Bundle args = new Bundle(); args.putInt("chat_id", chat_id); presentFragment(new ConvertGroupActivity(args)); } else if (id == add_shortcut) { try { long did; if (currentEncryptedChat != null) { did = ((long) currentEncryptedChat.id) << 32; } else if (user_id != 0) { did = user_id; } else if (chat_id != 0) { did = -chat_id; } else { return; } AndroidUtilities.installShortcut(did); /*try { Toast.makeText(getParentActivity(), LocaleController.getString("ShortcutAdded", R.string.ShortcutAdded), Toast.LENGTH_SHORT).show(); } catch (Exception e) { FileLog.e("tmessages", e); }*/ } catch (Exception e) { FileLog.e("tmessages", e); } } } }); createActionBarMenu(); listAdapter = new ListAdapter(context); avatarDrawable = new AvatarDrawable(); avatarDrawable.setProfile(true); fragmentView = new FrameLayout(context) { @Override public boolean hasOverlappingRendering() { return false; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); checkListViewScroll(); } }; FrameLayout frameLayout = (FrameLayout) fragmentView; listView = new RecyclerListView(context) { @Override public boolean hasOverlappingRendering() { return false; } }; listView.setTag(6); listView.setPadding(0, AndroidUtilities.dp(88), 0, 0); listView.setBackgroundColor(ContextCompat.getColor(context, R.color.settings_background)); listView.setVerticalScrollBarEnabled(false); listView.setItemAnimator(null); listView.setLayoutAnimation(null); listView.setClipToPadding(false); layoutManager = new LinearLayoutManager(context) { @Override public boolean supportsPredictiveItemAnimations() { return false; } }; layoutManager.setOrientation(LinearLayoutManager.VERTICAL); listView.setLayoutManager(layoutManager); listView.setGlowColor(AvatarDrawable.getProfileBackColorForId( user_id != 0 || ChatObject.isChannel(chat_id) && !currentChat.megagroup ? 5 : chat_id)); frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT)); listView.setAdapter(listAdapter); listView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() { @Override public void onItemClick(View view, final int position) { if (getParentActivity() == null) { return; } if (position == sharedMediaRow) { Bundle args = new Bundle(); if (user_id != 0) { args.putLong("dialog_id", dialog_id != 0 ? dialog_id : user_id); } else { args.putLong("dialog_id", -chat_id); } MediaActivity fragment = new MediaActivity(args); fragment.setChatInfo(info); presentFragment(fragment); } else if (position == settingsKeyRow) { Bundle args = new Bundle(); args.putInt("chat_id", (int) (dialog_id >> 32)); presentFragment(new IdenticonActivity(args)); } else if (position == settingsTimerRow) { showDialog(AndroidUtilities.buildTTLAlert(getParentActivity(), currentEncryptedChat).create()); } else if (position == settingsNotificationsRow) { Bundle args = new Bundle(); if (user_id != 0) { args.putLong("dialog_id", dialog_id == 0 ? user_id : dialog_id); } else if (chat_id != 0) { args.putLong("dialog_id", -chat_id); } presentFragment(new ProfileNotificationsActivity(args)); } else if (position == startSecretChatRow) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setMessage( LocaleController.getString("AreYouSureSecretChat", R.string.AreYouSureSecretChat)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { creatingChat = true; SecretChatHelper.getInstance().startSecretChat(getParentActivity(), MessagesController.getInstance().getUser(user_id)); } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } else if (position > emptyRowChat2 && position < membersEndRow) { int user_id; if (!sortedUsers.isEmpty()) { user_id = info.participants.participants .get(sortedUsers.get(position - emptyRowChat2 - 1)).user_id; } else { user_id = info.participants.participants.get(position - emptyRowChat2 - 1).user_id; } if (user_id == UserConfig.getClientUserId()) { return; } Bundle args = new Bundle(); args.putInt("user_id", user_id); presentFragment(new ProfileActivity(args)); } else if (position == addMemberRow) { openAddMember(); } else if (position == channelNameRow) { try { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); if (info.about != null && info.about.length() > 0) { intent.putExtra(Intent.EXTRA_TEXT, currentChat.title + "\n" + info.about + "\nhttps://telegram.me/" + currentChat.username); } else { intent.putExtra(Intent.EXTRA_TEXT, currentChat.title + "\nhttps://telegram.me/" + currentChat.username); } getParentActivity().startActivityForResult(Intent.createChooser(intent, LocaleController.getString("BotShare", R.string.BotShare)), 500); } catch (Exception e) { FileLog.e("tmessages", e); } } else if (position == leaveChannelRow) { leaveChatPressed(); } else if (position == membersRow || position == blockedUsersRow || position == managementRow) { Bundle args = new Bundle(); args.putInt("chat_id", chat_id); if (position == blockedUsersRow) { args.putInt("type", 0); } else if (position == managementRow) { args.putInt("type", 1); } else if (position == membersRow) { args.putInt("type", 2); } presentFragment(new ChannelUsersActivity(args)); } else if (position == convertRow) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setMessage(LocaleController.getString("ConvertGroupAlert", R.string.ConvertGroupAlert)); builder.setTitle(LocaleController.getString("ConvertGroupAlertWarning", R.string.ConvertGroupAlertWarning)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { MessagesController.getInstance().convertToMegaGroup(getParentActivity(), chat_id); } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } else { processOnClickOrPress(position); } } }); listView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() { @Override public boolean onItemClick(View view, int position) { if (position > emptyRowChat2 && position < membersEndRow) { if (getParentActivity() == null) { return false; } boolean allowKick = false; boolean allowSetAdmin = false; final TLRPC.ChatParticipant user; if (!sortedUsers.isEmpty()) { user = info.participants.participants.get(sortedUsers.get(position - emptyRowChat2 - 1)); } else { user = info.participants.participants.get(position - emptyRowChat2 - 1); } selectedUser = user.user_id; if (ChatObject.isChannel(currentChat)) { TLRPC.ChannelParticipant channelParticipant = ((TLRPC.TL_chatChannelParticipant) user).channelParticipant; if (user.user_id != UserConfig.getClientUserId()) { if (currentChat.creator) { allowKick = true; } else if (channelParticipant instanceof TLRPC.TL_channelParticipant) { if (currentChat.editor || channelParticipant.inviter_id == UserConfig.getClientUserId()) { allowKick = true; } } } TLRPC.User u = MessagesController.getInstance().getUser(user.user_id); allowSetAdmin = channelParticipant instanceof TLRPC.TL_channelParticipant && !u.bot; } else { if (user.user_id != UserConfig.getClientUserId()) { if (currentChat.creator) { allowKick = true; } else if (user instanceof TLRPC.TL_chatParticipant) { if (currentChat.admin && currentChat.admins_enabled || user.inviter_id == UserConfig.getClientUserId()) { allowKick = true; } } } } if (!allowKick) { return false; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); if (currentChat.megagroup && currentChat.creator && allowSetAdmin) { CharSequence[] items = new CharSequence[] { LocaleController.getString("SetAsAdmin", R.string.SetAsAdmin), LocaleController.getString("KickFromGroup", R.string.KickFromGroup) }; builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (i == 0) { TLRPC.TL_chatChannelParticipant channelParticipant = ((TLRPC.TL_chatChannelParticipant) user); channelParticipant.channelParticipant = new TLRPC.TL_channelParticipantEditor(); channelParticipant.channelParticipant.inviter_id = UserConfig.getClientUserId(); channelParticipant.channelParticipant.user_id = user.user_id; channelParticipant.channelParticipant.date = user.date; TLRPC.TL_channels_editAdmin req = new TLRPC.TL_channels_editAdmin(); req.channel = MessagesController.getInputChannel(chat_id); req.user_id = MessagesController.getInputUser(selectedUser); req.role = new TLRPC.TL_channelRoleEditor(); ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, final TLRPC.TL_error error) { if (error == null) { MessagesController.getInstance() .processUpdates((TLRPC.Updates) response, false); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { MessagesController.getInstance().loadFullChat(chat_id, 0, true); } }, 1000); } else { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { AlertsCreator.showAddUserAlert(error.text, ProfileActivity.this, false); } }); } } }); } else if (i == 1) { kickUser(selectedUser); } } }); } else { CharSequence[] items = new CharSequence[] { chat_id > 0 ? LocaleController.getString("KickFromGroup", R.string.KickFromGroup) : LocaleController.getString("KickFromBroadcast", R.string.KickFromBroadcast) }; builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (i == 0) { kickUser(selectedUser); } } }); } showDialog(builder.create()); return true; } else { return processOnClickOrPress(position); } } }); topView = new TopView(context); topView.setBackgroundColor(AvatarDrawable.getProfileBackColorForId( user_id != 0 || ChatObject.isChannel(chat_id) && !currentChat.megagroup ? 5 : chat_id)); frameLayout.addView(topView); frameLayout.addView(actionBar); avatarImage = new BackupImageView(context); avatarImage.setRoundRadius(AndroidUtilities.dp(21)); avatarImage.setPivotX(0); avatarImage.setPivotY(0); frameLayout.addView(avatarImage, LayoutHelper.createFrame(42, 42, Gravity.TOP | Gravity.LEFT, 64, 0, 0, 0)); avatarImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (user_id != 0) { TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (user.photo != null && user.photo.photo_big != null) { PhotoViewer.getInstance().setParentActivity(getParentActivity()); PhotoViewer.getInstance().openPhoto(user.photo.photo_big, ProfileActivity.this); } } else if (chat_id != 0) { TLRPC.Chat chat = MessagesController.getInstance().getChat(chat_id); if (chat.photo != null && chat.photo.photo_big != null) { PhotoViewer.getInstance().setParentActivity(getParentActivity()); PhotoViewer.getInstance().openPhoto(chat.photo.photo_big, ProfileActivity.this); } } } }); for (int a = 0; a < 2; a++) { if (!playProfileAnimation && a == 0) { continue; } nameTextView[a] = new AutoMarqueeTextView(context); nameTextView[a].setTextColor(0xffffffff); nameTextView[a].setTextSize(18); nameTextView[a].setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL); nameTextView[a].setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); nameTextView[a].setCompoundDrawablePadding(-AndroidUtilities.dp(1.3f)); nameTextView[a].setMaxLines(1); /*nameTextView[a].setLeftDrawableTopPadding(-AndroidUtilities.dp(1.3f)); nameTextView[a].setRightDrawableTopPadding(-AndroidUtilities.dp(1.3f));*/ nameTextView[a].setPivotX(0); nameTextView[a].setPivotY(0); frameLayout.addView(nameTextView[a], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, a == 0 ? 48 : 0, 0)); onlineTextView[a] = new SimpleTextView(context); onlineTextView[a].setTextColor(AvatarDrawable.getProfileTextColorForId( user_id != 0 || ChatObject.isChannel(chat_id) && !currentChat.megagroup ? 5 : chat_id)); onlineTextView[a].setTextSize(14); onlineTextView[a].setGravity(Gravity.LEFT); frameLayout.addView(onlineTextView[a], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, a == 0 ? 48 : 8, 0)); } if (user_id != 0 || chat_id >= 0 && !ChatObject.isLeftFromChat(currentChat)) { writeButton = new ImageView(context); try { writeButton.setBackgroundResource(R.drawable.floating_user_states); } catch (Throwable e) { FileLog.e("tmessages", e); } writeButton.setScaleType(ImageView.ScaleType.CENTER); if (user_id != 0) { writeButton.setImageResource(R.drawable.floating_message); writeButton.setPadding(0, AndroidUtilities.dp(3), 0, 0); } else if (chat_id != 0) { boolean isChannel = ChatObject.isChannel(currentChat); if (isChannel && !currentChat.creator && (!currentChat.megagroup || !currentChat.editor) || !isChannel && !currentChat.admin && !currentChat.creator && currentChat.admins_enabled) { writeButton.setImageResource(R.drawable.floating_message); writeButton.setPadding(0, AndroidUtilities.dp(3), 0, 0); } else { writeButton.setImageResource(R.drawable.floating_camera); } } frameLayout.addView(writeButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.RIGHT | Gravity.TOP, 0, 0, 16, 0)); if (Build.VERSION.SDK_INT >= 21) { StateListAnimator animator = new StateListAnimator(); animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator .ofFloat(writeButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4)) .setDuration(200)); animator.addState(new int[] {}, ObjectAnimator .ofFloat(writeButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2)) .setDuration(200)); writeButton.setStateListAnimator(animator); writeButton.setOutlineProvider(new ViewOutlineProvider() { @SuppressLint("NewApi") @Override public void getOutline(View view, Outline outline) { outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56)); } }); } writeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (getParentActivity() == null) { return; } if (user_id != 0) { if (playProfileAnimation && parentLayout.fragmentsStack .get(parentLayout.fragmentsStack.size() - 2) instanceof ChatActivity) { finishFragment(); } else { TLRPC.User user = MessagesController.getInstance().getUser(user_id); if (user == null || user instanceof TLRPC.TL_userEmpty) { return; } Bundle args = new Bundle(); args.putInt("user_id", user_id); if (!MessagesController.checkCanOpenChat(args, ProfileActivity.this)) { return; } NotificationCenter.getInstance().removeObserver(ProfileActivity.this, NotificationCenter.closeChats); NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); presentFragment(new ChatActivity(args), true); } } else if (chat_id != 0) { boolean isChannel = ChatObject.isChannel(currentChat); if (isChannel && !currentChat.creator && (!currentChat.megagroup || !currentChat.editor) || !isChannel && !currentChat.admin && !currentChat.creator && currentChat.admins_enabled) { if (playProfileAnimation && parentLayout.fragmentsStack .get(parentLayout.fragmentsStack.size() - 2) instanceof ChatActivity) { finishFragment(); } else { Bundle args = new Bundle(); args.putInt("chat_id", currentChat.id); if (!MessagesController.checkCanOpenChat(args, ProfileActivity.this)) { return; } NotificationCenter.getInstance().removeObserver(ProfileActivity.this, NotificationCenter.closeChats); NotificationCenter.getInstance() .postNotificationName(NotificationCenter.closeChats); presentFragment(new ChatActivity(args), true); } } else { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); CharSequence[] items; TLRPC.Chat chat = MessagesController.getInstance().getChat(chat_id); if (chat.photo == null || chat.photo.photo_big == null || chat.photo instanceof TLRPC.TL_chatPhotoEmpty) { items = new CharSequence[] { LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley) }; } else { items = new CharSequence[] { LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto) }; } builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (i == 0) { avatarUpdater.openCamera(); } else if (i == 1) { avatarUpdater.openGallery(); } else if (i == 2) { MessagesController.getInstance().changeChatAvatar(chat_id, null); } } }); showDialog(builder.create()); } } } }); } needLayout(); listView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { checkListViewScroll(); if (participantsMap != null && loadMoreMembersRow != -1 && layoutManager.findLastVisibleItemPosition() > loadMoreMembersRow - 8) { getChannelParticipants(false); } } }); return fragmentView; }
From source file:org.telegram.ui.Components.ChatActivityEnterView.java
public ChatActivityEnterView(Activity context, SizeNotifierFrameLayout parent, ChatActivity fragment, final boolean isChat) { super(context); dotPaint = new Paint(Paint.ANTI_ALIAS_FLAG); dotPaint.setColor(Theme.getColor(Theme.key_chat_emojiPanelNewTrending)); setFocusable(true);//from w ww .jav a 2 s . c om setFocusableInTouchMode(true); setWillNotDraw(false); NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordStarted); NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordStartError); NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordStopped); NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordProgressChanged); NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeChats); NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidSent); NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded); NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioRouteChanged); NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidReset); NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioProgressDidChanged); NotificationCenter.getInstance().addObserver(this, NotificationCenter.featuredStickersDidLoaded); parentActivity = context; parentFragment = fragment; sizeNotifierLayout = parent; sizeNotifierLayout.setDelegate(this); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); sendByEnter = preferences.getBoolean("send_by_enter", false); textFieldContainer = new LinearLayout(context); textFieldContainer.setOrientation(LinearLayout.HORIZONTAL); addView(textFieldContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, 2, 0, 0)); FrameLayout frameLayout = new FrameLayout(context); textFieldContainer.addView(frameLayout, LayoutHelper.createLinear(0, LayoutHelper.WRAP_CONTENT, 1.0f)); emojiButton = new ImageView(context) { @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (attachLayout != null && (emojiView == null || emojiView.getVisibility() != VISIBLE) && !StickersQuery.getUnreadStickerSets().isEmpty() && dotPaint != null) { int x = canvas.getWidth() / 2 + AndroidUtilities.dp(4 + 5); int y = canvas.getHeight() / 2 - AndroidUtilities.dp(13 - 5); canvas.drawCircle(x, y, AndroidUtilities.dp(5), dotPaint); } } }; emojiButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); emojiButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE); emojiButton.setPadding(0, AndroidUtilities.dp(1), 0, 0); // if (Build.VERSION.SDK_INT >= 21) { // emojiButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR)); // } setEmojiButtonImage(); frameLayout.addView(emojiButton, LayoutHelper.createFrame(48, 48, Gravity.BOTTOM | Gravity.LEFT, 3, 0, 0, 0)); emojiButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (!isPopupShowing() || currentPopupContentType != 0) { showPopup(1, 0); emojiView.onOpen(messageEditText.length() > 0 && !messageEditText.getText().toString().startsWith("@gif")); } else { openKeyboardInternal(); removeGifFromInputField(); } } }); messageEditText = new EditTextCaption(context) { @Override public InputConnection onCreateInputConnection(EditorInfo editorInfo) { final InputConnection ic = super.onCreateInputConnection(editorInfo); EditorInfoCompat.setContentMimeTypes(editorInfo, new String[] { "image/gif", "image/*", "image/jpg", "image/png" }); final InputConnectionCompat.OnCommitContentListener callback = new InputConnectionCompat.OnCommitContentListener() { @Override public boolean onCommitContent(InputContentInfoCompat inputContentInfo, int flags, Bundle opts) { if (BuildCompat.isAtLeastNMR1() && (flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) { try { inputContentInfo.requestPermission(); } catch (Exception e) { return false; } } ClipDescription description = inputContentInfo.getDescription(); if (description.hasMimeType("image/gif")) { SendMessagesHelper.prepareSendingDocument(null, null, inputContentInfo.getContentUri(), "image/gif", dialog_id, replyingMessageObject, inputContentInfo); } else { SendMessagesHelper.prepareSendingPhoto(null, inputContentInfo.getContentUri(), dialog_id, replyingMessageObject, null, null, inputContentInfo); } if (delegate != null) { delegate.onMessageSend(null); } return true; } }; return InputConnectionCompat.createWrapper(ic, editorInfo, callback); } @Override public boolean onTouchEvent(MotionEvent event) { if (isPopupShowing() && event.getAction() == MotionEvent.ACTION_DOWN) { showPopup(AndroidUtilities.usingHardwareInput ? 0 : 2, 0); openKeyboardInternal(); } try { return super.onTouchEvent(event); } catch (Exception e) { FileLog.e(e); } return false; } }; updateFieldHint(); messageEditText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); messageEditText.setInputType(messageEditText.getInputType() | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE); messageEditText.setSingleLine(false); messageEditText.setMaxLines(4); messageEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); messageEditText.setGravity(Gravity.BOTTOM); messageEditText.setPadding(0, AndroidUtilities.dp(11), 0, AndroidUtilities.dp(12)); messageEditText.setBackgroundDrawable(null); messageEditText.setTextColor(Theme.getColor(Theme.key_chat_messagePanelText)); messageEditText.setHintColor(Theme.getColor(Theme.key_chat_messagePanelHint)); messageEditText.setHintTextColor(Theme.getColor(Theme.key_chat_messagePanelHint)); frameLayout.addView(messageEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM, 52, 0, isChat ? 50 : 2, 0)); messageEditText.setOnKeyListener(new OnKeyListener() { boolean ctrlPressed = false; @Override public boolean onKey(View view, int i, KeyEvent keyEvent) { if (i == KeyEvent.KEYCODE_BACK && !keyboardVisible && isPopupShowing()) { if (keyEvent.getAction() == 1) { if (currentPopupContentType == 1 && botButtonsMessageObject != null) { SharedPreferences preferences = ApplicationLoader.applicationContext .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); preferences.edit().putInt("hidekeyboard_" + dialog_id, botButtonsMessageObject.getId()) .commit(); } showPopup(0, 0); removeGifFromInputField(); } return true; } else if (i == KeyEvent.KEYCODE_ENTER && (ctrlPressed || sendByEnter) && keyEvent.getAction() == KeyEvent.ACTION_DOWN && editingMessageObject == null) { sendMessage(); return true; } else if (i == KeyEvent.KEYCODE_CTRL_LEFT || i == KeyEvent.KEYCODE_CTRL_RIGHT) { ctrlPressed = keyEvent.getAction() == KeyEvent.ACTION_DOWN; return true; } return false; } }); messageEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { boolean ctrlPressed = false; @Override public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { if (i == EditorInfo.IME_ACTION_SEND) { sendMessage(); return true; } else if (keyEvent != null && i == EditorInfo.IME_NULL) { if ((ctrlPressed || sendByEnter) && keyEvent.getAction() == KeyEvent.ACTION_DOWN && editingMessageObject == null) { sendMessage(); return true; } else if (i == KeyEvent.KEYCODE_CTRL_LEFT || i == KeyEvent.KEYCODE_CTRL_RIGHT) { ctrlPressed = keyEvent.getAction() == KeyEvent.ACTION_DOWN; return true; } } return false; } }); messageEditText.addTextChangedListener(new TextWatcher() { boolean processChange = false; @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int start, int before, int count) { if (innerTextChange == 1) { return; } checkSendButton(true); CharSequence message = AndroidUtilities.getTrimmedString(charSequence.toString()); if (delegate != null) { if (!ignoreTextChange) { if (count > 2 || charSequence == null || charSequence.length() == 0) { messageWebPageSearch = true; } delegate.onTextChanged(charSequence, before > count + 1 || (count - before) > 2); } } if (innerTextChange != 2 && before != count && (count - before) > 1) { processChange = true; } if (editingMessageObject == null && !canWriteToChannel && message.length() != 0 && lastTypingTimeSend < System.currentTimeMillis() - 5000 && !ignoreTextChange) { int currentTime = ConnectionsManager.getInstance().getCurrentTime(); TLRPC.User currentUser = null; if ((int) dialog_id > 0) { currentUser = MessagesController.getInstance().getUser((int) dialog_id); } if (currentUser != null && (currentUser.id == UserConfig.getClientUserId() || currentUser.status != null && currentUser.status.expires < currentTime && !MessagesController.getInstance().onlinePrivacy .containsKey(currentUser.id))) { return; } lastTypingTimeSend = System.currentTimeMillis(); if (delegate != null) { delegate.needSendTyping(); } } } @Override public void afterTextChanged(Editable editable) { if (innerTextChange != 0) { return; } if (sendByEnter && editable.length() > 0 && editable.charAt(editable.length() - 1) == '\n' && editingMessageObject == null) { sendMessage(); } if (processChange) { ImageSpan[] spans = editable.getSpans(0, editable.length(), ImageSpan.class); for (int i = 0; i < spans.length; i++) { editable.removeSpan(spans[i]); } Emoji.replaceEmoji(editable, messageEditText.getPaint().getFontMetricsInt(), AndroidUtilities.dp(20), false); processChange = false; } } }); if (isChat) { attachLayout = new LinearLayout(context); attachLayout.setOrientation(LinearLayout.HORIZONTAL); attachLayout.setEnabled(false); attachLayout.setPivotX(AndroidUtilities.dp(48)); frameLayout.addView(attachLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 48, Gravity.BOTTOM | Gravity.RIGHT)); botButton = new ImageView(context); botButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); botButton.setImageResource(R.drawable.bot_keyboard2); botButton.setScaleType(ImageView.ScaleType.CENTER); botButton.setVisibility(GONE); // if (Build.VERSION.SDK_INT >= 21) { // botButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR)); // } attachLayout.addView(botButton, LayoutHelper.createLinear(48, 48)); botButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (botReplyMarkup != null) { if (!isPopupShowing() || currentPopupContentType != 1) { showPopup(1, 1); SharedPreferences preferences = ApplicationLoader.applicationContext .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); preferences.edit().remove("hidekeyboard_" + dialog_id).commit(); } else { if (currentPopupContentType == 1 && botButtonsMessageObject != null) { SharedPreferences preferences = ApplicationLoader.applicationContext .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); preferences.edit() .putInt("hidekeyboard_" + dialog_id, botButtonsMessageObject.getId()) .commit(); } openKeyboardInternal(); } } else if (hasBotCommands) { setFieldText("/"); messageEditText.requestFocus(); openKeyboard(); } } }); notifyButton = new ImageView(context); notifyButton.setImageResource(silent ? R.drawable.notify_members_off : R.drawable.notify_members_on); notifyButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); notifyButton.setScaleType(ImageView.ScaleType.CENTER); notifyButton.setVisibility(canWriteToChannel ? VISIBLE : GONE); // if (Build.VERSION.SDK_INT >= 21) { // notifyButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR)); // } attachLayout.addView(notifyButton, LayoutHelper.createLinear(48, 48)); notifyButton.setOnClickListener(new OnClickListener() { private Toast visibleToast; @Override public void onClick(View v) { silent = !silent; notifyButton.setImageResource( silent ? R.drawable.notify_members_off : R.drawable.notify_members_on); ApplicationLoader.applicationContext .getSharedPreferences("Notifications", Activity.MODE_PRIVATE).edit() .putBoolean("silent_" + dialog_id, silent).commit(); NotificationsController.updateServerNotificationsSettings(dialog_id); try { if (visibleToast != null) { visibleToast.cancel(); } } catch (Exception e) { FileLog.e(e); } if (silent) { visibleToast = Toast.makeText(parentActivity, LocaleController .getString("ChannelNotifyMembersInfoOff", R.string.ChannelNotifyMembersInfoOff), Toast.LENGTH_SHORT); } else { visibleToast = Toast.makeText(parentActivity, LocaleController .getString("ChannelNotifyMembersInfoOn", R.string.ChannelNotifyMembersInfoOn), Toast.LENGTH_SHORT); } visibleToast.show(); updateFieldHint(); } }); attachButton = new ImageView(context); attachButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); attachButton.setImageResource(R.drawable.ic_ab_attach); attachButton.setScaleType(ImageView.ScaleType.CENTER); // if (Build.VERSION.SDK_INT >= 21) { // attachButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR)); // } attachLayout.addView(attachButton, LayoutHelper.createLinear(48, 48)); attachButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { delegate.didPressedAttachButton(); } }); } recordedAudioPanel = new FrameLayout(context); recordedAudioPanel.setVisibility(audioToSend == null ? GONE : VISIBLE); recordedAudioPanel.setBackgroundColor(Theme.getColor(Theme.key_chat_messagePanelBackground)); recordedAudioPanel.setFocusable(true); recordedAudioPanel.setFocusableInTouchMode(true); recordedAudioPanel.setClickable(true); frameLayout.addView(recordedAudioPanel, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM)); recordDeleteImageView = new ImageView(context); recordDeleteImageView.setScaleType(ImageView.ScaleType.CENTER); recordDeleteImageView.setImageResource(R.drawable.ic_ab_delete); recordDeleteImageView.setColorFilter(new PorterDuffColorFilter( Theme.getColor(Theme.key_chat_messagePanelVoiceDelete), PorterDuff.Mode.MULTIPLY)); recordedAudioPanel.addView(recordDeleteImageView, LayoutHelper.createFrame(48, 48)); recordDeleteImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MessageObject playing = MediaController.getInstance().getPlayingMessageObject(); if (playing != null && playing == audioToSendMessageObject) { MediaController.getInstance().cleanupPlayer(true, true); } if (audioToSendPath != null) { new File(audioToSendPath).delete(); } hideRecordedAudioPanel(); checkSendButton(true); } }); recordedAudioBackground = new View(context); recordedAudioBackground.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(16), Theme.getColor(Theme.key_chat_recordedVoiceBackground))); recordedAudioPanel.addView(recordedAudioBackground, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 32, Gravity.CENTER_VERTICAL | Gravity.LEFT, 48, 0, 0, 0)); recordedAudioSeekBar = new SeekBarWaveformView(context); recordedAudioPanel.addView(recordedAudioSeekBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 32, Gravity.CENTER_VERTICAL | Gravity.LEFT, 48 + 44, 0, 52, 0)); playDrawable = Theme.createSimpleSelectorDrawable(context, R.drawable.s_play, Theme.getColor(Theme.key_chat_recordedVoicePlayPause), Theme.getColor(Theme.key_chat_recordedVoicePlayPausePressed)); pauseDrawable = Theme.createSimpleSelectorDrawable(context, R.drawable.s_pause, Theme.getColor(Theme.key_chat_recordedVoicePlayPause), Theme.getColor(Theme.key_chat_recordedVoicePlayPausePressed)); recordedAudioPlayButton = new ImageView(context); recordedAudioPlayButton.setImageDrawable(playDrawable); recordedAudioPlayButton.setScaleType(ImageView.ScaleType.CENTER); recordedAudioPanel.addView(recordedAudioPlayButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.BOTTOM, 48, 0, 0, 0)); recordedAudioPlayButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (audioToSend == null) { return; } if (MediaController.getInstance().isPlayingAudio(audioToSendMessageObject) && !MediaController.getInstance().isAudioPaused()) { MediaController.getInstance().pauseAudio(audioToSendMessageObject); recordedAudioPlayButton.setImageDrawable(playDrawable); } else { recordedAudioPlayButton.setImageDrawable(pauseDrawable); MediaController.getInstance().playAudio(audioToSendMessageObject); } } }); recordedAudioTimeTextView = new TextView(context); recordedAudioTimeTextView.setTextColor(Theme.getColor(Theme.key_chat_messagePanelVoiceDuration)); recordedAudioTimeTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); recordedAudioPanel.addView(recordedAudioTimeTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL, 0, 0, 13, 0)); recordPanel = new FrameLayout(context); recordPanel.setVisibility(GONE); recordPanel.setBackgroundColor(Theme.getColor(Theme.key_chat_messagePanelBackground)); frameLayout.addView(recordPanel, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM)); slideText = new LinearLayout(context); slideText.setOrientation(LinearLayout.HORIZONTAL); recordPanel.addView(slideText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 30, 0, 0, 0)); recordCancelImage = new ImageView(context); recordCancelImage.setImageResource(R.drawable.slidearrow); recordCancelImage.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_recordVoiceCancel), PorterDuff.Mode.MULTIPLY)); slideText.addView(recordCancelImage, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 0, 1, 0, 0)); recordCancelText = new TextView(context); recordCancelText.setText(LocaleController.getString("SlideToCancel", R.string.SlideToCancel)); recordCancelText.setTextColor(Theme.getColor(Theme.key_chat_recordVoiceCancel)); recordCancelText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12); slideText.addView(recordCancelText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 6, 0, 0, 0)); recordTimeContainer = new LinearLayout(context); recordTimeContainer.setOrientation(LinearLayout.HORIZONTAL); recordTimeContainer.setPadding(AndroidUtilities.dp(13), 0, 0, 0); recordTimeContainer.setBackgroundColor(Theme.getColor(Theme.key_chat_messagePanelBackground)); recordPanel.addView(recordTimeContainer, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL)); recordDot = new RecordDot(context); recordTimeContainer.addView(recordDot, LayoutHelper.createLinear(11, 11, Gravity.CENTER_VERTICAL, 0, 1, 0, 0)); recordTimeText = new TextView(context); recordTimeText.setText("00:00"); recordTimeText.setTextColor(Theme.getColor(Theme.key_chat_recordTime)); recordTimeText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); recordTimeContainer.addView(recordTimeText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 6, 0, 0, 0)); sendButtonContainer = new FrameLayout(context); textFieldContainer.addView(sendButtonContainer, LayoutHelper.createLinear(48, 48, Gravity.BOTTOM)); audioVideoButtonContainer = new FrameLayout(context); audioVideoButtonContainer.setBackgroundColor(Theme.getColor(Theme.key_chat_messagePanelBackground)); audioVideoButtonContainer.setSoundEffectsEnabled(false); sendButtonContainer.addView(audioVideoButtonContainer, LayoutHelper.createFrame(48, 48)); audioVideoButtonContainer.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { if (hasRecordVideo) { recordAudioVideoRunnableStarted = true; AndroidUtilities.runOnUIThread(recordAudioVideoRunnable, 150); } else { recordAudioVideoRunnable.run(); } } else if (motionEvent.getAction() == MotionEvent.ACTION_UP || motionEvent.getAction() == MotionEvent.ACTION_CANCEL) { if (recordAudioVideoRunnableStarted) { AndroidUtilities.cancelRunOnUIThread(recordAudioVideoRunnable); setRecordVideoButtonVisible(videoSendButton.getTag() == null, true); } else { startedDraggingX = -1; if (hasRecordVideo && videoSendButton.getTag() != null) { delegate.needStartRecordVideo(1); } else { MediaController.getInstance().stopRecording(1); } recordingAudioVideo = false; updateRecordIntefrace(); } } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE && recordingAudioVideo) { float x = motionEvent.getX(); if (x < -distCanMove) { if (hasRecordVideo && videoSendButton.getTag() != null) { delegate.needStartRecordVideo(2); } else { MediaController.getInstance().stopRecording(0); } recordingAudioVideo = false; updateRecordIntefrace(); } x = x + audioVideoButtonContainer.getX(); FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) slideText.getLayoutParams(); if (startedDraggingX != -1) { float dist = (x - startedDraggingX); recordCircle.setTranslationX(dist); params.leftMargin = AndroidUtilities.dp(30) + (int) dist; slideText.setLayoutParams(params); float alpha = 1.0f + dist / distCanMove; if (alpha > 1) { alpha = 1; } else if (alpha < 0) { alpha = 0; } slideText.setAlpha(alpha); } if (x <= slideText.getX() + slideText.getWidth() + AndroidUtilities.dp(30)) { if (startedDraggingX == -1) { startedDraggingX = x; distCanMove = (recordPanel.getMeasuredWidth() - slideText.getMeasuredWidth() - AndroidUtilities.dp(48)) / 2.0f; if (distCanMove <= 0) { distCanMove = AndroidUtilities.dp(80); } else if (distCanMove > AndroidUtilities.dp(80)) { distCanMove = AndroidUtilities.dp(80); } } } if (params.leftMargin > AndroidUtilities.dp(30)) { params.leftMargin = AndroidUtilities.dp(30); recordCircle.setTranslationX(0); slideText.setLayoutParams(params); slideText.setAlpha(1); startedDraggingX = -1; } } view.onTouchEvent(motionEvent); return true; } }); audioSendButton = new ImageView(context); audioSendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE); audioSendButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); audioSendButton.setImageResource(R.drawable.mic); audioSendButton.setPadding(0, 0, AndroidUtilities.dp(4), 0); audioVideoButtonContainer.addView(audioSendButton, LayoutHelper.createFrame(48, 48)); if (hasRecordVideo) { videoSendButton = new ImageView(context); videoSendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE); videoSendButton.setColorFilter(new PorterDuffColorFilter( Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); videoSendButton.setImageResource(R.drawable.ic_msg_panel_video); videoSendButton.setPadding(0, 0, AndroidUtilities.dp(4), 0); audioVideoButtonContainer.addView(videoSendButton, LayoutHelper.createFrame(48, 48)); } recordCircle = new RecordCircle(context); recordCircle.setVisibility(GONE); sizeNotifierLayout.addView(recordCircle, LayoutHelper.createFrame(124, 124, Gravity.BOTTOM | Gravity.RIGHT, 0, 0, -36, -38)); cancelBotButton = new ImageView(context); cancelBotButton.setVisibility(INVISIBLE); cancelBotButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE); cancelBotButton.setImageDrawable(progressDrawable = new CloseProgressDrawable2()); progressDrawable.setColorFilter(new PorterDuffColorFilter( Theme.getColor(Theme.key_chat_messagePanelCancelInlineBot), PorterDuff.Mode.MULTIPLY)); cancelBotButton.setSoundEffectsEnabled(false); cancelBotButton.setScaleX(0.1f); cancelBotButton.setScaleY(0.1f); cancelBotButton.setAlpha(0.0f); sendButtonContainer.addView(cancelBotButton, LayoutHelper.createFrame(48, 48)); cancelBotButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { String text = messageEditText.getText().toString(); int idx = text.indexOf(' '); if (idx == -1 || idx == text.length() - 1) { setFieldText(""); } else { setFieldText(text.substring(0, idx + 1)); } } }); sendButton = new ImageView(context); sendButton.setVisibility(INVISIBLE); sendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE); sendButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelSend), PorterDuff.Mode.MULTIPLY)); sendButton.setImageResource(R.drawable.ic_send); sendButton.setSoundEffectsEnabled(false); sendButton.setScaleX(0.1f); sendButton.setScaleY(0.1f); sendButton.setAlpha(0.0f); sendButtonContainer.addView(sendButton, LayoutHelper.createFrame(48, 48)); sendButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { sendMessage(); } }); doneButtonContainer = new FrameLayout(context); doneButtonContainer.setVisibility(GONE); textFieldContainer.addView(doneButtonContainer, LayoutHelper.createLinear(48, 48, Gravity.BOTTOM)); // if (Build.VERSION.SDK_INT >= 21) { // doneButtonContainer.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR)); // } doneButtonContainer.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { doneEditingMessage(); } }); doneButtonImage = new ImageView(context); doneButtonImage.setScaleType(ImageView.ScaleType.CENTER); doneButtonImage.setImageResource(R.drawable.edit_done); doneButtonImage.setColorFilter( new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_editDoneIcon), PorterDuff.Mode.MULTIPLY)); doneButtonContainer.addView(doneButtonImage, LayoutHelper.createFrame(48, 48)); doneButtonProgress = new ContextProgressView(context, 0); doneButtonProgress.setVisibility(View.INVISIBLE); doneButtonContainer.addView(doneButtonProgress, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); SharedPreferences sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("emoji", Context.MODE_PRIVATE); keyboardHeight = sharedPreferences.getInt("kbd_height", AndroidUtilities.dp(200)); keyboardHeightLand = sharedPreferences.getInt("kbd_height_land3", AndroidUtilities.dp(200)); setRecordVideoButtonVisible(false, false); checkSendButton(false); }
From source file:org.telegram.ui.PassportActivity.java
private void createPhoneVerificationInterface(Context context) { actionBar.setTitle(LocaleController.getString("PassportPhone", R.string.PassportPhone)); FrameLayout frameLayout = new FrameLayout(context); scrollView.addView(frameLayout, LayoutHelper.createScroll(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT)); for (int a = 0; a < 3; a++) { views[a] = new PhoneConfirmationView(context, a + 2); views[a].setVisibility(View.GONE); frameLayout.addView(views[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, AndroidUtilities.isTablet() ? 26 : 18, 30, AndroidUtilities.isTablet() ? 26 : 18, 0)); }/*from ww w .j av a 2 s.com*/ final Bundle params = new Bundle(); params.putString("phone", currentValues.get("phone")); fillNextCodeParams(params, currentPhoneVerification, false); }
From source file:org.telegram.ui.PassportActivity.java
private void createPasswordInterface(Context context) { TLRPC.User botUser = null;/*from www.java 2 s .c o m*/ if (currentForm != null) { for (int a = 0; a < currentForm.users.size(); a++) { TLRPC.User user = currentForm.users.get(a); if (user.id == currentBotId) { botUser = user; break; } } } else { botUser = UserConfig.getInstance(currentAccount).getCurrentUser(); } FrameLayout frameLayout = (FrameLayout) fragmentView; actionBar.setTitle(LocaleController.getString("TelegramPassport", R.string.TelegramPassport)); emptyView = new EmptyTextProgressView(context); emptyView.showProgress(); frameLayout.addView(emptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); passwordAvatarContainer = new FrameLayout(context); linearLayout2.addView(passwordAvatarContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 100)); BackupImageView avatarImageView = new BackupImageView(context); avatarImageView.setRoundRadius(AndroidUtilities.dp(32)); passwordAvatarContainer.addView(avatarImageView, LayoutHelper.createFrame(64, 64, Gravity.CENTER, 0, 8, 0, 0)); AvatarDrawable avatarDrawable = new AvatarDrawable(botUser); TLRPC.FileLocation photo = null; if (botUser.photo != null) { photo = botUser.photo.photo_small; } avatarImageView.setImage(photo, "50_50", avatarDrawable, botUser); passwordRequestTextView = new TextInfoPrivacyCell(context); passwordRequestTextView.getTextView().setGravity(Gravity.CENTER_HORIZONTAL); if (currentBotId == 0) { passwordRequestTextView .setText(LocaleController.getString("PassportSelfRequest", R.string.PassportSelfRequest)); } else { passwordRequestTextView.setText(AndroidUtilities.replaceTags(LocaleController .formatString("PassportRequest", R.string.PassportRequest, UserObject.getFirstName(botUser)))); } ((FrameLayout.LayoutParams) passwordRequestTextView.getTextView() .getLayoutParams()).gravity = Gravity.CENTER_HORIZONTAL; linearLayout2.addView(passwordRequestTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 21, 0, 21, 0)); noPasswordImageView = new ImageView(context); noPasswordImageView.setImageResource(R.drawable.no_password); noPasswordImageView.setColorFilter(new PorterDuffColorFilter( Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); linearLayout2.addView(noPasswordImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 13, 0, 0)); noPasswordTextView = new TextView(context); noPasswordTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); noPasswordTextView.setGravity(Gravity.CENTER_HORIZONTAL); noPasswordTextView.setPadding(AndroidUtilities.dp(21), AndroidUtilities.dp(10), AndroidUtilities.dp(21), AndroidUtilities.dp(17)); noPasswordTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4)); noPasswordTextView.setText(LocaleController.getString("TelegramPassportCreatePasswordInfo", R.string.TelegramPassportCreatePasswordInfo)); linearLayout2.addView(noPasswordTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 21, 10, 21, 0)); noPasswordSetTextView = new TextView(context); noPasswordSetTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueText5)); noPasswordSetTextView.setGravity(Gravity.CENTER); noPasswordSetTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); noPasswordSetTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); noPasswordSetTextView.setText(LocaleController.getString("TelegramPassportCreatePassword", R.string.TelegramPassportCreatePassword)); linearLayout2.addView(noPasswordSetTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 24, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 21, 9, 21, 0)); noPasswordSetTextView.setOnClickListener(v -> { TwoStepVerificationActivity activity = new TwoStepVerificationActivity(currentAccount, 1); activity.setCloseAfterSet(true); activity.setCurrentPasswordInfo(new byte[0], currentPassword); presentFragment(activity); }); inputFields = new EditTextBoldCursor[1]; inputFieldContainers = new ViewGroup[1]; for (int a = 0; a < 1; a++) { inputFieldContainers[a] = new FrameLayout(context); linearLayout2.addView(inputFieldContainers[a], LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 50)); inputFieldContainers[a].setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); inputFields[a] = new EditTextBoldCursor(context); inputFields[a].setTag(a); inputFields[a].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); inputFields[a].setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText)); inputFields[a].setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); inputFields[a].setBackgroundDrawable(null); inputFields[a].setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); inputFields[a].setCursorSize(AndroidUtilities.dp(20)); inputFields[a].setCursorWidth(1.5f); inputFields[a].setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); inputFields[a].setMaxLines(1); inputFields[a].setLines(1); inputFields[a].setSingleLine(true); inputFields[a].setTransformationMethod(PasswordTransformationMethod.getInstance()); inputFields[a].setTypeface(Typeface.DEFAULT); inputFields[a].setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI); inputFields[a].setPadding(0, 0, 0, AndroidUtilities.dp(6)); inputFields[a].setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); inputFieldContainers[a].addView(inputFields[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 21, 12, 21, 6)); inputFields[a].setOnEditorActionListener((textView, i, keyEvent) -> { if (i == EditorInfo.IME_ACTION_NEXT || i == EditorInfo.IME_ACTION_DONE) { doneItem.callOnClick(); return true; } return false; }); inputFields[a].setCustomSelectionActionModeCallback(new ActionMode.Callback() { public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } public void onDestroyActionMode(ActionMode mode) { } public boolean onCreateActionMode(ActionMode mode, Menu menu) { return false; } public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return false; } }); } passwordInfoRequestTextView = new TextInfoPrivacyCell(context); passwordInfoRequestTextView.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow)); passwordInfoRequestTextView.setText( LocaleController.formatString("PassportRequestPasswordInfo", R.string.PassportRequestPasswordInfo)); linearLayout2.addView(passwordInfoRequestTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); passwordForgotButton = new TextView(context); passwordForgotButton.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueText4)); passwordForgotButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); passwordForgotButton.setText(LocaleController.getString("ForgotPassword", R.string.ForgotPassword)); passwordForgotButton.setPadding(0, 0, 0, 0); linearLayout2.addView(passwordForgotButton, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 30, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 21, 0, 21, 0)); passwordForgotButton.setOnClickListener(v -> { if (currentPassword.has_recovery) { needShowProgress(); TLRPC.TL_auth_requestPasswordRecovery req = new TLRPC.TL_auth_requestPasswordRecovery(); int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { needHideProgress(); if (error == null) { final TLRPC.TL_auth_passwordRecovery res = (TLRPC.TL_auth_passwordRecovery) response; AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setMessage(LocaleController.formatString("RestoreEmailSent", R.string.RestoreEmailSent, res.email_pattern)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialogInterface, i) -> { TwoStepVerificationActivity fragment = new TwoStepVerificationActivity( currentAccount, 1); fragment.setRecoveryParams(currentPassword); currentPassword.email_unconfirmed_pattern = res.email_pattern; presentFragment(fragment); }); Dialog dialog = showDialog(builder.create()); if (dialog != null) { dialog.setCanceledOnTouchOutside(false); dialog.setCancelable(false); } } else { if (error.text.startsWith("FLOOD_WAIT")) { int time = Utilities.parseInt(error.text); String timeString; if (time < 60) { timeString = LocaleController.formatPluralString("Seconds", time); } else { timeString = LocaleController.formatPluralString("Minutes", time / 60); } showAlertWithText(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString)); } else { showAlertWithText(LocaleController.getString("AppName", R.string.AppName), error.text); } } }), ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin); ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid); } else { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); builder.setNegativeButton( LocaleController.getString("RestorePasswordResetAccount", R.string.RestorePasswordResetAccount), (dialog, which) -> Browser.openUrl(getParentActivity(), "https://telegram.org/deactivate?phone=" + UserConfig.getInstance(currentAccount).getClientPhone())); builder.setTitle(LocaleController.getString("RestorePasswordNoEmailTitle", R.string.RestorePasswordNoEmailTitle)); builder.setMessage(LocaleController.getString("RestorePasswordNoEmailText", R.string.RestorePasswordNoEmailText)); showDialog(builder.create()); } }); updatePasswordInterface(); }
From source file:org.telegram.ui.PassportActivity.java
private void createRequestInterface(Context context) { TLRPC.User botUser = null;// ww w .java 2 s .c o m if (currentForm != null) { for (int a = 0; a < currentForm.users.size(); a++) { TLRPC.User user = currentForm.users.get(a); if (user.id == currentBotId) { botUser = user; break; } } } FrameLayout frameLayout = (FrameLayout) fragmentView; actionBar.setTitle(LocaleController.getString("TelegramPassport", R.string.TelegramPassport)); actionBar.createMenu().addItem(info_item, R.drawable.profile_info); if (botUser != null) { FrameLayout avatarContainer = new FrameLayout(context); linearLayout2.addView(avatarContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 100)); BackupImageView avatarImageView = new BackupImageView(context); avatarImageView.setRoundRadius(AndroidUtilities.dp(32)); avatarContainer.addView(avatarImageView, LayoutHelper.createFrame(64, 64, Gravity.CENTER, 0, 8, 0, 0)); AvatarDrawable avatarDrawable = new AvatarDrawable(botUser); TLRPC.FileLocation photo = null; if (botUser.photo != null) { photo = botUser.photo.photo_small; } avatarImageView.setImage(photo, "50_50", avatarDrawable, botUser); bottomCell = new TextInfoPrivacyCell(context); bottomCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_top, Theme.key_windowBackgroundGrayShadow)); bottomCell.setText(AndroidUtilities.replaceTags(LocaleController.formatString("PassportRequest", R.string.PassportRequest, UserObject.getFirstName(botUser)))); bottomCell.getTextView().setGravity(Gravity.CENTER_HORIZONTAL); ((FrameLayout.LayoutParams) bottomCell.getTextView() .getLayoutParams()).gravity = Gravity.CENTER_HORIZONTAL; linearLayout2.addView(bottomCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); } headerCell = new HeaderCell(context); headerCell.setText( LocaleController.getString("PassportRequestedInformation", R.string.PassportRequestedInformation)); headerCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); linearLayout2.addView(headerCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); if (currentForm != null) { int size = currentForm.required_types.size(); ArrayList<TLRPC.TL_secureRequiredType> personalDocuments = new ArrayList<>(); ArrayList<TLRPC.TL_secureRequiredType> addressDocuments = new ArrayList<>(); int personalCount = 0; int addressCount = 0; boolean hasPersonalInfo = false; boolean hasAddressInfo = false; for (int a = 0; a < size; a++) { TLRPC.SecureRequiredType secureRequiredType = currentForm.required_types.get(a); if (secureRequiredType instanceof TLRPC.TL_secureRequiredType) { TLRPC.TL_secureRequiredType requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType; if (isPersonalDocument(requiredType.type)) { personalDocuments.add(requiredType); personalCount++; } else if (isAddressDocument(requiredType.type)) { addressDocuments.add(requiredType); addressCount++; } else if (requiredType.type instanceof TLRPC.TL_secureValueTypePersonalDetails) { hasPersonalInfo = true; } else if (requiredType.type instanceof TLRPC.TL_secureValueTypeAddress) { hasAddressInfo = true; } } else if (secureRequiredType instanceof TLRPC.TL_secureRequiredTypeOneOf) { TLRPC.TL_secureRequiredTypeOneOf requiredTypeOneOf = (TLRPC.TL_secureRequiredTypeOneOf) secureRequiredType; if (requiredTypeOneOf.types.isEmpty()) { continue; } TLRPC.SecureRequiredType innerType = requiredTypeOneOf.types.get(0); if (!(innerType instanceof TLRPC.TL_secureRequiredType)) { continue; } TLRPC.TL_secureRequiredType requiredType = (TLRPC.TL_secureRequiredType) innerType; if (isPersonalDocument(requiredType.type)) { for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) { innerType = requiredTypeOneOf.types.get(b); if (!(innerType instanceof TLRPC.TL_secureRequiredType)) { continue; } personalDocuments.add((TLRPC.TL_secureRequiredType) innerType); } personalCount++; } else if (isAddressDocument(requiredType.type)) { for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) { innerType = requiredTypeOneOf.types.get(b); if (!(innerType instanceof TLRPC.TL_secureRequiredType)) { continue; } addressDocuments.add((TLRPC.TL_secureRequiredType) innerType); } addressCount++; } } } boolean separatePersonal = !hasPersonalInfo || personalCount > 1; boolean separateAddress = !hasAddressInfo || addressCount > 1; for (int a = 0; a < size; a++) { TLRPC.SecureRequiredType secureRequiredType = currentForm.required_types.get(a); ArrayList<TLRPC.TL_secureRequiredType> documentTypes; TLRPC.TL_secureRequiredType requiredType; boolean documentOnly; if (secureRequiredType instanceof TLRPC.TL_secureRequiredType) { requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType; if (requiredType.type instanceof TLRPC.TL_secureValueTypePhone || requiredType.type instanceof TLRPC.TL_secureValueTypeEmail) { documentTypes = null; documentOnly = false; } else if (requiredType.type instanceof TLRPC.TL_secureValueTypePersonalDetails) { if (separatePersonal) { documentTypes = null; } else { documentTypes = personalDocuments; } documentOnly = false; } else if (requiredType.type instanceof TLRPC.TL_secureValueTypeAddress) { if (separateAddress) { documentTypes = null; } else { documentTypes = addressDocuments; } documentOnly = false; } else if (separatePersonal && isPersonalDocument(requiredType.type)) { documentTypes = new ArrayList<>(); documentTypes.add(requiredType); requiredType = new TLRPC.TL_secureRequiredType(); requiredType.type = new TLRPC.TL_secureValueTypePersonalDetails(); documentOnly = true; } else if (separateAddress && isAddressDocument(requiredType.type)) { documentTypes = new ArrayList<>(); documentTypes.add(requiredType); requiredType = new TLRPC.TL_secureRequiredType(); requiredType.type = new TLRPC.TL_secureValueTypeAddress(); documentOnly = true; } else { continue; } } else if (secureRequiredType instanceof TLRPC.TL_secureRequiredTypeOneOf) { TLRPC.TL_secureRequiredTypeOneOf requiredTypeOneOf = (TLRPC.TL_secureRequiredTypeOneOf) secureRequiredType; if (requiredTypeOneOf.types.isEmpty()) { continue; } TLRPC.SecureRequiredType innerType = requiredTypeOneOf.types.get(0); if (!(innerType instanceof TLRPC.TL_secureRequiredType)) { continue; } requiredType = (TLRPC.TL_secureRequiredType) innerType; if (separatePersonal && isPersonalDocument(requiredType.type) || separateAddress && isAddressDocument(requiredType.type)) { documentTypes = new ArrayList<>(); for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) { innerType = requiredTypeOneOf.types.get(b); if (!(innerType instanceof TLRPC.TL_secureRequiredType)) { continue; } documentTypes.add((TLRPC.TL_secureRequiredType) innerType); } if (isPersonalDocument(requiredType.type)) { requiredType = new TLRPC.TL_secureRequiredType(); requiredType.type = new TLRPC.TL_secureValueTypePersonalDetails(); } else { requiredType = new TLRPC.TL_secureRequiredType(); requiredType.type = new TLRPC.TL_secureValueTypeAddress(); } documentOnly = true; } else { continue; } } else { continue; } addField(context, requiredType, documentTypes, documentOnly, a == size - 1); } } if (botUser != null) { bottomCell = new TextInfoPrivacyCell(context); bottomCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow)); bottomCell.setLinkTextColorKey(Theme.key_windowBackgroundWhiteGrayText4); if (!TextUtils.isEmpty(currentForm.privacy_policy_url)) { String str2 = LocaleController.formatString("PassportPolicy", R.string.PassportPolicy, UserObject.getFirstName(botUser), botUser.username); SpannableStringBuilder text = new SpannableStringBuilder(str2); int index1 = str2.indexOf('*'); int index2 = str2.lastIndexOf('*'); if (index1 != -1 && index2 != -1) { bottomCell.getTextView().setMovementMethod(new AndroidUtilities.LinkMovementMethodMy()); text.replace(index2, index2 + 1, ""); text.replace(index1, index1 + 1, ""); text.setSpan(new LinkSpan(), index1, index2 - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } bottomCell.setText(text); } else { bottomCell.setText(AndroidUtilities.replaceTags(LocaleController.formatString("PassportNoPolicy", R.string.PassportNoPolicy, UserObject.getFirstName(botUser), botUser.username))); } bottomCell.getTextView().setHighlightColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4)); bottomCell.getTextView().setGravity(Gravity.CENTER_HORIZONTAL); linearLayout2.addView(bottomCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); } bottomLayout = new FrameLayout(context); bottomLayout.setBackgroundDrawable( Theme.createSelectorWithBackgroundDrawable(Theme.getColor(Theme.key_passport_authorizeBackground), Theme.getColor(Theme.key_passport_authorizeBackgroundSelected))); frameLayout.addView(bottomLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM)); bottomLayout.setOnClickListener(view -> { class ValueToSend { TLRPC.TL_secureValue value; boolean selfie_required; boolean translation_required; public ValueToSend(TLRPC.TL_secureValue v, boolean s, boolean t) { value = v; selfie_required = s; translation_required = t; } } ArrayList<ValueToSend> valuesToSend = new ArrayList<>(); for (int a = 0, size = currentForm.required_types.size(); a < size; a++) { TLRPC.TL_secureRequiredType requiredType; TLRPC.SecureRequiredType secureRequiredType = currentForm.required_types.get(a); if (secureRequiredType instanceof TLRPC.TL_secureRequiredType) { requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType; } else if (secureRequiredType instanceof TLRPC.TL_secureRequiredTypeOneOf) { TLRPC.TL_secureRequiredTypeOneOf requiredTypeOneOf = (TLRPC.TL_secureRequiredTypeOneOf) secureRequiredType; if (requiredTypeOneOf.types.isEmpty()) { continue; } secureRequiredType = requiredTypeOneOf.types.get(0); if (!(secureRequiredType instanceof TLRPC.TL_secureRequiredType)) { continue; } requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType; for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) { secureRequiredType = requiredTypeOneOf.types.get(b); if (!(secureRequiredType instanceof TLRPC.TL_secureRequiredType)) { continue; } TLRPC.TL_secureRequiredType innerType = (TLRPC.TL_secureRequiredType) secureRequiredType; if (getValueByType(innerType, true) != null) { requiredType = innerType; break; } } } else { continue; } TLRPC.TL_secureValue value = getValueByType(requiredType, true); if (value == null) { Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE); if (v != null) { v.vibrate(200); } AndroidUtilities.shakeView(getViewByType(requiredType), 2, 0); return; } String key = getNameForType(requiredType.type); HashMap<String, String> errors = errorsMap.get(key); if (errors != null && !errors.isEmpty()) { Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE); if (v != null) { v.vibrate(200); } AndroidUtilities.shakeView(getViewByType(requiredType), 2, 0); return; } valuesToSend.add( new ValueToSend(value, requiredType.selfie_required, requiredType.translation_required)); } showEditDoneProgress(false, true); TLRPC.TL_account_acceptAuthorization req = new TLRPC.TL_account_acceptAuthorization(); req.bot_id = currentBotId; req.scope = currentScope; req.public_key = currentPublicKey; JSONObject jsonObject = new JSONObject(); for (int a = 0, size = valuesToSend.size(); a < size; a++) { ValueToSend valueToSend = valuesToSend.get(a); TLRPC.TL_secureValue secureValue = valueToSend.value; JSONObject data = new JSONObject(); if (secureValue.plain_data != null) { if (secureValue.plain_data instanceof TLRPC.TL_securePlainEmail) { TLRPC.TL_securePlainEmail securePlainEmail = (TLRPC.TL_securePlainEmail) secureValue.plain_data; } else if (secureValue.plain_data instanceof TLRPC.TL_securePlainPhone) { TLRPC.TL_securePlainPhone securePlainPhone = (TLRPC.TL_securePlainPhone) secureValue.plain_data; } } else { try { JSONObject result = new JSONObject(); if (secureValue.data != null) { byte[] decryptedSecret = decryptValueSecret(secureValue.data.secret, secureValue.data.data_hash); data.put("data_hash", Base64.encodeToString(secureValue.data.data_hash, Base64.NO_WRAP)); data.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP)); result.put("data", data); } if (!secureValue.files.isEmpty()) { JSONArray files = new JSONArray(); for (int b = 0, size2 = secureValue.files.size(); b < size2; b++) { TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.files.get(b); byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash); JSONObject file = new JSONObject(); file.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP)); file.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP)); files.put(file); } result.put("files", files); } if (secureValue.front_side instanceof TLRPC.TL_secureFile) { TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.front_side; byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash); JSONObject front = new JSONObject(); front.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP)); front.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP)); result.put("front_side", front); } if (secureValue.reverse_side instanceof TLRPC.TL_secureFile) { TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.reverse_side; byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash); JSONObject reverse = new JSONObject(); reverse.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP)); reverse.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP)); result.put("reverse_side", reverse); } if (valueToSend.selfie_required && secureValue.selfie instanceof TLRPC.TL_secureFile) { TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.selfie; byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash); JSONObject selfie = new JSONObject(); selfie.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP)); selfie.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP)); result.put("selfie", selfie); } if (valueToSend.translation_required && !secureValue.translation.isEmpty()) { JSONArray translation = new JSONArray(); for (int b = 0, size2 = secureValue.translation.size(); b < size2; b++) { TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.translation .get(b); byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash); JSONObject file = new JSONObject(); file.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP)); file.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP)); translation.put(file); } result.put("translation", translation); } jsonObject.put(getNameForType(secureValue.type), result); } catch (Exception ignore) { } } TLRPC.TL_secureValueHash hash = new TLRPC.TL_secureValueHash(); hash.type = secureValue.type; hash.hash = secureValue.hash; req.value_hashes.add(hash); } JSONObject result = new JSONObject(); try { result.put("secure_data", jsonObject); } catch (Exception ignore) { } if (currentPayload != null) { try { result.put("payload", currentPayload); } catch (Exception ignore) { } } if (currentNonce != null) { try { result.put("nonce", currentNonce); } catch (Exception ignore) { } } String json = result.toString(); EncryptionResult encryptionResult = encryptData(AndroidUtilities.getStringBytes(json)); req.credentials = new TLRPC.TL_secureCredentialsEncrypted(); req.credentials.hash = encryptionResult.fileHash; req.credentials.data = encryptionResult.encryptedData; try { String key = currentPublicKey.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "") .replace("-----END PUBLIC KEY-----", ""); KeyFactory kf = KeyFactory.getInstance("RSA"); X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(Base64.decode(key, Base64.DEFAULT)); RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(keySpecX509); Cipher c = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC"); c.init(Cipher.ENCRYPT_MODE, pubKey); req.credentials.secret = c.doFinal(encryptionResult.decrypyedFileSecret); } catch (Exception e) { FileLog.e(e); } int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (error == null) { ignoreOnFailure = true; callCallback(true); finishFragment(); } else { showEditDoneProgress(false, false); if ("APP_VERSION_OUTDATED".equals(error.text)) { AlertsCreator.showUpdateAppAlert(getParentActivity(), LocaleController.getString("UpdateAppAlert", R.string.UpdateAppAlert), true); } else { showAlertWithText(LocaleController.getString("AppName", R.string.AppName), error.text); } } })); ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid); }); acceptTextView = new TextView(context); acceptTextView.setCompoundDrawablePadding(AndroidUtilities.dp(8)); acceptTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.authorize, 0, 0, 0); acceptTextView.setTextColor(Theme.getColor(Theme.key_passport_authorizeText)); acceptTextView.setText(LocaleController.getString("PassportAuthorize", R.string.PassportAuthorize)); acceptTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); acceptTextView.setGravity(Gravity.CENTER); acceptTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); bottomLayout.addView(acceptTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER)); progressViewButton = new ContextProgressView(context, 0); progressViewButton.setVisibility(View.INVISIBLE); bottomLayout.addView(progressViewButton, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); View shadow = new View(context); shadow.setBackgroundResource(R.drawable.header_shadow_reverse); frameLayout.addView(shadow, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 48)); }
From source file:org.telegram.ui.PassportActivity.java
private void createDocumentDeleteAlert() { final boolean checks[] = new boolean[] { true }; AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialog, which) -> { if (!documentOnly) { currentValues.clear();//from w w w. j a v a 2 s . c o m } currentDocumentValues.clear(); delegate.deleteValue(currentType, currentDocumentsType, availableDocumentTypes, checks[0], null, null); finishFragment(); }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); if (documentOnly && currentDocumentsType == null && currentType.type instanceof TLRPC.TL_secureValueTypeAddress) { builder.setMessage( LocaleController.getString("PassportDeleteAddressAlert", R.string.PassportDeleteAddressAlert)); } else if (documentOnly && currentDocumentsType == null && currentType.type instanceof TLRPC.TL_secureValueTypePersonalDetails) { builder.setMessage(LocaleController.getString("PassportDeletePersonalAlert", R.string.PassportDeletePersonalAlert)); } else { builder.setMessage(LocaleController.getString("PassportDeleteDocumentAlert", R.string.PassportDeleteDocumentAlert)); } if (!documentOnly && currentDocumentsType != null) { FrameLayout frameLayout = new FrameLayout(getParentActivity()); CheckBoxCell cell = new CheckBoxCell(getParentActivity(), 1); cell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); if (currentType.type instanceof TLRPC.TL_secureValueTypeAddress) { cell.setText(LocaleController.getString("PassportDeleteDocumentAddress", R.string.PassportDeleteDocumentAddress), "", true, false); } else if (currentType.type instanceof TLRPC.TL_secureValueTypePersonalDetails) { cell.setText(LocaleController.getString("PassportDeleteDocumentPersonal", R.string.PassportDeleteDocumentPersonal), "", true, false); } cell.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(16) : AndroidUtilities.dp(8), 0, LocaleController.isRTL ? AndroidUtilities.dp(8) : AndroidUtilities.dp(16), 0); frameLayout.addView(cell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.TOP | Gravity.LEFT)); cell.setOnClickListener(v -> { if (!v.isEnabled()) { return; } CheckBoxCell cell1 = (CheckBoxCell) v; checks[0] = !checks[0]; cell1.setChecked(checks[0], true); }); builder.setView(frameLayout); } showDialog(builder.create()); }
From source file:org.telegram.ui.PassportActivity.java
@Override public View createView(Context context) { actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setAllowOverlayTitle(true); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { private boolean onIdentityDone(Runnable finishRunnable, ErrorRunnable errorRunnable) { if (!uploadingDocuments.isEmpty() || checkFieldsForError()) { return false; }/* w w w. j av a2 s . c om*/ if (allowNonLatinName) { allowNonLatinName = false; boolean error = false; for (int a = 0; a < nonLatinNames.length; a++) { if (nonLatinNames[a]) { inputFields[a].setErrorText(LocaleController.getString("PassportUseLatinOnly", R.string.PassportUseLatinOnly)); if (!error) { error = true; String firstName = nonLatinNames[0] ? getTranslitString( inputExtraFields[FIELD_NATIVE_NAME].getText().toString()) : inputFields[FIELD_NAME].getText().toString(); String middleName = nonLatinNames[1] ? getTranslitString( inputExtraFields[FIELD_NATIVE_MIDNAME].getText().toString()) : inputFields[FIELD_MIDNAME].getText().toString(); String lastName = nonLatinNames[2] ? getTranslitString( inputExtraFields[FIELD_NATIVE_SURNAME].getText().toString()) : inputFields[FIELD_SURNAME].getText().toString(); if (!TextUtils.isEmpty(firstName) && !TextUtils.isEmpty(middleName) && !TextUtils.isEmpty(lastName)) { int num = a; AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setMessage(LocaleController.formatString("PassportNameCheckAlert", R.string.PassportNameCheckAlert, firstName, middleName, lastName)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("Done", R.string.Done), (dialogInterface, i) -> { inputFields[FIELD_NAME].setText(firstName); inputFields[FIELD_MIDNAME].setText(middleName); inputFields[FIELD_SURNAME].setText(lastName); showEditDoneProgress(true, true); onIdentityDone(finishRunnable, errorRunnable); }); builder.setNegativeButton(LocaleController.getString("Edit", R.string.Edit), (dialogInterface, i) -> onFieldError(inputFields[num])); showDialog(builder.create()); } else { onFieldError(inputFields[a]); } } } } if (error) { return false; } } if (isHasNotAnyChanges()) { finishFragment(); return false; } JSONObject json = null; JSONObject documentsJson = null; try { if (!documentOnly) { HashMap<String, String> valuesToSave = new HashMap<>(currentValues); if (currentType.native_names) { if (nativeInfoCell.getVisibility() == View.VISIBLE) { valuesToSave.put("first_name_native", inputExtraFields[FIELD_NATIVE_NAME].getText().toString()); valuesToSave.put("middle_name_native", inputExtraFields[FIELD_NATIVE_MIDNAME].getText().toString()); valuesToSave.put("last_name_native", inputExtraFields[FIELD_NATIVE_SURNAME].getText().toString()); } else { valuesToSave.put("first_name_native", inputFields[FIELD_NATIVE_NAME].getText().toString()); valuesToSave.put("middle_name_native", inputFields[FIELD_NATIVE_MIDNAME].getText().toString()); valuesToSave.put("last_name_native", inputFields[FIELD_NATIVE_SURNAME].getText().toString()); } } valuesToSave.put("first_name", inputFields[FIELD_NAME].getText().toString()); valuesToSave.put("middle_name", inputFields[FIELD_MIDNAME].getText().toString()); valuesToSave.put("last_name", inputFields[FIELD_SURNAME].getText().toString()); valuesToSave.put("birth_date", inputFields[FIELD_BIRTHDAY].getText().toString()); valuesToSave.put("gender", currentGender); valuesToSave.put("country_code", currentCitizeship); valuesToSave.put("residence_country_code", currentResidence); json = new JSONObject(); ArrayList<String> keys = new ArrayList<>(valuesToSave.keySet()); Collections.sort(keys, (key1, key2) -> { int val1 = getFieldCost(key1); int val2 = getFieldCost(key2); if (val1 < val2) { return -1; } else if (val1 > val2) { return 1; } return 0; }); for (int a = 0, size = keys.size(); a < size; a++) { String key = keys.get(a); json.put(key, valuesToSave.get(key)); } } if (currentDocumentsType != null) { HashMap<String, String> valuesToSave = new HashMap<>(currentDocumentValues); valuesToSave.put("document_no", inputFields[FIELD_CARDNUMBER].getText().toString()); if (currentExpireDate[0] != 0) { valuesToSave.put("expiry_date", String.format(Locale.US, "%02d.%02d.%d", currentExpireDate[2], currentExpireDate[1], currentExpireDate[0])); } else { valuesToSave.put("expiry_date", ""); } documentsJson = new JSONObject(); ArrayList<String> keys = new ArrayList<>(valuesToSave.keySet()); Collections.sort(keys, (key1, key2) -> { int val1 = getFieldCost(key1); int val2 = getFieldCost(key2); if (val1 < val2) { return -1; } else if (val1 > val2) { return 1; } return 0; }); for (int a = 0, size = keys.size(); a < size; a++) { String key = keys.get(a); documentsJson.put(key, valuesToSave.get(key)); } } } catch (Exception ignore) { } if (fieldsErrors != null) { fieldsErrors.clear(); } if (documentsErrors != null) { documentsErrors.clear(); } delegate.saveValue(currentType, null, json != null ? json.toString() : null, currentDocumentsType, documentsJson != null ? documentsJson.toString() : null, null, selfieDocument, translationDocuments, frontDocument, reverseLayout != null && reverseLayout.getVisibility() == View.VISIBLE ? reverseDocument : null, finishRunnable, errorRunnable); return true; } @Override public void onItemClick(int id) { if (id == -1) { if (checkDiscard()) { return; } if (currentActivityType == TYPE_REQUEST || currentActivityType == TYPE_PASSWORD) { callCallback(false); } finishFragment(); } else if (id == info_item) { if (getParentActivity() == null) { return; } final TextView message = new TextView(getParentActivity()); String str2 = LocaleController.getString("PassportInfo2", R.string.PassportInfo2); SpannableStringBuilder spanned = new SpannableStringBuilder(str2); int index1 = str2.indexOf('*'); int index2 = str2.lastIndexOf('*'); if (index1 != -1 && index2 != -1) { spanned.replace(index2, index2 + 1, ""); spanned.replace(index1, index1 + 1, ""); spanned.setSpan(new URLSpanNoUnderline( LocaleController.getString("PassportInfoUrl", R.string.PassportInfoUrl)) { @Override public void onClick(View widget) { dismissCurrentDialig(); super.onClick(widget); } }, index1, index2 - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } message.setText(spanned); message.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); message.setLinkTextColor(Theme.getColor(Theme.key_dialogTextLink)); message.setHighlightColor(Theme.getColor(Theme.key_dialogLinkSelection)); message.setPadding(AndroidUtilities.dp(23), 0, AndroidUtilities.dp(23), 0); message.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy()); message.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setView(message); builder.setTitle(LocaleController.getString("PassportInfoTitle", R.string.PassportInfoTitle)); builder.setNegativeButton(LocaleController.getString("Close", R.string.Close), null); showDialog(builder.create()); } else if (id == done_button) { if (currentActivityType == TYPE_PASSWORD) { onPasswordDone(false); return; } if (currentActivityType == TYPE_PHONE_VERIFICATION) { views[currentViewNum].onNextPressed(); } else { final Runnable finishRunnable = () -> finishFragment(); final ErrorRunnable errorRunnable = new ErrorRunnable() { @Override public void onError(String error, String text) { if ("PHONE_VERIFICATION_NEEDED".equals(error)) { startPhoneVerification(true, text, finishRunnable, this, delegate); } else { showEditDoneProgress(true, false); } } }; if (currentActivityType == TYPE_EMAIL) { String value; if (useCurrentValue) { value = currentEmail; } else { if (checkFieldsForError()) { return; } value = inputFields[FIELD_EMAIL].getText().toString(); } delegate.saveValue(currentType, value, null, null, null, null, null, null, null, null, finishRunnable, errorRunnable); } else if (currentActivityType == TYPE_PHONE) { String value; if (useCurrentValue) { value = UserConfig.getInstance(currentAccount).getCurrentUser().phone; } else { if (checkFieldsForError()) { return; } value = inputFields[FIELD_PHONECODE].getText().toString() + inputFields[FIELD_PHONE].getText().toString(); } delegate.saveValue(currentType, value, null, null, null, null, null, null, null, null, finishRunnable, errorRunnable); } else if (currentActivityType == TYPE_ADDRESS) { if (!uploadingDocuments.isEmpty() || checkFieldsForError()) { return; } if (isHasNotAnyChanges()) { finishFragment(); return; } JSONObject json = null; try { if (!documentOnly) { json = new JSONObject(); json.put("street_line1", inputFields[FIELD_STREET1].getText().toString()); json.put("street_line2", inputFields[FIELD_STREET2].getText().toString()); json.put("post_code", inputFields[FIELD_POSTCODE].getText().toString()); json.put("city", inputFields[FIELD_CITY].getText().toString()); json.put("state", inputFields[FIELD_STATE].getText().toString()); json.put("country_code", currentCitizeship); } } catch (Exception ignore) { } if (fieldsErrors != null) { fieldsErrors.clear(); } if (documentsErrors != null) { documentsErrors.clear(); } delegate.saveValue(currentType, null, json != null ? json.toString() : null, currentDocumentsType, null, documents, selfieDocument, translationDocuments, null, null, finishRunnable, errorRunnable); } else if (currentActivityType == TYPE_IDENTITY) { if (!onIdentityDone(finishRunnable, errorRunnable)) { return; } } else if (currentActivityType == TYPE_EMAIL_VERIFICATION) { final TLRPC.TL_account_verifyEmail req = new TLRPC.TL_account_verifyEmail(); req.email = currentValues.get("email"); req.code = inputFields[FIELD_EMAIL].getText().toString(); int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (error == null) { delegate.saveValue(currentType, currentValues.get("email"), null, null, null, null, null, null, null, null, finishRunnable, errorRunnable); } else { AlertsCreator.processError(currentAccount, error, PassportActivity.this, req); errorRunnable.onError(null, null); } })); ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid); } showEditDoneProgress(true, true); } } } }); if (currentActivityType == TYPE_PHONE_VERIFICATION) { fragmentView = scrollView = new ScrollView(context) { @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { return false; } @Override public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { if (currentViewNum == 1 || currentViewNum == 2 || currentViewNum == 4) { rectangle.bottom += AndroidUtilities.dp(40); } return super.requestChildRectangleOnScreen(child, rectangle, immediate); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { scrollHeight = MeasureSpec.getSize(heightMeasureSpec) - AndroidUtilities.dp(30); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }; scrollView.setFillViewport(true); AndroidUtilities.setScrollViewEdgeEffectColor(scrollView, Theme.getColor(Theme.key_actionBarDefault)); } else { fragmentView = new FrameLayout(context); FrameLayout frameLayout = (FrameLayout) fragmentView; fragmentView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray)); scrollView = new ScrollView(context) { @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { return false; } @Override public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { rectangle.offset(child.getLeft() - child.getScrollX(), child.getTop() - child.getScrollY()); rectangle.top += AndroidUtilities.dp(20); rectangle.bottom += AndroidUtilities.dp(50); return super.requestChildRectangleOnScreen(child, rectangle, immediate); } }; scrollView.setFillViewport(true); AndroidUtilities.setScrollViewEdgeEffectColor(scrollView, Theme.getColor(Theme.key_actionBarDefault)); frameLayout.addView(scrollView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, currentActivityType == TYPE_REQUEST ? 48 : 0)); linearLayout2 = new LinearLayout(context); linearLayout2.setOrientation(LinearLayout.VERTICAL); scrollView.addView(linearLayout2, new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } if (currentActivityType != TYPE_REQUEST && currentActivityType != TYPE_MANAGE) { ActionBarMenu menu = actionBar.createMenu(); doneItem = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); progressView = new ContextProgressView(context, 1); progressView.setAlpha(0.0f); progressView.setScaleX(0.1f); progressView.setScaleY(0.1f); progressView.setVisibility(View.INVISIBLE); doneItem.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); if (currentActivityType == TYPE_IDENTITY || currentActivityType == TYPE_ADDRESS) { if (chatAttachAlert != null) { try { if (chatAttachAlert.isShowing()) { chatAttachAlert.dismiss(); } } catch (Exception ignore) { } chatAttachAlert.onDestroy(); chatAttachAlert = null; } } } if (currentActivityType == TYPE_PASSWORD) { createPasswordInterface(context); } else if (currentActivityType == TYPE_REQUEST) { createRequestInterface(context); } else if (currentActivityType == TYPE_IDENTITY) { createIdentityInterface(context); fillInitialValues(); } else if (currentActivityType == TYPE_ADDRESS) { createAddressInterface(context); fillInitialValues(); } else if (currentActivityType == TYPE_PHONE) { createPhoneInterface(context); } else if (currentActivityType == TYPE_EMAIL) { createEmailInterface(context); } else if (currentActivityType == TYPE_EMAIL_VERIFICATION) { createEmailVerificationInterface(context); } else if (currentActivityType == TYPE_PHONE_VERIFICATION) { createPhoneVerificationInterface(context); } else if (currentActivityType == TYPE_MANAGE) { createManageInterface(context); } return fragmentView; }
From source file:net.bluehack.ui.ChatActivity.java
private void processSelectedOption(int option) { if (selectedObject == null) { return;/*from w ww . j a v a2s . c o m*/ } switch (option) { case 0: { if (SendMessagesHelper.getInstance().retrySendMessage(selectedObject, false)) { moveScrollToLastMessage(); } break; } case 1: { if (getParentActivity() == null) { selectedObject = null; return; } createDeleteMessagesAlert(selectedObject); break; } case 2: { forwaringMessage = selectedObject; Bundle args = new Bundle(); args.putBoolean("onlySelect", true); args.putInt("dialogsType", 1); DialogsActivity fragment = new DialogsActivity(args); fragment.setDelegate(this); presentFragment(fragment); break; } case 3: { AndroidUtilities.addToClipboard(getMessageContent(selectedObject, 0, false)); break; } case 4: { String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = FileLoader.getPathToMessage(selectedObject.messageOwner).toString(); } if (selectedObject.type == 3 || selectedObject.type == 1) { if (Build.VERSION.SDK_INT >= 23 && getParentActivity().checkSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { getParentActivity() .requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 4); selectedObject = null; return; } MediaController.saveFile(path, getParentActivity(), selectedObject.type == 3 ? 1 : 0, null, null); } break; } case 5: { File locFile = null; if (selectedObject.messageOwner.attachPath != null && selectedObject.messageOwner.attachPath.length() != 0) { File f = new File(selectedObject.messageOwner.attachPath); if (f.exists()) { locFile = f; } } if (locFile == null) { File f = FileLoader.getPathToMessage(selectedObject.messageOwner); if (f.exists()) { locFile = f; } } if (locFile != null) { if (LocaleController.getInstance().applyLanguageFile(locFile)) { presentFragment(new LanguageSelectActivity()); } else { if (getParentActivity() == null) { selectedObject = null; return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage( LocaleController.getString("IncorrectLocalization", R.string.IncorrectLocalization)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); showDialog(builder.create()); } } break; } case 6: { String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = FileLoader.getPathToMessage(selectedObject.messageOwner).toString(); } Intent intent = new Intent(Intent.ACTION_SEND); intent.setType(selectedObject.getDocument().mime_type); intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(path))); getParentActivity().startActivityForResult( Intent.createChooser(intent, LocaleController.getString("ShareFile", R.string.ShareFile)), 500); break; } case 7: { String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = FileLoader.getPathToMessage(selectedObject.messageOwner).toString(); } if (Build.VERSION.SDK_INT >= 23 && getParentActivity().checkSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { getParentActivity().requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 4); selectedObject = null; return; } MediaController.saveFile(path, getParentActivity(), 0, null, null); break; } case 8: { showReplyPanel(true, selectedObject, null, null, false, true); break; } case 9: { showDialog(new StickersAlert(getParentActivity(), this, selectedObject.getInputStickerSet(), null, bottomOverlayChat.getVisibility() != View.VISIBLE ? chatActivityEnterView : null)); break; } case 10: { if (Build.VERSION.SDK_INT >= 23 && getParentActivity().checkSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { getParentActivity().requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 4); selectedObject = null; return; } String fileName = FileLoader.getDocumentFileName(selectedObject.getDocument()); if (fileName == null || fileName.length() == 0) { fileName = selectedObject.getFileName(); } String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = FileLoader.getPathToMessage(selectedObject.messageOwner).toString(); } MediaController.saveFile(path, getParentActivity(), selectedObject.isMusic() ? 3 : 2, fileName, selectedObject.getDocument() != null ? selectedObject.getDocument().mime_type : ""); break; } case 11: { TLRPC.Document document = selectedObject.getDocument(); MessagesController.getInstance().saveGif(document); showGifHint(); chatActivityEnterView.addRecentGif(document); break; } case 12: { if (getParentActivity() == null) { selectedObject = null; return; } if (searchItem != null && actionBar.isSearchFieldVisible()) { actionBar.closeSearchField(); chatActivityEnterView.setFieldFocused(); } mentionsAdapter.setNeedBotContext(false); chatListView.setOnItemLongClickListener(null); chatListView.setOnItemClickListener(null); chatListView.setClickable(false); chatListView.setLongClickable(false); chatActivityEnterView.setEditingMessageObject(selectedObject, !selectedObject.isMediaEmpty()); if (chatActivityEnterView.isEditingCaption()) { mentionsAdapter.setAllowNewMentions(false); } actionModeTitleContainer.setVisibility(View.VISIBLE); selectedMessagesCountTextView.setVisibility(View.GONE); checkEditTimer(); chatActivityEnterView.setAllowStickersAndGifs(false, false); final ActionBarMenu actionMode = actionBar.createActionMode(); actionMode.getItem(reply).setVisibility(View.GONE); actionMode.getItem(copy).setVisibility(View.GONE); actionMode.getItem(forward).setVisibility(View.GONE); actionMode.getItem(delete).setVisibility(View.GONE); if (editDoneItemAnimation != null) { editDoneItemAnimation.cancel(); editDoneItemAnimation = null; } editDoneItem.setVisibility(View.VISIBLE); showEditDoneProgress(true, false); actionBar.showActionMode(); updatePinnedMessageView(true); updateVisibleRows(); TLRPC.TL_messages_getMessageEditData req = new TLRPC.TL_messages_getMessageEditData(); req.peer = MessagesController.getInputPeer((int) dialog_id); req.id = selectedObject.getId(); editingMessageObjectReqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { editingMessageObjectReqId = 0; if (response == null) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage( LocaleController.getString("EditMessageError", R.string.EditMessageError)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); showDialog(builder.create()); if (chatActivityEnterView != null) { chatActivityEnterView.setEditingMessageObject(null, false); } } else { showEditDoneProgress(false, true); } } }); } }); break; } case 13: { final int mid = selectedObject.getId(); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setMessage(LocaleController.getString("PinMessageAlert", R.string.PinMessageAlert)); final boolean[] checks = new boolean[] { true }; FrameLayout frameLayout = new FrameLayout(getParentActivity()); if (Build.VERSION.SDK_INT >= 21) { frameLayout.setPadding(0, AndroidUtilities.dp(8), 0, 0); } CheckBoxCell cell = new CheckBoxCell(getParentActivity()); cell.setBackgroundResource(R.drawable.list_selector); cell.setText(LocaleController.getString("PinNotify", R.string.PinNotify), "", true, false); cell.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(8) : 0, 0, LocaleController.isRTL ? 0 : AndroidUtilities.dp(8), 0); frameLayout.addView(cell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.TOP | Gravity.LEFT, 8, 0, 8, 0)); cell.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckBoxCell cell = (CheckBoxCell) v; checks[0] = !checks[0]; cell.setChecked(checks[0], true); } }); builder.setView(frameLayout); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { MessagesController.getInstance().pinChannelMessage(currentChat, mid, checks[0]); } }); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); break; } case 14: { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setMessage(LocaleController.getString("UnpinMessageAlert", R.string.UnpinMessageAlert)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { MessagesController.getInstance().pinChannelMessage(currentChat, 0, false); } }); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); break; } case 15: { Bundle args = new Bundle(); args.putInt("user_id", selectedObject.messageOwner.media.user_id); args.putString("phone", selectedObject.messageOwner.media.phone_number); args.putBoolean("addContact", true); presentFragment(new ContactAddActivity(args)); break; } case 16: { AndroidUtilities.addToClipboard(selectedObject.messageOwner.media.phone_number); break; } case 17: { try { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + selectedObject.messageOwner.media.phone_number)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getParentActivity().startActivityForResult(intent, 500); } catch (Exception e) { FileLog.e("tmessages", e); } break; } } selectedObject = null; }
From source file:kr.wdream.ui.ChatActivity.java
private void processSelectedOption(int option) { if (selectedObject == null) { return;//from ww w.ja v a 2s .c o m } switch (option) { case 0: { if (SendMessagesHelper.getInstance().retrySendMessage(selectedObject, false)) { moveScrollToLastMessage(); } break; } case 1: { if (getParentActivity() == null) { selectedObject = null; return; } createDeleteMessagesAlert(selectedObject); break; } case 2: { forwaringMessage = selectedObject; Bundle args = new Bundle(); args.putBoolean("onlySelect", true); args.putInt("dialogsType", 1); DialogsActivity fragment = new DialogsActivity(args); fragment.setDelegate(this); presentFragment(fragment); break; } case 3: { AndroidUtilities.addToClipboard(getMessageContent(selectedObject, 0, false)); break; } case 4: { String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = FileLoader.getPathToMessage(selectedObject.messageOwner).toString(); } if (selectedObject.type == 3 || selectedObject.type == 1) { if (Build.VERSION.SDK_INT >= 23 && getParentActivity().checkSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { getParentActivity() .requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 4); selectedObject = null; return; } MediaController.saveFile(path, getParentActivity(), selectedObject.type == 3 ? 1 : 0, null, null); } break; } case 5: { File locFile = null; if (selectedObject.messageOwner.attachPath != null && selectedObject.messageOwner.attachPath.length() != 0) { File f = new File(selectedObject.messageOwner.attachPath); if (f.exists()) { locFile = f; } } if (locFile == null) { File f = FileLoader.getPathToMessage(selectedObject.messageOwner); if (f.exists()) { locFile = f; } } if (locFile != null) { if (LocaleController.getInstance().applyLanguageFile(locFile)) { presentFragment(new LanguageSelectActivity()); } else { if (getParentActivity() == null) { selectedObject = null; return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName)); builder.setMessage(LocaleController.getString("IncorrectLocalization", kr.wdream.storyshop.R.string.IncorrectLocalization)); builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK), null); showDialog(builder.create()); } } break; } case 6: { String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = FileLoader.getPathToMessage(selectedObject.messageOwner).toString(); } Intent intent = new Intent(Intent.ACTION_SEND); intent.setType(selectedObject.getDocument().mime_type); intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(path))); getParentActivity().startActivityForResult(Intent.createChooser(intent, LocaleController.getString("ShareFile", kr.wdream.storyshop.R.string.ShareFile)), 500); break; } case 7: { String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = FileLoader.getPathToMessage(selectedObject.messageOwner).toString(); } if (Build.VERSION.SDK_INT >= 23 && getParentActivity().checkSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { getParentActivity().requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 4); selectedObject = null; return; } MediaController.saveFile(path, getParentActivity(), 0, null, null); break; } case 8: { showReplyPanel(true, selectedObject, null, null, false, true); break; } case 9: { showDialog(new StickersAlert(getParentActivity(), this, selectedObject.getInputStickerSet(), null, bottomOverlayChat.getVisibility() != View.VISIBLE ? chatActivityEnterView : null)); break; } case 10: { if (Build.VERSION.SDK_INT >= 23 && getParentActivity().checkSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { getParentActivity().requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 4); selectedObject = null; return; } String fileName = FileLoader.getDocumentFileName(selectedObject.getDocument()); if (fileName == null || fileName.length() == 0) { fileName = selectedObject.getFileName(); } String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = FileLoader.getPathToMessage(selectedObject.messageOwner).toString(); } MediaController.saveFile(path, getParentActivity(), selectedObject.isMusic() ? 3 : 2, fileName, selectedObject.getDocument() != null ? selectedObject.getDocument().mime_type : ""); break; } case 11: { TLRPC.Document document = selectedObject.getDocument(); MessagesController.getInstance().saveGif(document); showGifHint(); chatActivityEnterView.addRecentGif(document); break; } case 12: { if (getParentActivity() == null) { selectedObject = null; return; } if (searchItem != null && actionBar.isSearchFieldVisible()) { actionBar.closeSearchField(); chatActivityEnterView.setFieldFocused(); } mentionsAdapter.setNeedBotContext(false); chatListView.setOnItemLongClickListener(null); chatListView.setOnItemClickListener(null); chatListView.setClickable(false); chatListView.setLongClickable(false); chatActivityEnterView.setEditingMessageObject(selectedObject, !selectedObject.isMediaEmpty()); if (chatActivityEnterView.isEditingCaption()) { mentionsAdapter.setAllowNewMentions(false); } actionModeTitleContainer.setVisibility(View.VISIBLE); selectedMessagesCountTextView.setVisibility(View.GONE); checkEditTimer(); chatActivityEnterView.setAllowStickersAndGifs(false, false); final ActionBarMenu actionMode = actionBar.createActionMode(); actionMode.getItem(reply).setVisibility(View.GONE); actionMode.getItem(copy).setVisibility(View.GONE); actionMode.getItem(forward).setVisibility(View.GONE); actionMode.getItem(delete).setVisibility(View.GONE); if (editDoneItemAnimation != null) { editDoneItemAnimation.cancel(); editDoneItemAnimation = null; } editDoneItem.setVisibility(View.VISIBLE); showEditDoneProgress(true, false); actionBar.showActionMode(); updatePinnedMessageView(true); updateVisibleRows(); TLRPC.TL_messages_getMessageEditData req = new TLRPC.TL_messages_getMessageEditData(); req.peer = MessagesController.getInputPeer((int) dialog_id); req.id = selectedObject.getId(); editingMessageObjectReqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { editingMessageObjectReqId = 0; if (response == null) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName)); builder.setMessage(LocaleController.getString("EditMessageError", kr.wdream.storyshop.R.string.EditMessageError)); builder.setPositiveButton( LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK), null); showDialog(builder.create()); if (chatActivityEnterView != null) { chatActivityEnterView.setEditingMessageObject(null, false); } } else { showEditDoneProgress(false, true); } } }); } }); break; } case 13: { final int mid = selectedObject.getId(); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setMessage( LocaleController.getString("PinMessageAlert", kr.wdream.storyshop.R.string.PinMessageAlert)); final boolean[] checks = new boolean[] { true }; FrameLayout frameLayout = new FrameLayout(getParentActivity()); if (Build.VERSION.SDK_INT >= 21) { frameLayout.setPadding(0, AndroidUtilities.dp(8), 0, 0); } CheckBoxCell cell = new CheckBoxCell(getParentActivity()); cell.setBackgroundResource(kr.wdream.storyshop.R.drawable.list_selector); cell.setText(LocaleController.getString("PinNotify", kr.wdream.storyshop.R.string.PinNotify), "", true, false); cell.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(8) : 0, 0, LocaleController.isRTL ? 0 : AndroidUtilities.dp(8), 0); frameLayout.addView(cell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.TOP | Gravity.LEFT, 8, 0, 8, 0)); cell.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckBoxCell cell = (CheckBoxCell) v; checks[0] = !checks[0]; cell.setChecked(checks[0], true); } }); builder.setView(frameLayout); builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { MessagesController.getInstance().pinChannelMessage(currentChat, mid, checks[0]); } }); builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName)); builder.setNegativeButton(LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel), null); showDialog(builder.create()); break; } case 14: { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setMessage(LocaleController.getString("UnpinMessageAlert", kr.wdream.storyshop.R.string.UnpinMessageAlert)); builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { MessagesController.getInstance().pinChannelMessage(currentChat, 0, false); } }); builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName)); builder.setNegativeButton(LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel), null); showDialog(builder.create()); break; } case 15: { Bundle args = new Bundle(); args.putInt("user_id", selectedObject.messageOwner.media.user_id); args.putString("phone", selectedObject.messageOwner.media.phone_number); args.putBoolean("addContact", true); presentFragment(new ContactAddActivity(args)); break; } case 16: { AndroidUtilities.addToClipboard(selectedObject.messageOwner.media.phone_number); break; } case 17: { try { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + selectedObject.messageOwner.media.phone_number)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getParentActivity().startActivityForResult(intent, 500); } catch (Exception e) { FileLog.e("tmessages", e); } break; } } selectedObject = null; }