Example usage for android.app AlertDialog.Builder setIcon

List of usage examples for android.app AlertDialog.Builder setIcon

Introduction

In this page you can find the example usage for android.app AlertDialog.Builder setIcon.

Prototype

public void setIcon(Drawable icon) 

Source Link

Usage

From source file:im.neon.activity.CommonActivityUtils.java

/**
 * Check if the permissions provided in the list are granted.
 * This is an asynchronous method if permissions are requested, the final response
 * is provided in onRequestPermissionsResult(). In this case checkPermissions()
 * returns false.//from w w w .jav  a 2s  .c  om
 * <br>If checkPermissions() returns true, the permissions were already granted.
 * The permissions to be granted are given as bit map in aPermissionsToBeGrantedBitMap (ex: {@link #REQUEST_CODE_PERMISSION_TAKE_PHOTO}).
 * <br>aPermissionsToBeGrantedBitMap is passed as the request code in onRequestPermissionsResult().
 * <p>
 * If a permission was already denied by the user, a popup is displayed to
 * explain why vector needs the corresponding permission.
 *
 * @param aPermissionsToBeGrantedBitMap the permissions bit map to be granted
 * @param aCallingActivity              the calling Activity that is requesting the permissions
 * @return true if the permissions are granted (synchronous flow), false otherwise (asynchronous flow)
 */
