List of usage examples for android.text ClipboardManager setText
public abstract void setText(CharSequence text);
From source file:info.guardianproject.otr.app.im.app.ChatView.java
@Override protected void onFinishInflate() { // mStatusIcon = (ImageView) findViewById(R.id.statusIcon); // mDeliveryIcon = (ImageView) findViewById(R.id.deliveryIcon); // mTitle = (TextView) findViewById(R.id.title); mHistory = (ListView) findViewById(R.id.history); mComposeMessage = (EditText) findViewById(R.id.composeMessage); mSendButton = (ImageButton) findViewById(R.id.btnSend); mHistory.setOnItemClickListener(mOnItemClickListener); mButtonAttach = (ImageButton) findViewById(R.id.btnAttach); mViewAttach = findViewById(R.id.attachPanel); mStatusWarningView = findViewById(R.id.warning); mWarningText = (TextView) findViewById(R.id.warningText); mProgressTransfer = (ProgressBar) findViewById(R.id.progressTransfer); // mOtrSwitch = (CompoundButton)findViewById(R.id.otrSwitch); mProgressBarOtr = (ProgressBar) findViewById(R.id.progressBarOtr); mButtonAttach.setOnClickListener(new OnClickListener() { @Override//from www. ja va2s .com public void onClick(View v) { if (mViewAttach.getVisibility() == View.GONE) mViewAttach.setVisibility(View.VISIBLE); else mViewAttach.setVisibility(View.GONE); } }); ((ImageButton) findViewById(R.id.btnAttachAudio)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mNewChatActivity.startAudioPicker(); } }); ((ImageButton) findViewById(R.id.btnAttachPicture)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mNewChatActivity.startImagePicker(); } }); ((ImageButton) findViewById(R.id.btnTakePicture)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mNewChatActivity.startPhotoTaker(); } }); ((ImageButton) findViewById(R.id.btnAttachFile)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mNewChatActivity.startFilePicker(); } }); mHistory.setOnItemLongClickListener(new OnItemLongClickListener() { @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { if (arg1 instanceof MessageView) { String textToCopy = ((MessageView) arg1).getLastMessage(); int sdk = android.os.Build.VERSION.SDK_INT; if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) mNewChatActivity .getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(textToCopy); // } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) mNewChatActivity .getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("chat", textToCopy); clipboard.setPrimaryClip(clip); // } Toast.makeText(mNewChatActivity, mContext.getString(R.string.toast_chat_copied_to_clipboard), Toast.LENGTH_SHORT).show(); return true; } return false; } }); mWarningText.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showVerifyDialog(); } }); //mOtrSwitch.setOnCheckedChangeListener(mOtrListener); mComposeMessage.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: sendMessage(); return true; case KeyEvent.KEYCODE_ENTER: if (event.isAltPressed()) { mComposeMessage.append("\n"); return true; } } } return false; } }); mComposeMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (event != null) { if (event.isAltPressed()) { return false; } } InputMethodManager imm = (InputMethodManager) mContext .getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null && imm.isActive(v)) { imm.hideSoftInputFromWindow(getWindowToken(), 0); } sendMessage(); return true; } }); // TODO: this is a hack to implement BUG #1611278, when dispatchKeyEvent() works with // the soft keyboard, we should remove this hack. mComposeMessage.addTextChangedListener(new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int before, int after) { } public void onTextChanged(CharSequence s, int start, int before, int after) { //log("TextWatcher: " + s); userActionDetected(); } public void afterTextChanged(Editable s) { } }); mSendButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { sendMessage(); } }); Button btnApproveSubscription = (Button) findViewById(R.id.btnApproveSubscription); btnApproveSubscription.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mNewChatActivity.approveSubscription(mProviderId, mRemoteAddress); mHandler.postDelayed(new Runnable() { public void run() { bindChat(mLastChatId); } }, 2000); } }); Button btnDeclineSubscription = (Button) findViewById(R.id.btnDeclineSubscription); btnDeclineSubscription.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mHandler.postDelayed(new Runnable() { public void run() { mNewChatActivity.declineSubscription(mProviderId, mRemoteAddress); } }, 500); } }); /* mActionBox = (View)findViewById(R.id.actionBox); ImageButton btnActionBox = (ImageButton)findViewById(R.id.btnActionBox); btnActionBox.setOnClickListener(new OnClickListener () { @Override public void onClick(View v) { mEmojiPager.setVisibility(View.GONE); if (mActionBox.getVisibility() == View.GONE) mActionBox.setVisibility(View.VISIBLE); else mActionBox.setVisibility(View.GONE); } }); View btnEndChat = findViewById(R.id.btnEndChat); btnEndChat.setOnClickListener(new OnClickListener () { @Override public void onClick(View v) { ChatView.this.closeChatSession(); } }); View btnProfile = findViewById(R.id.btnProfile); btnProfile.setOnClickListener(new OnClickListener () { @Override public void onClick(View v) { viewProfile(); } }); View btnSharePicture = findViewById(R.id.btnSendPicture); btnSharePicture.setOnClickListener(new OnClickListener () { @Override public void onClick(View v) { if (mLastSessionStatus != null && mLastSessionStatus == SessionStatus.ENCRYPTED) { mNewChatActivity.startImagePicker(); } else { mHandler.showServiceErrorAlert(getContext().getString(R.string.please_enable_chat_encryption_to_share_files)); } } }); View btnShareFile = findViewById(R.id.btnSendFile); btnShareFile.setOnClickListener(new OnClickListener () { @Override public void onClick(View v) { if (mLastSessionStatus != null && mLastSessionStatus == SessionStatus.ENCRYPTED) { mNewChatActivity.startFilePicker(); } else { mHandler.showServiceErrorAlert(getContext().getString(R.string.please_enable_chat_encryption_to_share_files)); } } }); */ initEmoji(); mMessageAdapter = new MessageAdapter(mNewChatActivity, null); mHistory.setAdapter(mMessageAdapter); }
From source file:org.kontalk.ui.ComposeMessageFragment.java
@Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.menu_delete: { // using clone because listview returns its original copy deleteSelectedMessages(SystemUtils.cloneSparseBooleanArray(getListView().getCheckedItemPositions())); mode.finish();/*from w w w .j a v a 2 s.co m*/ return true; } case R.id.menu_retry: { CompositeMessage msg = getCheckedItem(); retryMessage(msg); mode.finish(); return true; } case R.id.menu_share: { CompositeMessage msg = getCheckedItem(); shareMessage(msg); mode.finish(); return true; } case R.id.menu_copy_text: { CompositeMessage msg = getCheckedItem(); TextComponent txt = (TextComponent) msg.getComponent(TextComponent.class); String text = (txt != null) ? txt.getContent() : ""; ClipboardManager cpm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); cpm.setText(text); Toast.makeText(getActivity(), R.string.message_text_copied, Toast.LENGTH_SHORT).show(); mode.finish(); return true; } case R.id.menu_decrypt: { CompositeMessage msg = getCheckedItem(); decryptMessage(msg); mode.finish(); return true; } case R.id.menu_open: { CompositeMessage msg = getCheckedItem(); openFile(msg); mode.finish(); return true; } case R.id.menu_download: { CompositeMessage msg = getCheckedItem(); startDownload(msg); mode.finish(); return true; } case R.id.menu_cancel_download: { CompositeMessage msg = getCheckedItem(); stopDownload(msg); mode.finish(); return true; } case R.id.menu_details: { CompositeMessage msg = getCheckedItem(); showMessageDetails(msg); mode.finish(); return true; } } return false; }
From source file:net.robotmedia.acv.ui.widget.OcrLayout.java
/** Send the provided text to the clipboard. */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") private void sendToClipboard(String text) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) this.context .getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(text); } else {// w w w . j a va 2s . c om android.content.ClipboardManager clipboard = (android.content.ClipboardManager) this.context .getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("OCR Manga Reader Text", text); clipboard.setPrimaryClip(clip); } }
From source file:org.telepatch.ui.ChatActivity.java
private void processSelectedOption(int option) { if (selectedObject == null) { return;//w w w . j av a 2 s .com } if (option == 0) { if (SendMessagesHelper.getInstance().retrySendMessage(selectedObject, false)) { chatListView.setSelectionFromTop(messages.size() - 1, -100000 - chatListView.getPaddingTop()); } } else if (option == 1) { ArrayList<Integer> ids = new ArrayList<Integer>(); ids.add(selectedObject.messageOwner.id); removeUnreadPlane(true); ArrayList<Long> random_ids = null; if (currentEncryptedChat != null && selectedObject.messageOwner.random_id != 0 && selectedObject.type != 10) { random_ids = new ArrayList<Long>(); random_ids.add(selectedObject.messageOwner.random_id); } deleteMessages(ids, random_ids, currentEncryptedChat); //MessagesController.getInstance().deleteMessages(ids, random_ids, currentEncryptedChat); } else if (option == 2) { forwaringMessage = selectedObject; Bundle args = new Bundle(); args.putBoolean("onlySelect", true); args.putBoolean("serverOnly", true); args.putString("selectAlertString", LocaleController.getString("ForwardMessagesTo", R.string.ForwardMessagesTo)); args.putString("selectAlertStringGroup", LocaleController.getString("ForwardMessagesToGroup", R.string.ForwardMessagesToGroup)); MessagesActivity fragment = new MessagesActivity(args); fragment.setDelegate(this); presentFragment(fragment); } else if (option == 3) { if (Build.VERSION.SDK_INT < 11) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) ApplicationLoader.applicationContext .getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(selectedObject.messageText); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext .getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("label", selectedObject.messageText); clipboard.setPrimaryClip(clip); } } else if (option == 4) { String fileName = selectedObject.getFileName(); String path = selectedObject.messageOwner.attachPath; if (path == null || path.length() == 0) { path = FileLoader.getPathToMessage(selectedObject.messageOwner).toString(); } if (selectedObject.type == 3) { MediaController.saveFile(path, getParentActivity(), 1, null); } else if (selectedObject.type == 1) { MediaController.saveFile(path, getParentActivity(), 0, null); } else if (selectedObject.type == 8 || selectedObject.type == 9) { MediaController.saveFile(path, getParentActivity(), 2, selectedObject.messageOwner.media.document.file_name); } } else if (option == 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) { 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); showAlertDialog(builder); } } } selectedObject = null; }
From source file:org.petero.droidfish.DroidFish.java
private final Dialog clipBoardDialog() { final int COPY_GAME = 0; final int COPY_POSITION = 1; final int PASTE = 2; setAutoMode(AutoMode.OFF);/*from ww w . ja v a 2 s. co m*/ List<CharSequence> lst = new ArrayList<CharSequence>(); List<Integer> actions = new ArrayList<Integer>(); lst.add(getString(R.string.copy_game)); actions.add(COPY_GAME); lst.add(getString(R.string.copy_position)); actions.add(COPY_POSITION); lst.add(getString(R.string.paste)); actions.add(PASTE); final List<Integer> finalActions = actions; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.tools_menu); builder.setItems(lst.toArray(new CharSequence[lst.size()]), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch (finalActions.get(item)) { case COPY_GAME: { String pgn = ctrl.getPGN(); ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(pgn); break; } case COPY_POSITION: { String fen = ctrl.getFEN() + "\n"; ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(fen); break; } case PASTE: { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); if (clipboard.hasText()) { String fenPgn = clipboard.getText().toString(); try { ctrl.setFENOrPGN(fenPgn); setBoardFlip(true); } catch (ChessParseError e) { Toast.makeText(getApplicationContext(), getParseErrString(e), Toast.LENGTH_SHORT) .show(); } } break; } } } }); AlertDialog alert = builder.create(); return alert; }
From source file:org.telegram.ui.ChatActivity.java
private void processSelectedOption(int option) { if (option == 0) { if (selectedObject != null && selectedObject.messageOwner.id < 0) { if (selectedObject.type == 0 || selectedObject.type == 1) { if (selectedObject.messageOwner instanceof TLRPC.TL_messageForwarded) { MessagesController.Instance.sendMessage(selectedObject, dialog_id); } else { MessagesController.Instance.sendMessage(selectedObject.messageOwner.message, dialog_id); }//from w w w.ja v a2 s .co m } else if (selectedObject.type == 8 || selectedObject.type == 9) { MessagesController.Instance.sendMessage(selectedObject, dialog_id); } else if (selectedObject.type == 4 || selectedObject.type == 5) { MessagesController.Instance.sendMessage(selectedObject.messageOwner.media.geo.lat, selectedObject.messageOwner.media.geo._long, dialog_id); } else if (selectedObject.type == 2 || selectedObject.type == 3) { if (selectedObject.messageOwner instanceof TLRPC.TL_messageForwarded) { MessagesController.Instance.sendMessage(selectedObject, dialog_id); } else { TLRPC.TL_photo photo = (TLRPC.TL_photo) selectedObject.messageOwner.media.photo; MessagesController.Instance.sendMessage(photo, dialog_id); } } else if (selectedObject.type == 6 || selectedObject.type == 7) { if (selectedObject.messageOwner instanceof TLRPC.TL_messageForwarded) { MessagesController.Instance.sendMessage(selectedObject, dialog_id); } else { TLRPC.TL_video video = (TLRPC.TL_video) selectedObject.messageOwner.media.video; video.path = selectedObject.messageOwner.attachPath; MessagesController.Instance.sendMessage(video, dialog_id); } } else if (selectedObject.type == 12 || selectedObject.type == 13) { TLRPC.User user = MessagesController.Instance.users .get(selectedObject.messageOwner.media.user_id); MessagesController.Instance.sendMessage(user, dialog_id); } else if (selectedObject.type == 16 || selectedObject.type == 17) { TLRPC.TL_document document = (TLRPC.TL_document) selectedObject.messageOwner.media.document; document.path = selectedObject.messageOwner.attachPath; MessagesController.Instance.sendMessage(document, dialog_id); } else if (selectedObject.type == 18 || selectedObject.type == 19) { TLRPC.TL_audio audio = (TLRPC.TL_audio) selectedObject.messageOwner.media.audio; audio.path = selectedObject.messageOwner.attachPath; MessagesController.Instance.sendMessage(audio, dialog_id); } ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(selectedObject.messageOwner.id); MessagesController.Instance.deleteMessages(arr); chatListView.setSelection(messages.size() + 1); } } else if (option == 1) { if (selectedObject != null) { ArrayList<Integer> ids = new ArrayList<Integer>(); ids.add(selectedObject.messageOwner.id); removeUnreadPlane(true); MessagesController.Instance.deleteMessages(ids); selectedObject = null; } } else if (option == 2) { if (selectedObject != null) { if (parentActivity == null) { return; } forwaringMessage = selectedObject; selectedObject = null; MessagesActivity fragment = new MessagesActivity(); fragment.selectAlertString = R.string.ForwardMessagesTo; fragment.animationType = 1; Bundle args = new Bundle(); args.putBoolean("onlySelect", true); args.putBoolean("serverOnly", true); fragment.setArguments(args); fragment.delegate = this; ((ApplicationActivity) parentActivity).presentFragment(fragment, "select_chat", false); } } else if (option == 3) { if (selectedObject != null) { if (android.os.Build.VERSION.SDK_INT < 11) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) parentActivity .getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(selectedObject.messageText); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) parentActivity .getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("label", selectedObject.messageText); clipboard.setPrimaryClip(clip); } selectedObject = null; } } }
From source file:edu.mit.viral.shen.DroidFish.java
private final Dialog clipBoardDialog() { final int COPY_GAME = 0; final int COPY_POSITION = 1; final int PASTE = 2; List<CharSequence> lst = new ArrayList<CharSequence>(); List<Integer> actions = new ArrayList<Integer>(); lst.add(getString(R.string.copy_game)); actions.add(COPY_GAME);// ww w . j av a 2 s . c om lst.add(getString(R.string.copy_position)); actions.add(COPY_POSITION); lst.add(getString(R.string.paste)); actions.add(PASTE); final List<Integer> finalActions = actions; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.tools_menu); builder.setItems(lst.toArray(new CharSequence[lst.size()]), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch (finalActions.get(item)) { case COPY_GAME: { String pgn = ctrl.getPGN(); ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(pgn); break; } case COPY_POSITION: { String fen = ctrl.getFEN() + "\n"; ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(fen); break; } case PASTE: { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); if (clipboard.hasText()) { String fenPgn = clipboard.getText().toString(); try { ctrl.setFENOrPGN(fenPgn); setBoardFlip(true); } catch (ChessParseError e) { Toast.makeText(getApplicationContext(), getParseErrString(e), Toast.LENGTH_SHORT) .show(); } } break; } } } }); AlertDialog alert = builder.create(); return alert; }
From source file:org.telepatch.ui.ChatActivity.java
public View createView(LayoutInflater inflater, ViewGroup container) { if (fragmentView == null) { actionBarLayer.setDisplayHomeAsUpEnabled(true, R.drawable.ic_ab_back); if (AndroidUtilities.isTablet()) { actionBarLayer.setExtraLeftMargin(4); }/*from w w w . j a v a2 s.c o m*/ actionBarLayer.setBackOverlay(R.layout.updating_state_layout); actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == -2) { selectedMessagesIds.clear(); selectedMessagesCanCopyIds.clear(); actionBarLayer.hideActionMode(); updateVisibleRows(); } else if (id == attach_photo) { try { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File image = Utilities.generatePicturePath(); if (image != null) { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image)); currentPicturePath = image.getAbsolutePath(); } startActivityForResult(takePictureIntent, 0); } catch (Exception e) { FileLog.e("tmessages", e); } } else if (id == attach_gallery) { PhotoPickerActivity fragment = new PhotoPickerActivity(); fragment.setDelegate(new PhotoPickerActivity.PhotoPickerActivityDelegate() { @Override public void didSelectPhotos(ArrayList<String> photos) { SendMessagesHelper.prepareSendingPhotos(photos, null, dialog_id); } @Override public void startPhotoSelectActivity() { try { Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); photoPickerIntent.setType("image/*"); startActivityForResult(photoPickerIntent, 1); } catch (Exception e) { FileLog.e("tmessages", e); } } }); presentFragment(fragment); } else if (id == attach_video) { try { Intent pickIntent = new Intent(); pickIntent.setType("video/*"); pickIntent.setAction(Intent.ACTION_GET_CONTENT); pickIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long) (1024 * 1024 * 1000)); Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); File video = Utilities.generateVideoPath(); if (video != null) { if (Build.VERSION.SDK_INT >= 18) { takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(video)); } takeVideoIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long) (1024 * 1024 * 1000)); currentPicturePath = video.getAbsolutePath(); } Intent chooserIntent = Intent.createChooser(pickIntent, ""); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { takeVideoIntent }); startActivityForResult(chooserIntent, 2); } catch (Exception e) { FileLog.e("tmessages", e); } } else if (id == attach_location) { if (!isGoogleMapsInstalled()) { return; } LocationActivity fragment = new LocationActivity(); fragment.setDelegate(new LocationActivity.LocationActivityDelegate() { @Override public void didSelectLocation(double latitude, double longitude) { SendMessagesHelper.getInstance().sendMessage(latitude, longitude, dialog_id); if (chatListView != null) { chatListView.setSelectionFromTop(messages.size() - 1, -100000 - chatListView.getPaddingTop()); } if (paused) { scrollToTopOnResume = true; } } }); presentFragment(fragment); } else if (id == attach_document) { DocumentSelectActivity fragment = new DocumentSelectActivity(); fragment.setDelegate(new DocumentSelectActivity.DocumentSelectActivityDelegate() { @Override public void didSelectFile(DocumentSelectActivity activity, String path) { activity.finishFragment(); SendMessagesHelper.prepareSendingDocument(path, path, dialog_id); } @Override public void startDocumentSelectActivity() { try { Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); photoPickerIntent.setType("*/*"); startActivityForResult(photoPickerIntent, 21); } catch (Exception e) { FileLog.e("tmessages", e); } } }); presentFragment(fragment); } else if (id == chat_menu_avatar) { if (currentUser != null) { Bundle args = new Bundle(); args.putInt("user_id", currentUser.id); if (currentEncryptedChat != null) { args.putLong("dialog_id", dialog_id); } presentFragment(new UserProfileActivity(args)); } else if (currentChat != null) { if (info != null && info instanceof TLRPC.TL_chatParticipantsForbidden) { return; } int count = currentChat.participants_count; if (info != null) { count = info.participants.size(); } if (count == 0 || currentChat.left || currentChat instanceof TLRPC.TL_chatForbidden) { return; } Bundle args = new Bundle(); args.putInt("chat_id", currentChat.id); ChatProfileActivity fragment = new ChatProfileActivity(args); fragment.setChatInfo(info); presentFragment(fragment); } } else if (id == copy) { String str = ""; ArrayList<Integer> ids = new ArrayList<Integer>(selectedMessagesCanCopyIds.keySet()); if (currentEncryptedChat == null) { Collections.sort(ids); } else { Collections.sort(ids, Collections.reverseOrder()); } for (Integer messageId : ids) { MessageObject messageObject = selectedMessagesCanCopyIds.get(messageId); if (str.length() != 0) { str += "\n"; } if (messageObject.messageOwner.message != null) { str += messageObject.messageOwner.message; } else { str += messageObject.messageText; } } if (str.length() != 0) { if (Build.VERSION.SDK_INT < 11) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) ApplicationLoader.applicationContext .getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(str); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext .getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("label", str); clipboard.setPrimaryClip(clip); } } selectedMessagesIds.clear(); selectedMessagesCanCopyIds.clear(); actionBarLayer.hideActionMode(); updateVisibleRows(); } else if (id == delete) { ArrayList<Integer> ids = new ArrayList<Integer>(selectedMessagesIds.keySet()); ArrayList<Long> random_ids = null; if (currentEncryptedChat != null) { random_ids = new ArrayList<Long>(); for (HashMap.Entry<Integer, MessageObject> entry : selectedMessagesIds.entrySet()) { MessageObject msg = entry.getValue(); if (msg.messageOwner.random_id != 0 && msg.type != 10) { random_ids.add(msg.messageOwner.random_id); } } } //MessagesController.getInstance().deleteMessages(ids, random_ids, currentEncryptedChat); //TODO qui utilizzo un mio metodo per cancellare i messaggi, cosi' prima mostro un alert deleteMessages(ids, random_ids, currentEncryptedChat); actionBarLayer.hideActionMode(); } else if (id == forward) { Bundle args = new Bundle(); args.putBoolean("onlySelect", true); args.putBoolean("serverOnly", true); args.putString("selectAlertString", LocaleController.getString("ForwardMessagesTo", R.string.ForwardMessagesTo)); args.putString("selectAlertStringGroup", LocaleController .getString("ForwardMessagesToGroup", R.string.ForwardMessagesToGroup)); MessagesActivity fragment = new MessagesActivity(args); fragment.setDelegate(ChatActivity.this); presentFragment(fragment); } } }); updateSubtitle(); if (currentEncryptedChat != null) { actionBarLayer.setTitleIcon(R.drawable.ic_lock_white, AndroidUtilities.dp(4)); } else if (currentChat != null && currentChat.id < 0) { actionBarLayer.setTitleIcon(R.drawable.broadcast2, AndroidUtilities.dp(4)); } ActionBarMenu menu = actionBarLayer.createMenu(); if (currentEncryptedChat != null) { timeItem = menu.addItemResource(chat_enc_timer, R.layout.chat_header_enc_layout); } //TODO aggiungo il pulsante di ricerca item_search = menu.addItem(chat_menu_search, R.drawable.ic_ab_search); item_search.setIsSearchField(true) .setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { @Override public void onSearchExpand() { searching = true; } @Override public void onSearchCollapse() { searching = false; //MessagesController.getInstance().loadMessages(dialog_id, 0, 20, maxMessageId, !cacheEndReaced, minDate, classGuid, false, false); //NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); } @Override public void onTextChanged(final EditText editText) { editText.requestFocus(); editText.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { boolean result = false; // se l'evento e' un "tasto premuto" sul tasto enter if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { //fai azione if (!editText.getText().toString().equals("")) { searchMessages(dialog_id, editText.getText().toString(), new FutureSearch()); try { presentFragment(new SearchResultsActivity( doSearchAndBlock(dialog_id, editText.getText().toString()), getArguments())); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (NullPointerException e) { Log.e("xela92", "NullPointerException. Forse la connessione di rete e' assente? La ricerca stata annullata. "); e.printStackTrace(); } } result = true; } return result; } }); } }); ActionBarMenuItem item = menu.addItem(chat_menu_attach, R.drawable.ic_ab_attach); item.addSubItem(attach_photo, LocaleController.getString("ChatTakePhoto", R.string.ChatTakePhoto), R.drawable.ic_attach_photo); item.addSubItem(attach_gallery, LocaleController.getString("ChatGallery", R.string.ChatGallery), R.drawable.ic_attach_gallery); item.addSubItem(attach_video, LocaleController.getString("ChatVideo", R.string.ChatVideo), R.drawable.ic_attach_video); item.addSubItem(attach_document, LocaleController.getString("ChatDocument", R.string.ChatDocument), R.drawable.ic_ab_doc); item.addSubItem(attach_location, LocaleController.getString("ChatLocation", R.string.ChatLocation), R.drawable.ic_attach_location); menuItem = item; actionModeViews.clear(); final ActionBarMenu actionMode = actionBarLayer.createActionMode(); actionModeViews.add(actionMode.addItem(-2, R.drawable.ic_ab_done_gray, R.drawable.bar_selector_mode)); FrameLayout layout = new FrameLayout(actionMode.getContext()); layout.setBackgroundColor(0xffe5e5e5); actionMode.addView(layout); LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) layout.getLayoutParams(); layoutParams.width = AndroidUtilities.dp(1); layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; layoutParams.topMargin = AndroidUtilities.dp(12); layoutParams.bottomMargin = AndroidUtilities.dp(12); layoutParams.gravity = Gravity.CENTER_VERTICAL; layout.setLayoutParams(layoutParams); actionModeViews.add(layout); selectedMessagesCountTextView = new TextView(actionMode.getContext()); selectedMessagesCountTextView.setTextSize(18); selectedMessagesCountTextView.setTextColor(0xff000000); selectedMessagesCountTextView.setSingleLine(true); selectedMessagesCountTextView.setLines(1); selectedMessagesCountTextView.setEllipsize(TextUtils.TruncateAt.END); selectedMessagesCountTextView.setPadding(AndroidUtilities.dp(11), 0, 0, 0); selectedMessagesCountTextView.setGravity(Gravity.CENTER_VERTICAL); selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); actionMode.addView(selectedMessagesCountTextView); layoutParams = (LinearLayout.LayoutParams) selectedMessagesCountTextView.getLayoutParams(); layoutParams.weight = 1; layoutParams.width = 0; layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; selectedMessagesCountTextView.setLayoutParams(layoutParams); if (currentEncryptedChat == null) { actionModeViews .add(actionMode.addItem(copy, R.drawable.ic_ab_fwd_copy, R.drawable.bar_selector_mode)); actionModeViews.add( actionMode.addItem(forward, R.drawable.ic_ab_fwd_forward, R.drawable.bar_selector_mode)); actionModeViews .add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete, R.drawable.bar_selector_mode)); } else { actionModeViews .add(actionMode.addItem(copy, R.drawable.ic_ab_fwd_copy, R.drawable.bar_selector_mode)); actionModeViews .add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete, R.drawable.bar_selector_mode)); } actionMode.getItem(copy) .setVisibility(selectedMessagesCanCopyIds.size() != 0 ? View.VISIBLE : View.GONE); View avatarLayout = menu.addItemResource(chat_menu_avatar, R.layout.chat_header_layout); avatarImageView = (BackupImageView) avatarLayout.findViewById(R.id.chat_avatar_image); avatarImageView.processDetach = false; checkActionBarMenu(); fragmentView = inflater.inflate(R.layout.chat_layout, container, false); View contentView = fragmentView.findViewById(R.id.chat_layout); TextView emptyView = (TextView) fragmentView.findViewById(R.id.searchEmptyView); emptyViewContainer = fragmentView.findViewById(R.id.empty_view); emptyViewContainer.setVisibility(View.GONE); emptyViewContainer.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); emptyView.setText(LocaleController.getString("NoMessages", R.string.NoMessages)); chatListView = (LayoutListView) fragmentView.findViewById(R.id.chat_list_view); chatListView.setAdapter(chatAdapter = new ChatAdapter(getParentActivity())); topPanel = fragmentView.findViewById(R.id.top_panel); topPlaneClose = (ImageView) fragmentView.findViewById(R.id.top_plane_close); topPanelText = (TextView) fragmentView.findViewById(R.id.top_panel_text); bottomOverlay = fragmentView.findViewById(R.id.bottom_overlay); bottomOverlayText = (TextView) fragmentView.findViewById(R.id.bottom_overlay_text); bottomOverlayChat = fragmentView.findViewById(R.id.bottom_overlay_chat); progressView = fragmentView.findViewById(R.id.progressLayout); pagedownButton = fragmentView.findViewById(R.id.pagedown_button); pagedownButton.setVisibility(View.GONE); View progressViewInner = progressView.findViewById(R.id.progressLayoutInner); updateContactStatus(); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); int selectedBackground = preferences.getInt("selectedBackground", 1000001); int selectedColor = preferences.getInt("selectedColor", 0); if (selectedColor != 0) { contentView.setBackgroundColor(selectedColor); chatListView.setCacheColorHint(selectedColor); } else { chatListView.setCacheColorHint(0); try { if (selectedBackground == 1000001) { ((SizeNotifierRelativeLayout) contentView).setBackgroundImage(R.drawable.background_hd); } else { File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper.jpg"); if (toFile.exists()) { if (ApplicationLoader.cachedWallpaper != null) { ((SizeNotifierRelativeLayout) contentView) .setBackgroundImage(ApplicationLoader.cachedWallpaper); } else { Drawable drawable = Drawable.createFromPath(toFile.getAbsolutePath()); if (drawable != null) { ((SizeNotifierRelativeLayout) contentView).setBackgroundImage(drawable); ApplicationLoader.cachedWallpaper = drawable; } else { contentView.setBackgroundColor(-2693905); chatListView.setCacheColorHint(-2693905); } } isCustomTheme = true; } else { ((SizeNotifierRelativeLayout) contentView).setBackgroundImage(R.drawable.background_hd); } } } catch (Exception e) { contentView.setBackgroundColor(-2693905); chatListView.setCacheColorHint(-2693905); FileLog.e("tmessages", e); } } if (currentEncryptedChat != null) { emptyView.setVisibility(View.GONE); View secretChatPlaceholder = contentView.findViewById(R.id.secret_placeholder); secretChatPlaceholder.setVisibility(View.VISIBLE); if (isCustomTheme) { secretChatPlaceholder.setBackgroundResource(R.drawable.system_black); } else { secretChatPlaceholder.setBackgroundResource(R.drawable.system_blue); } secretViewStatusTextView = (TextView) contentView.findViewById(R.id.invite_text); secretChatPlaceholder.setPadding(AndroidUtilities.dp(16), AndroidUtilities.dp(12), AndroidUtilities.dp(16), AndroidUtilities.dp(12)); View v = contentView.findViewById(R.id.secret_placeholder); v.setVisibility(View.VISIBLE); if (currentEncryptedChat.admin_id == UserConfig.getClientUserId()) { if (currentUser.first_name.length() > 0) { secretViewStatusTextView .setText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing", R.string.EncryptedPlaceholderTitleOutgoing, currentUser.first_name)); } else { secretViewStatusTextView .setText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing", R.string.EncryptedPlaceholderTitleOutgoing, currentUser.last_name)); } } else { if (currentUser.first_name.length() > 0) { secretViewStatusTextView .setText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming", R.string.EncryptedPlaceholderTitleIncoming, currentUser.first_name)); } else { secretViewStatusTextView .setText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming", R.string.EncryptedPlaceholderTitleIncoming, currentUser.last_name)); } } updateSecretStatus(); } if (isCustomTheme) { progressViewInner.setBackgroundResource(R.drawable.system_loader2); emptyView.setBackgroundResource(R.drawable.system_black); } else { progressViewInner.setBackgroundResource(R.drawable.system_loader1); emptyView.setBackgroundResource(R.drawable.system_blue); } emptyView.setPadding(AndroidUtilities.dp(7), AndroidUtilities.dp(1), AndroidUtilities.dp(7), AndroidUtilities.dp(1)); if (currentUser != null && (currentUser.id / 1000 == 333 || currentUser.id % 1000 == 0)) { emptyView.setText(LocaleController.getString("GotAQuestion", R.string.GotAQuestion)); } chatListView.setOnItemLongClickListener(onItemLongClickListener); chatListView.setOnItemClickListener(onItemClickListener); final Rect scrollRect = new Rect(); chatListView.setOnInterceptTouchEventListener(new LayoutListView.OnInterceptTouchEventListener() { @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (actionBarLayer.isActionModeShowed()) { return false; } if (event.getAction() == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); int count = chatListView.getChildCount(); Rect rect = new Rect(); for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); int top = view.getTop(); int bottom = view.getBottom(); view.getLocalVisibleRect(rect); if (top > y || bottom < y) { continue; } if (!(view instanceof ChatMediaCell)) { break; } final ChatMediaCell cell = (ChatMediaCell) view; final MessageObject messageObject = cell.getMessageObject(); if (messageObject == null || !messageObject.isSecretPhoto() || !cell.getPhotoImage().isInsideImage(x, y - top)) { break; } File file = FileLoader.getPathToMessage(messageObject.messageOwner); if (!file.exists()) { break; } startX = x; startY = y; chatListView.setOnItemClickListener(null); openSecretPhotoRunnable = new Runnable() { @Override public void run() { if (openSecretPhotoRunnable == null) { return; } chatListView.requestDisallowInterceptTouchEvent(true); chatListView.setOnItemLongClickListener(null); chatListView.setLongClickable(false); openSecretPhotoRunnable = null; if (sendSecretMessageRead(messageObject)) { cell.invalidate(); } SecretPhotoViewer.getInstance().setParentActivity(getParentActivity()); SecretPhotoViewer.getInstance().openPhoto(messageObject); } }; AndroidUtilities.RunOnUIThread(openSecretPhotoRunnable, 100); return true; } } return false; } }); chatListView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (openSecretPhotoRunnable != null || SecretPhotoViewer.getInstance().isVisible()) { if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_POINTER_UP) { AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { chatListView.setOnItemClickListener(onItemClickListener); } }, 150); if (openSecretPhotoRunnable != null) { AndroidUtilities.CancelRunOnUIThread(openSecretPhotoRunnable); openSecretPhotoRunnable = null; try { Toast.makeText(v.getContext(), LocaleController.getString("PhotoTip", R.string.PhotoTip), Toast.LENGTH_SHORT).show(); } catch (Exception e) { FileLog.e("tmessages", e); } } else { if (SecretPhotoViewer.getInstance().isVisible()) { AndroidUtilities.RunOnUIThread(new Runnable() { @Override public void run() { chatListView.setOnItemLongClickListener(onItemLongClickListener); chatListView.setLongClickable(true); } }); SecretPhotoViewer.getInstance().closePhoto(); } } } else if (event.getAction() != MotionEvent.ACTION_DOWN) { if (SecretPhotoViewer.getInstance().isVisible()) { return true; } else if (openSecretPhotoRunnable != null) { if (event.getAction() == MotionEvent.ACTION_MOVE) { if (Math.hypot(startX - event.getX(), startY - event.getY()) > AndroidUtilities .dp(5)) { AndroidUtilities.CancelRunOnUIThread(openSecretPhotoRunnable); openSecretPhotoRunnable = null; } } else { AndroidUtilities.CancelRunOnUIThread(openSecretPhotoRunnable); openSecretPhotoRunnable = null; } } } } return false; } }); chatListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int i) { } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (visibleItemCount > 0) { if (firstVisibleItem <= 10) { if (!endReached && !loading) { if (messagesByDays.size() != 0) { MessagesController.getInstance().loadMessages(dialog_id, 20, maxMessageId, !cacheEndReaced, minDate, classGuid, false, false, null); } else { MessagesController.getInstance().loadMessages(dialog_id, 20, 0, !cacheEndReaced, minDate, classGuid, false, false, null); } loading = true; } } if (firstVisibleItem + visibleItemCount >= totalItemCount - 6) { if (!unread_end_reached && !loadingForward) { MessagesController.getInstance().loadMessages(dialog_id, 20, minMessageId, true, maxDate, classGuid, false, true, null); loadingForward = true; } } if (firstVisibleItem + visibleItemCount == totalItemCount && unread_end_reached) { showPagedownButton(false, true); } } for (int a = 0; a < visibleItemCount; a++) { View view = absListView.getChildAt(a); if (view instanceof ChatMessageCell) { ChatMessageCell messageCell = (ChatMessageCell) view; messageCell.getLocalVisibleRect(scrollRect); messageCell.setVisiblePart(scrollRect.top, scrollRect.bottom - scrollRect.top); } } } }); bottomOverlayChatText = (TextView) fragmentView.findViewById(R.id.bottom_overlay_chat_text); TextView textView = (TextView) fragmentView.findViewById(R.id.secret_title); textView.setText( LocaleController.getString("EncryptedDescriptionTitle", R.string.EncryptedDescriptionTitle)); textView = (TextView) fragmentView.findViewById(R.id.secret_description1); textView.setText(LocaleController.getString("EncryptedDescription1", R.string.EncryptedDescription1)); textView = (TextView) fragmentView.findViewById(R.id.secret_description2); textView.setText(LocaleController.getString("EncryptedDescription2", R.string.EncryptedDescription2)); textView = (TextView) fragmentView.findViewById(R.id.secret_description3); textView.setText(LocaleController.getString("EncryptedDescription3", R.string.EncryptedDescription3)); textView = (TextView) fragmentView.findViewById(R.id.secret_description4); textView.setText(LocaleController.getString("EncryptedDescription4", R.string.EncryptedDescription4)); if (loading && messages.isEmpty()) { progressView.setVisibility(View.VISIBLE); chatListView.setEmptyView(null); } else { progressView.setVisibility(View.GONE); chatListView.setEmptyView(emptyViewContainer); } pagedownButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { scrollToLastMessage(); } }); bottomOverlayChat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); if (currentUser != null && userBlocked) { builder.setMessage(LocaleController.getString("AreYouSureUnblockContact", R.string.AreYouSureUnblockContact)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { MessagesController.getInstance().unblockUser(currentUser.id); } }); } else { builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat", R.string.AreYouSureDeleteThisChat)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { MessagesController.getInstance().deleteDialog(dialog_id, 0, false); finishFragment(); } }); } builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showAlertDialog(builder); } }); updateBottomOverlay(); chatActivityEnterView.setContainerView(getParentActivity(), fragmentView); } else { ViewGroup parent = (ViewGroup) fragmentView.getParent(); if (parent != null) { parent.removeView(fragmentView); } } return fragmentView; }
From source file:com.sentaroh.android.SMBSync.SMBSyncMain.java
private void createHistoryContextMenu_Single(final int cin) { ccMenu.addMenuItem(msgs_move_to_top, R.drawable.menu_top) .setOnClickListener(new CustomContextMenuOnClickListener() { @Override//from w w w . ja va 2s. co m public void onClick(CharSequence menuTitle) { mGp.syncHistoryListView.setSelection(0); } }); ccMenu.addMenuItem(msgs_move_to_bottom, R.drawable.menu_bottom) .setOnClickListener(new CustomContextMenuOnClickListener() { @Override public void onClick(CharSequence menuTitle) { mGp.syncHistoryListView.setSelection(mGp.syncHistoryAdapter.getCount() - 1); } }); final SyncHistoryListItem item = mGp.syncHistoryAdapter.getItem(cin); if (!item.sync_result_file_path.equals("")) { ccMenu.addMenuItem(getString(R.string.msgs_sync_history_ccmeu_show_log), R.drawable.ic_64_browse_text) .setOnClickListener(new CustomContextMenuOnClickListener() { @Override public void onClick(CharSequence menuTitle) { Intent intent = new Intent(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("file://" + item.sync_result_file_path), "text/plain"); startActivityForResult(intent, 1); } }); } ccMenu.addMenuItem(msgs_sync_history_ccmeu_delete, R.drawable.menu_trash) .setOnClickListener(new CustomContextMenuOnClickListener() { @Override public void onClick(CharSequence menuTitle) { confirmDeleteHistory(); } }); ccMenu.addMenuItem(msgs_sync_history_ccmeu_unselectall) .setOnClickListener(new CustomContextMenuOnClickListener() { @Override public void onClick(CharSequence menuTitle) { for (int i = 0; i < mGp.syncHistoryAdapter.getCount(); i++) mGp.syncHistoryAdapter.getItem(i).isChecked = false; mGp.syncHistoryAdapter.notifyDataSetChanged(); } }); ccMenu.addMenuItem(msgs_sync_history_ccmeu_selectall) .setOnClickListener(new CustomContextMenuOnClickListener() { @Override public void onClick(CharSequence menuTitle) { for (int i = 0; i < mGp.syncHistoryAdapter.getCount(); i++) mGp.syncHistoryAdapter.getItem(i).isChecked = true; mGp.syncHistoryAdapter.notifyDataSetChanged(); } }); ccMenu.addMenuItem(msgs_sync_history_ccmeu_copy_clipboard) .setOnClickListener(new CustomContextMenuOnClickListener() { @Override public void onClick(CharSequence menuTitle) { ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); SyncHistoryListItem hli = mGp.syncHistoryAdapter.getItem(cin); StringBuilder out = new StringBuilder(256); out.append(hli.sync_date).append(" "); out.append(hli.sync_time).append(" "); out.append(hli.sync_prof).append("\n"); if (hli.sync_status == SyncHistoryListItem.SYNC_STATUS_SUCCESS) { out.append(mContext.getString(R.string.msgs_sync_history_status_success)).append("\n"); } else if (hli.sync_status == SyncHistoryListItem.SYNC_STATUS_ERROR) { out.append(mContext.getString(R.string.msgs_sync_history_status_fail)).append("\n"); } else if (hli.sync_status == SyncHistoryListItem.SYNC_STATUS_CANCELLED) { out.append(mContext.getString(R.string.msgs_sync_history_status_cancel)).append("\n"); } out.append(mContext.getString(R.string.msgs_sync_history_count_copied)) .append(Integer.toString(hli.sync_result_no_of_copied)).append(" "); out.append(mContext.getString(R.string.msgs_sync_history_count_deleted)) .append(Integer.toString(hli.sync_result_no_of_deleted)).append(" "); out.append(mContext.getString(R.string.msgs_sync_history_count_ignored)) .append(Integer.toString(hli.sync_result_no_of_ignored)).append(" "); out.append("\n").append(hli.sync_error_text); cm.setText(out); } }); ccMenu.createMenu(); }
From source file:com.irccloud.android.activity.MainActivity.java
@SuppressLint("NewApi") @SuppressWarnings("deprecation") private void showUserPopup(UsersDataSource.User user, Spanned message) { ArrayList<String> itemList = new ArrayList<String>(); final String[] items; final Spanned text_to_copy = message; selected_user = user;/*from w w w . j a v a2 s . c o m*/ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB); if (message != null) { if (message.getSpans(0, message.length(), URLSpan.class).length > 0) itemList.add("Copy URL"); itemList.add("Copy Message"); } if (selected_user != null) { itemList.add("Whois"); itemList.add("Send a message"); itemList.add("Mention"); itemList.add("Invite to a channel"); itemList.add("Ignore"); if (buffer.type.equalsIgnoreCase("channel")) { UsersDataSource.User self_user = UsersDataSource.getInstance().getUser(buffer.bid, server.nick); if (self_user != null && self_user.mode != null) { if (self_user.mode.contains(server != null ? server.MODE_OPER : "Y") || self_user.mode.contains(server != null ? server.MODE_OWNER : "q") || self_user.mode.contains(server != null ? server.MODE_ADMIN : "a") || self_user.mode.contains(server != null ? server.MODE_OP : "o")) { if (selected_user.mode.contains(server != null ? server.MODE_OP : "o")) itemList.add("Deop"); else itemList.add("Op"); } if (self_user.mode.contains(server != null ? server.MODE_OPER : "Y") || self_user.mode.contains(server != null ? server.MODE_OWNER : "q") || self_user.mode.contains(server != null ? server.MODE_ADMIN : "a") || self_user.mode.contains(server != null ? server.MODE_OP : "o") || self_user.mode.contains(server != null ? server.MODE_HALFOP : "h")) { itemList.add("Kick"); itemList.add("Ban"); } } } itemList.add("Copy Hostmask"); } items = itemList.toArray(new String[itemList.size()]); if (selected_user != null) if (selected_user.hostmask != null && selected_user.hostmask.length() > 0) builder.setTitle(selected_user.nick + "\n(" + selected_user.hostmask + ")"); else builder.setTitle(selected_user.nick); else builder.setTitle("Message"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int item) { if (conn == null || buffer == null) return; AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB); View view; final TextView prompt; final EditText input; AlertDialog dialog; if (items[item].equals("Copy Message")) { if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService( CLIPBOARD_SERVICE); clipboard.setText(text_to_copy); } else { @SuppressLint("ServiceCast") android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService( CLIPBOARD_SERVICE); if (clipboard != null) { android.content.ClipData clip = android.content.ClipData .newPlainText("IRCCloud Message", text_to_copy); clipboard.setPrimaryClip(clip); } else { Toast.makeText(MainActivity.this, "Unable to copy message. Please try again.", Toast.LENGTH_SHORT).show(); return; } } Toast.makeText(MainActivity.this, "Message copied to clipboard", Toast.LENGTH_SHORT).show(); } else if (items[item].equals("Copy Hostmask")) { if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService( CLIPBOARD_SERVICE); clipboard.setText(selected_user.nick + "!" + selected_user.hostmask); } else { @SuppressLint("ServiceCast") android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService( CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("Hostmask", selected_user.nick + "!" + selected_user.hostmask); clipboard.setPrimaryClip(clip); } Toast.makeText(MainActivity.this, "Hostmask copied to clipboard", Toast.LENGTH_SHORT).show(); } else if (items[item].equals("Copy URL") && text_to_copy != null) { final ArrayList<String> urlListItems = new ArrayList<String>(); for (URLSpan o : text_to_copy.getSpans(0, text_to_copy.length(), URLSpan.class)) { String url = o.getURL(); url = url.replace(getResources().getString(R.string.IMAGE_SCHEME) + "://", "http://"); url = url.replace(getResources().getString(R.string.IMAGE_SCHEME_SECURE) + "://", "https://"); if (server != null) { url = url.replace( getResources().getString(R.string.IRCCLOUD_SCHEME) + "://cid/" + server.cid + "/", ((server.ssl > 0) ? "ircs://" : "irc://") + server.hostname + ":" + server.port + "/"); } urlListItems.add(url); } if (urlListItems.size() == 1) { if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService( CLIPBOARD_SERVICE); clipboard.setText(urlListItems.get(0)); } else { @SuppressLint("ServiceCast") android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService( CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData .newPlainText(urlListItems.get(0), urlListItems.get(0)); clipboard.setPrimaryClip(clip); } Toast.makeText(MainActivity.this, "URL copied to clipboard", Toast.LENGTH_SHORT).show(); } else { builder = new AlertDialog.Builder(MainActivity.this); builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB); builder.setTitle("Choose a URL"); builder.setItems(urlListItems.toArray(new String[urlListItems.size()]), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService( CLIPBOARD_SERVICE); clipboard.setText(urlListItems.get(i)); } else { @SuppressLint("ServiceCast") android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService( CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData .newPlainText(urlListItems.get(i), urlListItems.get(i)); clipboard.setPrimaryClip(clip); } Toast.makeText(MainActivity.this, "URL copied to clipboard", Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MainActivity.this); dialog.getWindow() .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } } else if (items[item].equals("Whois")) { conn.whois(buffer.cid, selected_user.nick, null); } else if (items[item].equals("Send a message")) { conn.say(buffer.cid, null, "/query " + selected_user.nick); } else if (items[item].equals("Mention")) { if (!getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) { Toast.makeText(MainActivity.this, "Double-tap a message to quickly reply to the sender", Toast.LENGTH_LONG).show(); SharedPreferences.Editor editor = getSharedPreferences("prefs", 0).edit(); editor.putBoolean("mentionTip", true); editor.commit(); } onUserDoubleClicked(selected_user.nick); } else if (items[item].equals("Invite to a channel")) { view = getDialogTextPrompt(); prompt = (TextView) view.findViewById(R.id.prompt); input = (EditText) view.findViewById(R.id.textInput); input.setText(""); prompt.setText("Invite " + selected_user.nick + " to a channel"); builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")"); builder.setView(view); builder.setPositiveButton("Invite", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { conn.invite(buffer.cid, input.getText().toString(), selected_user.nick); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MainActivity.this); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } else if (items[item].equals("Ignore")) { view = getDialogTextPrompt(); prompt = (TextView) view.findViewById(R.id.prompt); input = (EditText) view.findViewById(R.id.textInput); input.setText("*!" + selected_user.hostmask); prompt.setText("Ignore messages for " + selected_user.nick + " at this hostmask"); builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")"); builder.setView(view); builder.setPositiveButton("Ignore", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { conn.ignore(buffer.cid, input.getText().toString()); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MainActivity.this); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } else if (items[item].equals("Op")) { conn.mode(buffer.cid, buffer.name, "+" + (server != null ? server.MODE_OP : "o") + " " + selected_user.nick); } else if (items[item].equals("Deop")) { conn.mode(buffer.cid, buffer.name, "-" + (server != null ? server.MODE_OP : "o") + " " + selected_user.nick); } else if (items[item].equals("Kick")) { view = getDialogTextPrompt(); prompt = (TextView) view.findViewById(R.id.prompt); input = (EditText) view.findViewById(R.id.textInput); input.setText(""); prompt.setText("Give a reason for kicking"); builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")"); builder.setView(view); builder.setPositiveButton("Kick", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { conn.kick(buffer.cid, buffer.name, selected_user.nick, input.getText().toString()); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MainActivity.this); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } else if (items[item].equals("Ban")) { view = getDialogTextPrompt(); prompt = (TextView) view.findViewById(R.id.prompt); input = (EditText) view.findViewById(R.id.textInput); input.setText("*!" + selected_user.hostmask); prompt.setText("Add a banmask for " + selected_user.nick); builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")"); builder.setView(view); builder.setPositiveButton("Ban", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { conn.mode(buffer.cid, buffer.name, "+b " + input.getText().toString()); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MainActivity.this); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } dialogInterface.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.setOwnerActivity(this); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { MessageViewFragment mvf = (MessageViewFragment) getSupportFragmentManager() .findFragmentById(R.id.messageViewFragment); if (mvf != null) mvf.longPressOverride = false; } }); dialog.show(); }