public static boolean checkPermissions(final int aPermissionsToBeGrantedBitMap,
        final Activity aCallingActivity) {
    boolean isPermissionGranted = false;

    // sanity check
    if (null == aCallingActivity) {
        Log.w(LOG_TAG, "## checkPermissions(): invalid input data");
        isPermissionGranted = false;
    } else if (REQUEST_CODE_PERMISSION_BY_PASS == aPermissionsToBeGrantedBitMap) {
        isPermissionGranted = true;
    } else if ((REQUEST_CODE_PERMISSION_TAKE_PHOTO != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_AUDIO_IP_CALL != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_VIDEO_IP_CALL != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_MEMBERS_SEARCH != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_HOME_ACTIVITY != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_MEMBER_DETAILS != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_ROOM_DETAILS != aPermissionsToBeGrantedBitMap)) {
        Log.w(LOG_TAG, "## checkPermissions(): permissions to be granted are not supported");
        isPermissionGranted = false;
    } else {
        List<String> permissionListAlreadyDenied = new ArrayList<>();
        List<String> permissionsListToBeGranted = new ArrayList<>();
        final List<String> finalPermissionsListToBeGranted;
        boolean isRequestPermissionRequired = false;
        Resources resource = aCallingActivity.getResources();
        String explanationMessage = "";
        String permissionType;

        // retrieve the permissions to be granted according to the request code bit map
        if (PERMISSION_CAMERA == (aPermissionsToBeGrantedBitMap & PERMISSION_CAMERA)) {
            permissionType = Manifest.permission.CAMERA;
            isRequestPermissionRequired |= updatePermissionsToBeGranted(aCallingActivity,
                    permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
        }

        if (PERMISSION_RECORD_AUDIO == (aPermissionsToBeGrantedBitMap & PERMISSION_RECORD_AUDIO)) {
            permissionType = Manifest.permission.RECORD_AUDIO;
            isRequestPermissionRequired |= updatePermissionsToBeGranted(aCallingActivity,
                    permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
        }

        if (PERMISSION_WRITE_EXTERNAL_STORAGE == (aPermissionsToBeGrantedBitMap
                & PERMISSION_WRITE_EXTERNAL_STORAGE)) {
            permissionType = Manifest.permission.WRITE_EXTERNAL_STORAGE;
            isRequestPermissionRequired |= updatePermissionsToBeGranted(aCallingActivity,
                    permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
        }

        // the contact book access is requested for any android platforms
        // for android M, we use the system preferences
        // for android < M, we use a dedicated settings
        if (PERMISSION_READ_CONTACTS == (aPermissionsToBeGrantedBitMap & PERMISSION_READ_CONTACTS)) {
            permissionType = Manifest.permission.READ_CONTACTS;

            if (Build.VERSION.SDK_INT >= 23) {
                isRequestPermissionRequired |= updatePermissionsToBeGranted(aCallingActivity,
                        permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
            } else {
                if (!ContactsManager.getInstance().isContactBookAccessRequested()) {
                    isRequestPermissionRequired = true;
                    permissionsListToBeGranted.add(permissionType);
                }
            }
        }

        finalPermissionsListToBeGranted = permissionsListToBeGranted;

        // if some permissions were already denied: display a dialog to the user before asking again..
        // if some permissions were already denied: display a dialog to the user before asking again..
        if (!permissionListAlreadyDenied.isEmpty()) {
            if (null != resource) {
                // add the user info text to be displayed to explain why the permission is required by the App
                if (aPermissionsToBeGrantedBitMap == REQUEST_CODE_PERMISSION_VIDEO_IP_CALL
                        || aPermissionsToBeGrantedBitMap == REQUEST_CODE_PERMISSION_AUDIO_IP_CALL) {
                    // Permission request for VOIP call
                    if (permissionListAlreadyDenied.contains(Manifest.permission.CAMERA)
                            && permissionListAlreadyDenied.contains(Manifest.permission.RECORD_AUDIO)) {
                        // Both missing
                        explanationMessage += resource
                                .getString(R.string.permissions_rationale_msg_camera_and_audio);
                    } else if (permissionListAlreadyDenied.contains(Manifest.permission.RECORD_AUDIO)) {
                        // Audio missing
                        explanationMessage += resource
                                .getString(R.string.permissions_rationale_msg_record_audio);
                        explanationMessage += resource
                                .getString(R.string.permissions_rationale_msg_record_audio_explanation);
                    } else if (permissionListAlreadyDenied.contains(Manifest.permission.CAMERA)) {
                        // Camera missing
                        explanationMessage += resource.getString(R.string.permissions_rationale_msg_camera);
                        explanationMessage += resource
                                .getString(R.string.permissions_rationale_msg_camera_explanation);
                    }
                } else {
                    for (String permissionAlreadyDenied : permissionListAlreadyDenied) {
                        if (Manifest.permission.CAMERA.equals(permissionAlreadyDenied)) {
                            if (!TextUtils.isEmpty(explanationMessage)) {
                                explanationMessage += "\n\n";
                            }
                            explanationMessage += resource.getString(R.string.permissions_rationale_msg_camera);
                        } else if (Manifest.permission.RECORD_AUDIO.equals(permissionAlreadyDenied)) {
                            if (!TextUtils.isEmpty(explanationMessage)) {
                                explanationMessage += "\n\n";
                            }
                            explanationMessage += resource
                                    .getString(R.string.permissions_rationale_msg_record_audio);
                        } else if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permissionAlreadyDenied)) {
                            if (!TextUtils.isEmpty(explanationMessage)) {
                                explanationMessage += "\n\n";
                            }
                            explanationMessage += resource
                                    .getString(R.string.permissions_rationale_msg_storage);
                        } else if (Manifest.permission.READ_CONTACTS.equals(permissionAlreadyDenied)) {
                            if (!TextUtils.isEmpty(explanationMessage)) {
                                explanationMessage += "\n\n";
                            }
                            explanationMessage += resource
                                    .getString(R.string.permissions_rationale_msg_contacts);
                        } else {
                            Log.d(LOG_TAG, "## checkPermissions(): already denied permission not supported");
                        }
                    }
                }
            } else { // fall back if resource is null.. very unlikely
                explanationMessage = "You are about to be asked to grant permissions..\n\n";
            }

            // display the dialog with the info text
            AlertDialog.Builder permissionsInfoDialog = new AlertDialog.Builder(aCallingActivity);
            if (null != resource) {
                permissionsInfoDialog.setTitle(resource.getString(R.string.permissions_rationale_popup_title));
            }

            permissionsInfoDialog.setMessage(explanationMessage);
            permissionsInfoDialog.setPositiveButton(aCallingActivity.getString(R.string.ok),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!finalPermissionsListToBeGranted.isEmpty()) {
                                ActivityCompat.requestPermissions(aCallingActivity,
                                        finalPermissionsListToBeGranted
                                                .toArray(new String[finalPermissionsListToBeGranted.size()]),
                                        aPermissionsToBeGrantedBitMap);
                            }
                        }
                    });

            Dialog dialog = permissionsInfoDialog.show();

            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    CommonActivityUtils.displayToast(aCallingActivity,
                            aCallingActivity.getString(R.string.missing_permissions_warning));
                }
            });

        } else {
            // some permissions are not granted, ask permissions
            if (isRequestPermissionRequired) {
                final String[] fPermissionsArrayToBeGranted = finalPermissionsListToBeGranted
                        .toArray(new String[finalPermissionsListToBeGranted.size()]);

                // for android < M, we use a custom dialog to request the contacts book access.
                if (permissionsListToBeGranted.contains(Manifest.permission.READ_CONTACTS)
                        && (Build.VERSION.SDK_INT < 23)) {
                    AlertDialog.Builder permissionsInfoDialog = new AlertDialog.Builder(aCallingActivity);
                    permissionsInfoDialog.setIcon(android.R.drawable.ic_dialog_info);

                    if (null != resource) {
                        permissionsInfoDialog
                                .setTitle(resource.getString(R.string.permissions_rationale_popup_title));
                    }

                    permissionsInfoDialog.setMessage(
                            resource.getString(R.string.permissions_msg_contacts_warning_other_androids));

                    // gives the contacts book access
                    permissionsInfoDialog.setPositiveButton(aCallingActivity.getString(R.string.yes),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    ContactsManager.getInstance().setIsContactBookAccessAllowed(true);
                                    ActivityCompat.requestPermissions(aCallingActivity,
                                            fPermissionsArrayToBeGranted, aPermissionsToBeGrantedBitMap);
                                }
                            });

                    // or reject it
                    permissionsInfoDialog.setNegativeButton(aCallingActivity.getString(R.string.no),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    ContactsManager.getInstance().setIsContactBookAccessAllowed(false);
                                    ActivityCompat.requestPermissions(aCallingActivity,
                                            fPermissionsArrayToBeGranted, aPermissionsToBeGrantedBitMap);
                                }
                            });

                    permissionsInfoDialog.show();

                } else {
                    ActivityCompat.requestPermissions(aCallingActivity, fPermissionsArrayToBeGranted,
                            aPermissionsToBeGrantedBitMap);
                }
            } else {
                // permissions were granted, start now..
                isPermissionGranted = true;
            }
        }
    }
    return isPermissionGranted;
}

From source file:org.distantshoresmedia.keyboard.LatinIME.java

private void showOptionsMenu() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setCancelable(true);//from   w w  w.j  av  a2s. co  m
    builder.setIcon(R.drawable.ic_dialog_keyboard);
    builder.setNegativeButton(android.R.string.cancel, null);
    CharSequence itemSettings = getString(R.string.english_ime_settings);
    CharSequence itemInputMethod = getString(R.string.selectInputMethod);
    builder.setItems(new CharSequence[] { itemInputMethod, itemSettings },
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface di, int position) {
                    di.dismiss();
                    switch (position) {
                    case POS_SETTINGS:
                        launchSettings();
                        break;
                    case POS_METHOD:
                        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).showInputMethodPicker();
                        break;
                    }
                }
            });
    builder.setTitle(mResources.getString(R.string.english_ime_input_options));
    mOptionsDialog = builder.create();
    Window window = mOptionsDialog.getWindow();
    WindowManager.LayoutParams lp = window.getAttributes();
    lp.token = mKeyboardSwitcher.getInputView().getWindowToken();
    lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
    window.setAttributes(lp);
    window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    mOptionsDialog.show();
}

From source file:com.smc.tw.waltz.MainActivity.java

private void showNewAccessCodeDialog(WaltzDevice device) {
    if (DEBUG)//from   w w  w.  ja  v a2s .  c o  m
        Log.d(TAG, "showNewAccessCodeDialog d:" + device);

    if (mNewAccessCodeDialog != null) {
        mNewAccessCodeDialog.dismiss();
    }

    LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
    View dialogView = inflater.inflate(R.layout.dialog_access_code_new, null);

    AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.WaltzDialog);

    final TextView firstTextView = (TextView) dialogView.findViewById(R.id.new_first_access_code_text);
    final TextView secondTextView = (TextView) dialogView.findViewById(R.id.new_second_access_code_text);
    final PinEditText firstView = (PinEditText) dialogView.findViewById(R.id.new_first_access_code_view);
    final PinEditText secondView = (PinEditText) dialogView.findViewById(R.id.new_second_access_code_view);

    firstView.requestFocus();

    String name = device.getName();

    firstTextView.setText(getString(R.string.dialog_access_code_new) + " " + name);
    secondTextView.setText(getString(R.string.dialog_access_code_again));

    builder.setIcon(R.drawable.ic_launcher);
    builder.setTitle(R.string.dialog_access_code);
    builder.setView(dialogView);
    builder.setCancelable(false);

    builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int id) {
            String firstText = firstView.getText().toString();
            String secondText = secondView.getText().toString();

            if (firstText == null || secondText == null || !firstText.equals(secondText)) {
                showAccessCodeNotMatchDialog();
                return;
            }

            device.changeAccessCode(firstText);
        }
    });

    builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int id) {
        }
    });

    mNewAccessCodeDialog = builder.create();

    firstView.setOnPinListener(new PinEditText.OnPinListener() {
        @Override
        public void onPincodeDone() {
            if (DEBUG)
                Log.d(TAG, "showNewAccessCodeDialog ft:" + firstView.getText().toString());

            secondView.requestFocus();
        }
    });

    secondView.setOnPinListener(new PinEditText.OnPinListener() {
        @Override
        public void onPincodeDone() {
            if (DEBUG)
                Log.d(TAG, "showNewAccessCodeDialog st:" + secondView.getText().toString());
        }
    });

    mNewAccessCodeDialog.show();
}

From source file:im.neon.activity.VectorRoomActivity.java

/**
 * Display a dialog box to indicate that the conf call can no be performed.
 * <p>See {@link #isUserAllowedToStartConfCall()}
 *///from   w w w .j a  v  a  2s . co  m
private void displayConfCallNotAllowed() {
    // display the dialog with the info text
    AlertDialog.Builder permissionsInfoDialog = new AlertDialog.Builder(VectorRoomActivity.this);
    Resources resource = getResources();

    if ((null != resource) && (null != permissionsInfoDialog)) {
        permissionsInfoDialog
                .setTitle(resource.getString(R.string.missing_permissions_title_to_start_conf_call));
        permissionsInfoDialog.setMessage(resource.getString(R.string.missing_permissions_to_start_conf_call));

        permissionsInfoDialog.setIcon(android.R.drawable.ic_dialog_alert);
        permissionsInfoDialog.setPositiveButton(resource.getString(R.string.ok), null);
        permissionsInfoDialog.show();
    } else {
        Log.e(LOG_TAG, "## displayConfCallNotAllowed(): impossible to create dialog");
    }
}

From source file:im.neon.activity.VectorRoomActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_vector_room);

    if (CommonActivityUtils.shouldRestartApp(this)) {
        Log.e(LOG_TAG, "onCreate : Restart the application.");
        CommonActivityUtils.restartApp(this);
        return;/*from w  w w .j  a  va2s.  c  o  m*/
    }

    final Intent intent = getIntent();
    if (!intent.hasExtra(EXTRA_ROOM_ID)) {
        Log.e(LOG_TAG, "No room ID extra.");
        finish();
        return;
    }

    mSession = MXCActionBarActivity.getSession(this, intent);

    if (mSession == null) {
        Log.e(LOG_TAG, "No MXSession.");
        finish();
        return;
    }

    String roomId = intent.getStringExtra(EXTRA_ROOM_ID);

    // ensure that the preview mode is really expected
    if (!intent.hasExtra(EXTRA_ROOM_PREVIEW_ID)) {
        sRoomPreviewData = null;
        Matrix.getInstance(this).clearTmpStoresList();
    }

    if (CommonActivityUtils.isGoingToSplash(this, mSession.getMyUserId(), roomId)) {
        Log.d(LOG_TAG, "onCreate : Going to splash screen");
        return;
    }

    //setDragEdge(SwipeBackLayout.DragEdge.LEFT);

    // bind the widgets of the room header view. The room header view is displayed by
    // clicking on the title of the action bar
    mRoomHeaderView = (RelativeLayout) findViewById(R.id.action_bar_header);
    mActionBarHeaderRoomTopic = (TextView) findViewById(R.id.action_bar_header_room_topic);
    mActionBarHeaderRoomName = (TextView) findViewById(R.id.action_bar_header_room_title);
    mActionBarHeaderActiveMembers = (TextView) findViewById(R.id.action_bar_header_room_members);
    mActionBarHeaderRoomAvatar = (ImageView) mRoomHeaderView.findViewById(R.id.avatar_img);
    mActionBarHeaderInviteMemberView = mRoomHeaderView.findViewById(R.id.action_bar_header_invite_members);
    mRoomPreviewLayout = findViewById(R.id.room_preview_info_layout);
    mVectorPendingCallView = (VectorPendingCallView) findViewById(R.id.room_pending_call_view);
    mVectorOngoingConferenceCallView = (VectorOngoingConferenceCallView) findViewById(
            R.id.room_ongoing_conference_call_view);
    mE2eImageView = (ImageView) findViewById(R.id.room_encrypted_image_view);

    // hide the header room as soon as the bottom layout (text edit zone) is touched
    findViewById(R.id.room_bottom_layout).setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            enableActionBarHeader(HIDE_ACTION_BAR_HEADER);
            return false;
        }
    });

    // use a toolbar instead of the actionbar
    // to be able to display an expandable header
    mToolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.room_toolbar);
    this.setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // set the default custom action bar layout,
    // that will be displayed from the custom action bar layout
    setActionBarDefaultCustomLayout();

    mCallId = intent.getStringExtra(EXTRA_START_CALL_ID);
    mEventId = intent.getStringExtra(EXTRA_EVENT_ID);
    mDefaultRoomName = intent.getStringExtra(EXTRA_DEFAULT_NAME);
    mDefaultTopic = intent.getStringExtra(EXTRA_DEFAULT_TOPIC);

    // the user has tapped on the "View" notification button
    if ((null != intent.getAction()) && (intent.getAction().startsWith(NotificationUtils.TAP_TO_VIEW_ACTION))) {
        // remove any pending notifications
        NotificationManager notificationsManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationsManager.cancelAll();
    }

    Log.d(LOG_TAG, "Displaying " + roomId);

    mEditText = (EditText) findViewById(R.id.editText_messageBox);

    // hide the header room as soon as the message input text area is touched
    mEditText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            enableActionBarHeader(HIDE_ACTION_BAR_HEADER);
        }
    });

    // IME's DONE button is treated as a send action
    mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
            int imeActionId = actionId & EditorInfo.IME_MASK_ACTION;

            if (EditorInfo.IME_ACTION_DONE == imeActionId) {
                sendTextMessage();
            }

            return false;
        }
    });

    mSendingMessagesLayout = findViewById(R.id.room_sending_message_layout);
    mSendImageView = (ImageView) findViewById(R.id.room_send_image_view);
    mSendButtonLayout = findViewById(R.id.room_send_layout);
    mSendButtonLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!TextUtils.isEmpty(mEditText.getText())) {
                sendTextMessage();
            } else {
                // hide the header room
                enableActionBarHeader(HIDE_ACTION_BAR_HEADER);

                FragmentManager fm = getSupportFragmentManager();
                IconAndTextDialogFragment fragment = (IconAndTextDialogFragment) fm
                        .findFragmentByTag(TAG_FRAGMENT_ATTACHMENTS_DIALOG);

                if (fragment != null) {
                    fragment.dismissAllowingStateLoss();
                }

                final Integer[] messages = new Integer[] { R.string.option_send_files,
                        R.string.option_take_photo_video, };

                final Integer[] icons = new Integer[] { R.drawable.ic_material_file, // R.string.option_send_files
                        R.drawable.ic_material_camera, // R.string.option_take_photo
                };

                fragment = IconAndTextDialogFragment.newInstance(icons, messages, null,
                        ContextCompat.getColor(VectorRoomActivity.this, R.color.vector_text_black_color));
                fragment.setOnClickListener(new IconAndTextDialogFragment.OnItemClickListener() {
                    @Override
                    public void onItemClick(IconAndTextDialogFragment dialogFragment, int position) {
                        Integer selectedVal = messages[position];

                        if (selectedVal == R.string.option_send_files) {
                            VectorRoomActivity.this.launchFileSelectionIntent();
                        } else if (selectedVal == R.string.option_take_photo_video) {
                            if (CommonActivityUtils.checkPermissions(
                                    CommonActivityUtils.REQUEST_CODE_PERMISSION_TAKE_PHOTO,
                                    VectorRoomActivity.this)) {
                                launchCamera();
                            }
                        }
                    }
                });

                fragment.show(fm, TAG_FRAGMENT_ATTACHMENTS_DIALOG);
            }
        }
    });

    mEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(android.text.Editable s) {
            if (null != mRoom) {
                MXLatestChatMessageCache latestChatMessageCache = VectorRoomActivity.this.mLatestChatMessageCache;
                String textInPlace = latestChatMessageCache.getLatestText(VectorRoomActivity.this,
                        mRoom.getRoomId());

                // check if there is really an update
                // avoid useless updates (initializations..)
                if (!mIgnoreTextUpdate && !textInPlace.equals(mEditText.getText().toString())) {
                    latestChatMessageCache.updateLatestMessage(VectorRoomActivity.this, mRoom.getRoomId(),
                            mEditText.getText().toString());
                    handleTypingNotification(mEditText.getText().length() != 0);
                }

                manageSendMoreButtons();
                refreshCallButtons();
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    mVectorPendingCallView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            IMXCall call = VectorCallViewActivity.getActiveCall();
            if (null != call) {
                final Intent intent = new Intent(VectorRoomActivity.this, VectorCallViewActivity.class);
                intent.putExtra(VectorCallViewActivity.EXTRA_MATRIX_ID,
                        call.getSession().getCredentials().userId);
                intent.putExtra(VectorCallViewActivity.EXTRA_CALL_ID, call.getCallId());

                VectorRoomActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        VectorRoomActivity.this.startActivity(intent);
                    }
                });
            } else {
                // if the call is no more active, just remove the view
                mVectorPendingCallView.onCallTerminated();
            }
        }
    });

    mActionBarHeaderInviteMemberView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchRoomDetails(VectorRoomDetailsActivity.PEOPLE_TAB_INDEX);
        }
    });

    // notifications area
    mNotificationsArea = findViewById(R.id.room_notifications_area);
    mNotificationIconImageView = (ImageView) mNotificationsArea.findViewById(R.id.room_notification_icon);
    mNotificationTextView = (TextView) mNotificationsArea.findViewById(R.id.room_notification_message);

    mCanNotPostTextView = findViewById(R.id.room_cannot_post_textview);

    // increase the clickable area to open the keyboard.
    // when there is no text, it is quite small and some user thought the edition was disabled.
    findViewById(R.id.room_sending_message_layout).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mEditText.requestFocus()) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(mEditText, InputMethodManager.SHOW_IMPLICIT);
            }
        }
    });

    mStartCallLayout = findViewById(R.id.room_start_call_layout);
    mStartCallLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if ((null != mRoom) && mRoom.isEncrypted() && (mRoom.getActiveMembers().size() > 2)) {
                // display the dialog with the info text
                AlertDialog.Builder permissionsInfoDialog = new AlertDialog.Builder(VectorRoomActivity.this);
                Resources resource = getResources();
                permissionsInfoDialog
                        .setMessage(resource.getString(R.string.room_no_conference_call_in_encrypted_rooms));
                permissionsInfoDialog.setIcon(android.R.drawable.ic_dialog_alert);
                permissionsInfoDialog.setPositiveButton(resource.getString(R.string.ok), null);
                permissionsInfoDialog.show();

            } else if (isUserAllowedToStartConfCall()) {
                displayVideoCallIpDialog();
            } else {
                displayConfCallNotAllowed();
            }
        }
    });

    mStopCallLayout = findViewById(R.id.room_end_call_layout);
    mStopCallLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            IMXCall call = mSession.mCallsManager.getCallWithRoomId(mRoom.getRoomId());

            if (null != call) {
                call.hangup(null);
            }
        }
    });

    findViewById(R.id.room_button_margin_right).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // extend the right side of right button
            // to avoid clicking in the void
            if (mStopCallLayout.getVisibility() == View.VISIBLE) {
                mStopCallLayout.performClick();
            } else if (mStartCallLayout.getVisibility() == View.VISIBLE) {
                mStartCallLayout.performClick();
            } else if (mSendButtonLayout.getVisibility() == View.VISIBLE) {
                mSendButtonLayout.performClick();
            }
        }
    });

    mMyUserId = mSession.getCredentials().userId;

    CommonActivityUtils.resumeEventStream(this);

    mRoom = mSession.getDataHandler().getRoom(roomId, false);

    FragmentManager fm = getSupportFragmentManager();
    mVectorMessageListFragment = (VectorMessageListFragment) fm
            .findFragmentByTag(TAG_FRAGMENT_MATRIX_MESSAGE_LIST);

    if (mVectorMessageListFragment == null) {
        Log.d(LOG_TAG, "Create VectorMessageListFragment");

        // this fragment displays messages and handles all message logic
        mVectorMessageListFragment = VectorMessageListFragment.newInstance(mMyUserId, roomId, mEventId,
                (null == sRoomPreviewData) ? null : VectorMessageListFragment.PREVIEW_MODE_READ_ONLY,
                org.matrix.androidsdk.R.layout.fragment_matrix_message_list_fragment);
        fm.beginTransaction().add(R.id.anchor_fragment_messages, mVectorMessageListFragment,
                TAG_FRAGMENT_MATRIX_MESSAGE_LIST).commit();
    } else {
        Log.d(LOG_TAG, "Reuse VectorMessageListFragment");
    }

    mVectorRoomMediasSender = new VectorRoomMediasSender(this, mVectorMessageListFragment,
            Matrix.getInstance(this).getMediasCache());
    mVectorRoomMediasSender.onRestoreInstanceState(savedInstanceState);

    manageRoomPreview();

    addRoomHeaderClickListeners();

    // in timeline mode (i.e search in the forward and backward room history)
    // or in room preview mode
    // the edition items are not displayed
    if (!TextUtils.isEmpty(mEventId) || (null != sRoomPreviewData)) {
        mNotificationsArea.setVisibility(View.GONE);
        findViewById(R.id.bottom_separator).setVisibility(View.GONE);
        findViewById(R.id.room_notification_separator).setVisibility(View.GONE);
        findViewById(R.id.room_notifications_area).setVisibility(View.GONE);

        View v = findViewById(R.id.room_bottom_layout);
        ViewGroup.LayoutParams params = v.getLayoutParams();
        params.height = 0;
        v.setLayoutParams(params);
    }

    mLatestChatMessageCache = Matrix.getInstance(this).getDefaultLatestChatMessageCache();

    // some medias must be sent while opening the chat
    if (intent.hasExtra(EXTRA_ROOM_INTENT)) {
        final Intent mediaIntent = intent.getParcelableExtra(EXTRA_ROOM_INTENT);

        // sanity check
        if (null != mediaIntent) {
            mEditText.postDelayed(new Runnable() {
                @Override
                public void run() {
                    intent.removeExtra(EXTRA_ROOM_INTENT);
                    sendMediasIntent(mediaIntent);
                }
            }, 1000);
        }
    }

    mVectorOngoingConferenceCallView.initRoomInfo(mSession, mRoom);
    mVectorOngoingConferenceCallView
            .setCallClickListener(new VectorOngoingConferenceCallView.ICallClickListener() {

                private void startCall(boolean isVideo) {
                    if (CommonActivityUtils.checkPermissions(
                            isVideo ? CommonActivityUtils.REQUEST_CODE_PERMISSION_VIDEO_IP_CALL
                                    : CommonActivityUtils.REQUEST_CODE_PERMISSION_AUDIO_IP_CALL,
                            VectorRoomActivity.this)) {
                        startIpCall(isVideo);
                    }
                }

                @Override
                public void onVoiceCallClick() {
                    startCall(false);
                }

                @Override
                public void onVideoCallClick() {
                    startCall(true);
                }
            });

    View avatarLayout = findViewById(R.id.room_self_avatar);

    if (null != avatarLayout) {
        mAvatarImageView = (ImageView) avatarLayout.findViewById(R.id.avatar_img);
    }

    refreshSelfAvatar();

    // in case a "Send as" dialog was in progress when the activity was destroyed (life cycle)
    mVectorRoomMediasSender.resumeResizeMediaAndSend();

    // header visibility has launched
    enableActionBarHeader(intent.getBooleanExtra(EXTRA_EXPAND_ROOM_HEADER, false) ? SHOW_ACTION_BAR_HEADER
            : HIDE_ACTION_BAR_HEADER);

    // the both flags are only used once
    intent.removeExtra(EXTRA_EXPAND_ROOM_HEADER);

    Log.d(LOG_TAG, "End of create");
}

From source file:com.android.mms.ui.ComposeMessageActivity.java

private void showAddAttachmentDialog(final boolean replace) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setIcon(R.drawable.ic_dialog_attach);
    builder.setTitle(R.string.add_attachment);

    if (mAttachmentTypeSelectorAdapter == null) {
        mAttachmentTypeSelectorAdapter = new AttachmentTypeSelectorAdapter(this,
                AttachmentTypeSelectorAdapter.MODE_WITH_SLIDESHOW);
    }/*from w  w  w  . ja v a  2s . c  om*/
    builder.setAdapter(mAttachmentTypeSelectorAdapter, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            addAttachment(mAttachmentTypeSelectorAdapter.buttonToCommand(which), replace);
            dialog.dismiss();
        }
    });

    builder.show();
}

From source file:org.nla.tarotdroid.lib.ui.GameSetHistoryActivity.java

/**
 * Manage click on GameSet./*from  ww w .j a v a2  s.  co  m*/
 * 
 * @param pos
 */
private void onListItemClick(final int pos) {
    final GameSet gameSet = (GameSet) getListAdapter().getItem(pos);

    final Item[] items = AppContext.getApplication().isAppLimited() ? limitedItems : allItems;

    ListAdapter adapter = new ArrayAdapter<Item>(this, android.R.layout.select_dialog_item, android.R.id.text1,
            items) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // User super class to create the View
            View v = super.getView(position, convertView, parent);
            TextView tv = (TextView) v.findViewById(android.R.id.text1);

            // Put the image on the TextView
            tv.setCompoundDrawablesWithIntrinsicBounds(items[position].icon, 0, 0, 0);

            // Add margin between image and text (support various screen
            // densities)
            int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
            tv.setCompoundDrawablePadding(dp5);

            return v;
        }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(String.format(this.getString(R.string.lblGameSetHistoryActivityMenuTitle),
            new SimpleDateFormat("dd/MM/yy").format(gameSet.getCreationTs())));

    builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int itemIndex) {

            Item item = items[itemIndex];

            if (item.itemType == Item.ItemTypes.publishOnFacebook) {

                // check for active internet connexion first
                // see post
                // http://stackoverflow.com/questions/2789612/how-can-i-check-whether-an-android-device-is-connected-to-the-web
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
                        Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                if (networkInfo != null && networkInfo.isConnected()) {

                    if (gameSet.getGameCount() == 0) {
                        Toast.makeText(GameSetHistoryActivity.this,
                                R.string.lblFacebookImpossibleToPublishGamesetWithNoGame, Toast.LENGTH_SHORT)
                                .show();
                    }

                    else if (!AppContext.getApplication().getNotificationIds().isEmpty()) {
                        Toast.makeText(GameSetHistoryActivity.this, R.string.lblFacebookGamesetBeingPublished,
                                Toast.LENGTH_SHORT).show();
                    }

                    else {
                        tempGameSet = gameSet;

                        // // TODO Improve in later version
                        // ShortenUrlTask shortenUrlTask = new
                        // ShortenUrlTask(FacebookHelper.buildGameSetUrl(tempGameSet));
                        // shortenUrlTask.setCallback(urlShortenedCallback);
                        // shortenUrlTask.execute();

                        startPostProcess();
                    }
                } else {
                    Toast.makeText(GameSetHistoryActivity.this,
                            getString(R.string.titleInternetConnexionNecessary), Toast.LENGTH_LONG).show();
                }
            } else if (item.itemType == Item.ItemTypes.publishOnTwitter) {
                Toast.makeText(GameSetHistoryActivity.this, "TODO: Publish on twitter", Toast.LENGTH_LONG)
                        .show();

                Intent intent = new Intent(GameSetHistoryActivity.this, TwitterConnectActivity.class);
                startActivity(intent);
            } else if (item.itemType == Item.ItemTypes.remove) {
                RemoveGameSetDialogClickListener removeGameSetDialogClickListener = new RemoveGameSetDialogClickListener(
                        gameSet);
                AlertDialog.Builder builder = new AlertDialog.Builder(GameSetHistoryActivity.this);
                builder.setTitle(GameSetHistoryActivity.this.getString(R.string.titleRemoveGameSetYesNo));
                builder.setMessage(Html.fromHtml(
                        GameSetHistoryActivity.this.getText(R.string.msgRemoveGameSetYesNo).toString()));
                builder.setPositiveButton(GameSetHistoryActivity.this.getString(R.string.btnOk),
                        removeGameSetDialogClickListener);
                builder.setNegativeButton(GameSetHistoryActivity.this.getString(R.string.btnCancel),
                        removeGameSetDialogClickListener).show();
                builder.setIcon(android.R.drawable.ic_dialog_alert);
            } else if (item.itemType == Item.ItemTypes.transferOverBluetooth) {
                if (!GameSetHistoryActivity.this.bluetoothHelper.isBluetoothEnabled()) {
                    Toast.makeText(GameSetHistoryActivity.this,
                            GameSetHistoryActivity.this.getString(R.string.msgActivateBluetooth),
                            Toast.LENGTH_LONG).show();
                }

                try {
                    // make sure at least one device was discovered
                    if (GameSetHistoryActivity.this.bluetoothHelper.getBluetoothDeviceCount() == 0) {
                        Toast.makeText(GameSetHistoryActivity.this,
                                GameSetHistoryActivity.this.getString(R.string.msgRunDiscoverDevicesFirst),
                                Toast.LENGTH_LONG).show();
                    }

                    // display devices and download
                    final String[] items = GameSetHistoryActivity.this.bluetoothHelper
                            .getBluetoothDeviceNames();

                    AlertDialog.Builder builder = new AlertDialog.Builder(GameSetHistoryActivity.this);
                    builder.setTitle(GameSetHistoryActivity.this.getString(R.string.lblSelectBluetoothDevice));
                    builder.setItems(items, new BluetoothDeviceClickListener(gameSet, items));
                    AlertDialog alert = builder.create();
                    alert.show();
                } catch (Exception e) {
                    AuditHelper.auditError(ErrorTypes.gameSetHistoryActivityError, e,
                            GameSetHistoryActivity.this);
                }
            } else if (item.itemType == Item.ItemTypes.exportToExcel) {
                try {
                    if (!AppContext.getApplication().isAppLimited()) {

                        ExportToExcelTask task = new ExportToExcelTask(GameSetHistoryActivity.this,
                                progressDialog);
                        task.setCallback(excelExportCallback);
                        task.execute(gameSet);
                    }
                } catch (Exception e) {
                    Toast.makeText(
                            GameSetHistoryActivity.this, AppContext.getApplication().getResources()
                                    .getText(R.string.msgGameSetExportError).toString() + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                    AuditHelper.auditError(ErrorTypes.excelFileStorage, e);
                }
            } else if (item.itemType == Item.ItemTypes.edit) {
                // SharedPreferences preferences =
                // PreferenceManager.getDefaultSharedPreferences(GameSetHistoryActivity.this);

                // set selected gameset as session gameset
                // AppContext.getApplication().getBizService().setGameSet(gameSet);

                // // Get non DAL stored parameters property from shared
                // preferences
                // UIHelper.fillNonComputationPreferences(gameSet.getGameSetParameters(),
                // preferences);

                // start tab gameset activity
                Intent intent = new Intent(GameSetHistoryActivity.this, TabGameSetActivity.class);
                intent.putExtra(ActivityParams.PARAM_GAMESET_ID, gameSet.getId());
                GameSetHistoryActivity.this.startActivityForResult(intent, RequestCodes.DISPLAY_WITH_FACEBOOK);
            }
        }
    });
    AlertDialog alert = builder.create();
    alert.show();

}