Example usage for android.widget ToggleButton setOnCheckedChangeListener

List of usage examples for android.widget ToggleButton setOnCheckedChangeListener

Introduction

In this page you can find the example usage for android.widget ToggleButton setOnCheckedChangeListener.

Prototype

public void setOnCheckedChangeListener(@Nullable OnCheckedChangeListener listener) 

Source Link

Document

Register a callback to be invoked when the checked state of this button changes.

Usage

From source file:com.concavenp.artistrymuse.fragments.ProjectDetailsFragment.java

private void updateUserDetails(User model) {

    mUserModel = model;/*from   w w w.jav a  2 s.  c o m*/

    // If there is model data then show the details otherwise tell the user to choose something
    if (mUserModel != null) {

        // The favorite/unfavorite toggle button
        final ToggleButton favoriteButton = getView().findViewById(R.id.favorite_un_favorite_toggleButton);

        // Determine the initial state of the button given the user's list of "favorites"
        final Map<String, Favorite> favorites = mUserModel.getFavorites();

        // Set the initial state of the button
        if (favorites.containsKey(mUidForDetails)) {

            favoriteInQuestion = favorites.get(mUidForDetails);

            favoriteButton.setChecked(true);

        } else {

            favoriteInQuestion = null;

            favoriteButton.setChecked(false);

        }

        favoriteButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {

                    // The new object that will be added to the DB
                    favoriteInQuestion = new Favorite();
                    favoriteInQuestion.setFavoritedDate(new Date().getTime());
                    favoriteInQuestion.setRating(new Random().nextDouble() * 10.0);
                    favoriteInQuestion.setUid(mUidForDetails);

                    // Add the Project in question to the map of projects the user has favorited
                    mDatabase.child(USERS.getType()).child(getUid()).child(User.FAVORITES).child(mUidForDetails)
                            .setValue(favoriteInQuestion);

                    // Create a has map of the values updates to the Project in question
                    Map<String, Object> childUpdates = new HashMap<>();

                    // Update the ratings count for the project in question
                    int ratingCount = mProjectInQuestionModel.getRatingsCount() + 1;
                    childUpdates.put(
                            getString(R.string.firebase_separator) + PROJECTS.getType()
                                    + getString(R.string.firebase_separator) + mUidForDetails
                                    + getString(R.string.firebase_separator) + Project.RATINGS_COUNT,
                            ratingCount);

                    // Update the rating for the project in question
                    double newRating = ((mProjectInQuestionModel.getRating()
                            * mProjectInQuestionModel.getRatingsCount()) + favoriteInQuestion.getRating())
                            / ratingCount;
                    childUpdates.put(getString(R.string.firebase_separator) + PROJECTS.getType()
                            + getString(R.string.firebase_separator) + mUidForDetails
                            + getString(R.string.firebase_separator) + Project.RATING, newRating);

                    // Update the Favorited count
                    int favoritedCount = mProjectInQuestionModel.getFavorited() + 1;
                    childUpdates.put(
                            getString(R.string.firebase_separator) + PROJECTS.getType()
                                    + getString(R.string.firebase_separator) + mUidForDetails
                                    + getString(R.string.firebase_separator) + Project.FAVORITED,
                            favoritedCount);

                    // Update the Project in question
                    mDatabase.updateChildren(childUpdates);

                } else {

                    // Only perform the operation if it appears that we have favorited this project before
                    if (favoriteInQuestion != null) {

                        // Create a has map of the values updates to the Project in question
                        Map<String, Object> childUpdates = new HashMap<>();

                        // Update the ratings count for the project in question
                        int ratingCount = mProjectInQuestionModel.getRatingsCount() - 1;
                        childUpdates.put(
                                getString(R.string.firebase_separator) + PROJECTS.getType()
                                        + getString(R.string.firebase_separator) + mUidForDetails
                                        + getString(R.string.firebase_separator) + Project.RATINGS_COUNT,
                                ratingCount);

                        // Update the rating for the project in question
                        double newRating = ((mProjectInQuestionModel.getRating()
                                * mProjectInQuestionModel.getRatingsCount()) - favoriteInQuestion.getRating())
                                / ratingCount;
                        if (Double.isNaN(newRating)) {
                            newRating = 0.0;
                        }
                        childUpdates.put(getString(R.string.firebase_separator) + PROJECTS.getType()
                                + getString(R.string.firebase_separator) + mUidForDetails
                                + getString(R.string.firebase_separator) + Project.RATING, newRating);

                        // Update the Favorited count
                        int favoritedCount = mProjectInQuestionModel.getFavorited() - 1;
                        childUpdates.put(
                                getString(R.string.firebase_separator) + PROJECTS.getType()
                                        + getString(R.string.firebase_separator) + mUidForDetails
                                        + getString(R.string.firebase_separator) + Project.FAVORITED,
                                favoritedCount);

                        // Update the Project in question
                        mDatabase.updateChildren(childUpdates);

                        // Remove the favorite object in question from the map of people the user is following
                        mDatabase.child(USERS.getType()).child(getUid()).child(User.FAVORITES)
                                .child(mUidForDetails).removeValue();

                        // Clear out the local storage of the favorite object
                        favoriteInQuestion = null;

                    }

                }

            }

        });

    }

}

From source file:com.coinprism.wallet.fragment.BalanceTab.java

/**
 * Constructs the UI when the activity is first rendered.
 *
 * @param rootView the rootView of the fragment
 *//* ww  w .j ava  2s .co  m*/
public void setupUI(final View rootView) {
    final WalletState state = WalletState.getState();

    final TextView addressText = (TextView) rootView.findViewById(R.id.address);
    final ImageView qrCode = (ImageView) rootView.findViewById(R.id.qrAddress);

    final ToggleButton addressTypeSelector = (ToggleButton) rootView.findViewById(R.id.addressTypeSelector);

    final View.OnClickListener enlarge = new View.OnClickListener() {
        // Enlarge the QR code
        @Override
        public void onClick(View view) {
            final QRCodeDialog dialog = new QRCodeDialog();
            if (addressTypeSelector.isChecked()) {
                dialog.configure(WalletState.getState().getConfiguration().getReceiveAssetAddress(),
                        getString(R.string.tab_wallet_dialog_qr_title_assets));
            } else {
                dialog.configure(WalletState.getState().getConfiguration().getAddress(),
                        getString(R.string.tab_wallet_dialog_qr_title_bitcoin));
            }

            dialog.show(BalanceTab.this.getActivity().getSupportFragmentManager(), "");
        }
    };

    LinearLayout addressPanel = (LinearLayout) rootView.findViewById(R.id.addressArea);
    addressPanel.setOnClickListener(enlarge);
    qrCode.setOnClickListener(enlarge);

    addressTypeSelector.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (addressTypeSelector.isChecked()) {
                addressText.setText(state.getConfiguration().getReceiveAssetAddress());
                QRCodeEncoder.createQRCode(state.getConfiguration().getReceiveAssetAddress(), qrCode, 148, 148,
                        8, 0xFFFFFFFF);
            } else {
                addressText.setText(state.getConfiguration().getAddress());
                QRCodeEncoder.createQRCode(state.getConfiguration().getAddress(), qrCode, 148, 148, 8,
                        0xFFFFFFFF);
            }
        }
    });

    addressTypeSelector.setChecked(true);
}

From source file:org.openremote.android.console.AppSettingsActivity.java

/**
 * Creates the auto layout.//from   ww  w.j a v a  2s  .c o  m
 * It contains toggle button to switch auto state, two text view to indicate auto messages.
 * 
 * @return the relative layout
 */
private RelativeLayout createAutoLayout() {
    RelativeLayout autoLayout = new RelativeLayout(this);
    autoLayout.setPadding(10, 5, 10, 10);
    autoLayout.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, 80));
    TextView autoText = new TextView(this);
    RelativeLayout.LayoutParams autoTextLayout = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    autoTextLayout.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    autoTextLayout.addRule(RelativeLayout.CENTER_VERTICAL);
    autoText.setLayoutParams(autoTextLayout);
    autoText.setText("Auto Discovery");

    ToggleButton autoButton = new ToggleButton(this);
    autoButton.setWidth(150);
    RelativeLayout.LayoutParams autoButtonLayout = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    autoButtonLayout.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    autoButtonLayout.addRule(RelativeLayout.CENTER_VERTICAL);
    autoButton.setLayoutParams(autoButtonLayout);
    autoButton.setChecked(autoMode);
    autoButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            appSettingsView.removeViewAt(2);
            currentServer = "";
            if (isChecked) {
                IPAutoDiscoveryServer.isInterrupted = false;
                appSettingsView.addView(constructAutoServersView(), 2);
            } else {
                IPAutoDiscoveryServer.isInterrupted = true;
                appSettingsView.addView(constructCustomServersView(), 2);
            }
            AppSettingsModel.setAutoMode(AppSettingsActivity.this, isChecked);
        }
    });

    TextView infoText = new TextView(this);
    RelativeLayout.LayoutParams infoTextLayout = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    infoTextLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    infoTextLayout.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    infoText.setLayoutParams(infoTextLayout);
    infoText.setTextSize(10);
    infoText.setText("Turn off auto-discovery to input controller url manually.");

    autoLayout.addView(autoText);
    autoLayout.addView(autoButton);
    autoLayout.addView(infoText);
    return autoLayout;
}

From source file:org.openremote.android.console.AppSettingsActivity.java

/**
 * Initializes the SSL related UI widget properties and event handlers to deal with user
 * interactions./*  ww  w . j  a v a2  s. c om*/
 */
private void initSSLState() {
    // Get UI Widget references...

    final ToggleButton sslToggleButton = (ToggleButton) findViewById(R.id.ssl_toggle);
    final EditText sslPortEditField = (EditText) findViewById(R.id.ssl_port);

    final TextView pin = (TextView) findViewById(R.id.ssl_clientcert_pin);

    // Configure UI to current settings state...

    boolean sslEnabled = AppSettingsModel.isSSLEnabled(this);

    sslToggleButton.setChecked(sslEnabled);
    sslPortEditField.setText("" + AppSettingsModel.getSSLPort(this));

    // If SSL is off, disable the port edit field by default...

    if (!sslEnabled) {
        sslPortEditField.setEnabled(false);
        sslPortEditField.setFocusable(false);
        sslPortEditField.setFocusableInTouchMode(false);
    }

    // Manage state changes to SSL toggle...

    sslToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isEnabled) {

            // If SSL is being disabled, and the user had soft keyboard open, close it...

            if (!isEnabled) {
                InputMethodManager input = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                input.hideSoftInputFromWindow(sslPortEditField.getWindowToken(), 0);
            }

            // Set SSL state in config model accordingly...

            AppSettingsModel.enableSSL(AppSettingsActivity.this, isEnabled);

            // Enable/Disable SSL Port text field according to SSL toggle on/off state...

            sslPortEditField.setEnabled(isEnabled);
            sslPortEditField.setFocusable(isEnabled);
            sslPortEditField.setFocusableInTouchMode(isEnabled);
        }
    });

    pin.setText("...");

    final Handler pinHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            pin.setText(msg.getData().getString("pin"));
        }
    };

    new Thread() {
        public void run() {
            String pin = ORKeyPair.getInstance().getPIN(getApplicationContext());

            Bundle bundle = new Bundle();
            bundle.putString("pin", pin);

            Message msg = pinHandler.obtainMessage();
            msg.setData(bundle);

            msg.sendToTarget();
        }
    }.start();

    sslPortEditField.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            //TODO not very user friendly
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                String sslPortStr = ((EditText) v).getText().toString();

                try {
                    int sslPort = Integer.parseInt(sslPortStr.trim());
                    AppSettingsModel.setSSLPort(AppSettingsActivity.this, sslPort);
                }

                catch (NumberFormatException ex) {
                    Toast toast = Toast.makeText(getApplicationContext(), "SSL port format is not correct.", 1);
                    toast.show();

                    return false;
                }

                catch (IllegalArgumentException e) {
                    Toast toast = Toast.makeText(getApplicationContext(), e.getMessage(), 2);
                    toast.show();

                    sslPortEditField.setText("" + AppSettingsModel.getSSLPort(AppSettingsActivity.this));

                    return false;
                }
            }

            return false;
        }

    });

}

From source file:net.sylvek.sharemyposition.ShareMyPosition.java

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    default:/* w ww. j a v  a  2 s .c  o  m*/
        return super.onCreateDialog(id);
    case MAP_DLG:
        final View sharedMapView = LayoutInflater.from(this).inflate(R.layout.sharedmap, null);
        final FrameLayout map = (FrameLayout) sharedMapView.findViewById(R.id.sharedmap);
        map.addView(this.sharedMap);
        final CheckBox latlonAddress = (CheckBox) sharedMapView.findViewById(R.id.add_lat_lon_location);
        final CheckBox geocodeAddress = (CheckBox) sharedMapView.findViewById(R.id.add_address_location);
        final RadioButton nourl = (RadioButton) sharedMapView.findViewById(R.id.add_no_url_location);
        final RadioButton url = (RadioButton) sharedMapView.findViewById(R.id.add_url_location);
        final RadioButton gmap = (RadioButton) sharedMapView.findViewById(R.id.add_native_location);
        final EditText body = (EditText) sharedMapView.findViewById(R.id.body);
        final ToggleButton track = (ToggleButton) sharedMapView.findViewById(R.id.add_track_location);

        latlonAddress.setChecked(pref.getBoolean(PREF_LAT_LON_CHECKED, true));
        geocodeAddress.setChecked(pref.getBoolean(PREF_ADDRESS_CHECKED, true));
        final boolean isUrl = pref.getBoolean(PREF_URL_CHECKED, true);
        final boolean isGmap = pref.getBoolean(PREF_GMAP_CHECKED, false);
        url.setChecked(isUrl);
        gmap.setChecked(isGmap);
        nourl.setChecked(!isUrl && !isGmap);
        body.setText(pref.getString(PREF_BODY_DEFAULT, getString(R.string.body)));
        track.setChecked(pref.getBoolean(PREF_TRACK_CHECKED, false));

        if (track.isChecked()) {
            latlonAddress.setEnabled(false);
            latlonAddress.setChecked(false);
            geocodeAddress.setEnabled(false);
            geocodeAddress.setChecked(false);
            url.setEnabled(false);
            url.setChecked(true);
            gmap.setEnabled(false);
            gmap.setChecked(false);
            nourl.setEnabled(false);
            nourl.setChecked(false);
        }

        track.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                latlonAddress.setEnabled(!isChecked);
                latlonAddress.setChecked(!isChecked);
                geocodeAddress.setEnabled(!isChecked);
                geocodeAddress.setChecked(!isChecked);
                url.setEnabled(!isChecked);
                url.setChecked(true);
                gmap.setEnabled(!isChecked);
                gmap.setChecked(!isChecked);
                nourl.setEnabled(!isChecked);
                nourl.setChecked(!isChecked);
            }
        });

        return new AlertDialog.Builder(this).setTitle(R.string.app_name).setView(sharedMapView)
                .setOnCancelListener(new OnCancelListener() {

                    @Override
                    public void onCancel(DialogInterface arg0) {
                        finish();
                    }
                }).setNeutralButton(R.string.options, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        /* needed to display neutral button */
                    }
                }).setPositiveButton(R.string.share_it, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        final boolean isLatLong = ((CheckBox) sharedMapView
                                .findViewById(R.id.add_lat_lon_location)).isChecked();
                        final boolean isGeocodeAddress = ((CheckBox) sharedMapView
                                .findViewById(R.id.add_address_location)).isChecked();
                        final boolean isUrl = ((RadioButton) sharedMapView.findViewById(R.id.add_url_location))
                                .isChecked();
                        final boolean isGmap = ((RadioButton) sharedMapView
                                .findViewById(R.id.add_native_location)).isChecked();
                        final EditText body = (EditText) sharedMapView.findViewById(R.id.body);
                        final boolean isTracked = ((ToggleButton) sharedMapView
                                .findViewById(R.id.add_track_location)).isChecked();
                        final String uuid = UUID.randomUUID().toString();

                        pref.edit().putBoolean(PREF_LAT_LON_CHECKED, isLatLong)
                                .putBoolean(PREF_ADDRESS_CHECKED, isGeocodeAddress)
                                .putBoolean(PREF_URL_CHECKED, isUrl).putBoolean(PREF_GMAP_CHECKED, isGmap)
                                .putString(PREF_BODY_DEFAULT, body.getText().toString())
                                .putBoolean(PREF_TRACK_CHECKED, isTracked).commit();

                        final Intent t = new Intent(Intent.ACTION_SEND);
                        t.setType("text/plain");
                        t.addCategory(Intent.CATEGORY_DEFAULT);
                        final Intent share = Intent.createChooser(t, getString(R.string.app_name));
                        final GeoPoint p = sharedMap.getMapCenter();

                        final String text = body.getText().toString();
                        share(p.getLatitude(), p.getLongitude(), t, share, text, isGeocodeAddress, isUrl,
                                isGmap, isLatLong, isTracked, uuid);
                    }
                }).create();
    case PROGRESS_DLG:
        final ProgressDialog dlg = new ProgressDialog(this);
        dlg.setTitle(getText(R.string.app_name));
        dlg.setMessage(getText(R.string.progression_desc));
        dlg.setIndeterminate(true);
        dlg.setCancelable(true);
        dlg.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        return dlg;
    case PROVIDERS_DLG:
        return new AlertDialog.Builder(this).setTitle(R.string.app_name).setCancelable(false)
                .setIcon(android.R.drawable.ic_menu_help).setMessage(R.string.providers_needed)
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }

                }).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent gpsProperty = new Intent(
                                android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(gpsProperty);
                    }
                }).create();
    }
}

From source file:org.noise_planet.noisecapture.CommentActivity.java

private void addTag(String tagName, int id, ViewGroup column, int color) {
    ToggleButton tagButton = new ToggleButton(this);
    if (color != -1) {
        LinearLayout colorBox = new LinearLayout(this);
        // Convert the dps to pixels, based on density scale
        final int tagPaddingPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
                getResources().getDisplayMetrics());
        final int tagPaddingPxBottom = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3,
                getResources().getDisplayMetrics());
        //use a GradientDrawable with only one color set, to make it a solid color
        colorBox.setBackgroundResource(R.drawable.tag_round_corner);
        GradientDrawable gradientDrawable = (GradientDrawable) colorBox.getBackground();
        gradientDrawable.setColor(color);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(tagPaddingPx, tagPaddingPx, tagPaddingPx, tagPaddingPxBottom);
        colorBox.setLayoutParams(params);
        colorBox.addView(tagButton);/*from  w  w  w.j  a v  a2s.  c om*/
        column.addView(colorBox);
    } else {
        column.addView(tagButton);
    }
    tagButton.setTextOff(tagName);
    tagButton.setTextOn(tagName);
    boolean isChecked = checkedTags.contains(id);
    tagButton.setChecked(isChecked);
    if (isChecked) {
        tagButton.setTextColor(selectedColor);
    }
    tagButton.setOnCheckedChangeListener(new TagStateListener(id, checkedTags));
    tagButton.setMinHeight(0);
    tagButton.setMinimumHeight(0);
    tagButton.setTextSize(Dimension.SP, 12);
    tagButton.setEnabled(record == null || record.getUploadId().isEmpty());
    tagButton.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    tagButton.invalidate();
}

From source file:com.aniruddhc.acemusic.player.EqualizerActivity.EqualizerActivity.java

/**
 * Initializes the ActionBar./* w w  w.  j a  v  a2 s  .c om*/
 */
private void showEqualizerActionBar(Menu menu) {

    //Set the Actionbar color.
    getActionBar().setBackgroundDrawable(UIElementsHelper.getGeneralActionBarBackground(mContext));

    //Hide all menu items except the toggle button and "done" icon.
    menu.findItem(R.id.action_equalizer).setVisible(false);
    menu.findItem(R.id.action_pin).setVisible(false);
    menu.findItem(R.id.action_queue_drawer).setVisible(false);
    menu.findItem(R.id.action_settings).setVisible(false);
    menu.findItem(R.id.action_done).setVisible(true);

    /**
     * The Toggle button in the actionbar doesn't work at this point. The setChecked()
     * method doesn't do anything, so there's no way to programmatically set the
     * switch to its correct position when the equalizer fragment is first shown.
     * Users will just have to rely on the "Reset" button in the equalizer fragment
     * to effectively switch off the equalizer.
     */
    menu.findItem(R.id.action_equalizer_toggle).setVisible(false); //Hide the toggle for now.

    //Set the toggle listener.
    ToggleButton equalizerToggle = (ToggleButton) menu.findItem(R.id.action_equalizer_toggle).getActionView()
            .findViewById(R.id.actionbar_toggle_switch);

    //Set the current state of the toggle.
    boolean toggleSetting = true;
    if (mApp.isEqualizerEnabled())
        toggleSetting = true;
    else
        toggleSetting = false;

    //Set the ActionBar title text color.
    int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
    TextView abTitle = (TextView) findViewById(titleId);
    abTitle.setTextColor(0xFFFFFFFF);

    equalizerToggle.setChecked(toggleSetting);
    equalizerToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean state) {
            mApp.setIsEqualizerEnabled(state);

            if (state == true)
                applyCurrentEQSettings();

        }

    });

    getActionBar().setHomeButtonEnabled(false);
    getActionBar().setDisplayHomeAsUpEnabled(false);

}

From source file:ru.valle.btc.MainActivity.java

private void showQRCodePopupForPrivateKey(final String label, final String address, final String[] data,
        final String[] dataTypes) {
    DisplayMetrics dm = getResources().getDisplayMetrics();
    final int screenSize = Math.min(dm.widthPixels, dm.heightPixels);
    new AsyncTask<Void, Void, Bitmap[]>() {

        @Override/*  w ww  . j a v  a 2s . c om*/
        protected Bitmap[] doInBackground(Void... params) {
            Bitmap[] result = new Bitmap[data.length];
            for (int i = 0; i < data.length; i++) {
                if (data[i] != null) {
                    QRCode qr = QRCode.getMinimumQRCode(data[i], ErrorCorrectLevel.M);
                    result[i] = qr.createImage(screenSize / 2);
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(final Bitmap[] bitmap) {
            if (bitmap != null) {
                View view = getLayoutInflater().inflate(R.layout.private_key_qr, mainLayout, false);
                if (view != null) {
                    final ToggleButton toggle1 = (ToggleButton) view.findViewById(R.id.toggle_1);
                    final ToggleButton toggle2 = (ToggleButton) view.findViewById(R.id.toggle_2);
                    final ToggleButton toggle3 = (ToggleButton) view.findViewById(R.id.toggle_3);
                    final ImageView qrView = (ImageView) view.findViewById(R.id.qr_code_image);
                    final TextView dataView = (TextView) view.findViewById(R.id.qr_code_data);

                    if (data[0] == null) {
                        toggle1.setVisibility(View.GONE);
                    } else {
                        toggle1.setTextOff(dataTypes[0]);
                        toggle1.setTextOn(dataTypes[0]);
                        toggle1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                if (isChecked) {
                                    toggle2.setChecked(false);
                                    toggle3.setChecked(false);
                                    qrView.setImageBitmap(bitmap[0]);
                                    dataView.setText(data[0]);
                                } else if (!toggle2.isChecked() && !toggle3.isChecked()) {
                                    buttonView.setChecked(true);
                                }
                            }
                        });
                    }
                    if (data[1] == null) {
                        toggle2.setVisibility(View.GONE);
                    } else {
                        toggle2.setTextOff(dataTypes[1]);
                        toggle2.setTextOn(dataTypes[1]);
                        toggle2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                if (isChecked) {
                                    toggle1.setChecked(false);
                                    toggle3.setChecked(false);
                                    qrView.setImageBitmap(bitmap[1]);
                                    dataView.setText(data[1]);
                                } else if (!toggle1.isChecked() && !toggle3.isChecked()) {
                                    buttonView.setChecked(true);
                                }
                            }
                        });
                    }
                    if (data[2] == null) {
                        toggle3.setVisibility(View.GONE);
                    } else {
                        toggle3.setTextOff(dataTypes[2]);
                        toggle3.setTextOn(dataTypes[2]);
                        toggle3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                if (isChecked) {
                                    toggle1.setChecked(false);
                                    toggle2.setChecked(false);
                                    qrView.setImageBitmap(bitmap[2]);
                                    dataView.setText(data[2]);
                                } else if (!toggle1.isChecked() && !toggle2.isChecked()) {
                                    buttonView.setChecked(true);
                                }
                            }
                        });
                    }
                    if (data[2] != null) {
                        toggle3.setChecked(true);
                    } else if (data[0] != null) {
                        toggle1.setChecked(true);
                    } else {
                        toggle2.setChecked(true);
                    }

                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle(label);
                    builder.setView(view);
                    DialogInterface.OnClickListener shareClickListener = new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            int selectedIndex;
                            if (toggle1.isChecked()) {
                                selectedIndex = 0;
                            } else if (toggle2.isChecked()) {
                                selectedIndex = 1;
                            } else {
                                selectedIndex = 2;
                            }
                            Intent intent = new Intent(Intent.ACTION_SEND);
                            intent.setType("text/plain");
                            intent.putExtra(Intent.EXTRA_SUBJECT, label);
                            intent.putExtra(Intent.EXTRA_TEXT, data[selectedIndex]);
                            startActivity(
                                    Intent.createChooser(intent, getString(R.string.share_chooser_title)));
                        }
                    };
                    if (systemSupportsPrint()) {
                        builder.setPositiveButton(R.string.print, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                int selectedIndex;
                                if (toggle1.isChecked()) {
                                    selectedIndex = 0;
                                } else if (toggle2.isChecked()) {
                                    selectedIndex = 1;
                                } else {
                                    selectedIndex = 2;
                                }
                                Renderer.printWallet(MainActivity.this, label, SCHEME_BITCOIN + address,
                                        data[selectedIndex]);
                            }
                        });
                        builder.setNeutralButton(R.string.share, shareClickListener);
                    } else {
                        builder.setPositiveButton(R.string.share, shareClickListener);
                    }
                    builder.setNegativeButton(android.R.string.cancel, null);
                    builder.show();
                }
            }
        }
    }.execute();
}

From source file:ru.valle.safetrade.SellActivity.java

private void takeFunds() {
    String finalAddress = "";
    String errorMessage = null;//from ww  w.ja v a 2  s.co  m
    if (tradeInfo == null) {
        errorMessage = getString(R.string.state_not_loaded_yet);
    } else if (TextUtils.isEmpty(tradeInfo.privateKey)) {
        errorMessage = getString(R.string.no_private_key_from_buyer);
    } else if (addressState == null) {
        errorMessage = getString(R.string.alert_checking_balance);//TODO it may be not true because of networking errors, add retry
    }
    //        } else if (addressState.getBalance() == 0) {
    //            errorMessage = getString(R.string.zero_balance, addressState.address);
    //        }
    else {
        CharSequence enteredAddress = finalAddressView.getText();
        if (enteredAddress != null) {
            finalAddress = enteredAddress.toString();
        }
        if (TextUtils.isEmpty(finalAddress)) {
            errorMessage = getString(R.string.enter_your_final_address);
        }
    }
    if (errorMessage != null) {
        showAlert(errorMessage);
    } else {
        View feesSelectorView = LayoutInflater.from(this).inflate(R.layout.fees_selector, null);
        assert feesSelectorView != null;
        TextView descView = (TextView) feesSelectorView.findViewById(R.id.tx_desc);

        final AddressState addressStateArg;
        final BTCUtils.PrivateKeyInfo privateKeyInfo;

        //args
        //            addressStateArg = addressState;
        //            privateKeyInfo = BTCUtils.decodePrivateKey(tradeInfo.privateKey);
        //
        try {
            addressStateArg = new AddressState("1933phfhK3ZgFQNLGSDXvqCn32k2buXY8a",
                    MainActivity.parseUnspentOutputsFromBlockchainInfo(new String(
                            QRCodesProvider.readStream(getResources().openRawResource(R.raw.fakeoutputs)))));
            privateKeyInfo = BTCUtils.decodePrivateKey(tradeInfo.privateKey);
        } catch (Exception e) {
            throw new RuntimeException();
        }
        //

        final long balance = addressStateArg.getBalance();
        descView.setText(
                getString(R.string.confirm_tx_x_btc_to_addr, BTCUtils.formatValue(balance), finalAddress));

        final ToggleButton minFeeButton = (ToggleButton) feesSelectorView.findViewById(R.id.min_miner_fee);
        final ToggleButton safeFeeButton = (ToggleButton) feesSelectorView.findViewById(R.id.safe_miner_fee);
        final ToggleButton maxFeeButton = (ToggleButton) feesSelectorView.findViewById(R.id.max_miner_fee);

        final TextView minersFeeView = (TextView) feesSelectorView.findViewById(R.id.miners_fee);

        final ToggleButton noDevFeeButton = (ToggleButton) feesSelectorView.findViewById(R.id.no_dev_fee);
        final ToggleButton medDevFeeButton = (ToggleButton) feesSelectorView.findViewById(R.id.med_dev_fee);
        final ToggleButton maxDevFeeButton = (ToggleButton) feesSelectorView.findViewById(R.id.max_dev_fee);

        final TextView devFeeView = (TextView) feesSelectorView.findViewById(R.id.developer_fee);

        final TextView txDescFinalView = (TextView) feesSelectorView.findViewById(R.id.tx_desc_after_fees);

        CompoundButton.OnCheckedChangeListener feesSelectorListener = new CompoundButton.OnCheckedChangeListener() {
            long fee;
            long devFee;
            public int feeLevel;

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                switch (buttonView.getId()) {
                case R.id.min_miner_fee: {
                    if (isChecked) {
                        safeFeeButton.setChecked(false);
                        maxFeeButton.setChecked(false);
                        updateFee(0);
                    } else if (!safeFeeButton.isChecked() && !maxFeeButton.isChecked()) {
                        buttonView.setChecked(true);
                    }
                }
                    break;
                case R.id.safe_miner_fee: {
                    if (isChecked) {
                        minFeeButton.setChecked(false);
                        maxFeeButton.setChecked(false);
                        updateFee(1);
                    } else if (!minFeeButton.isChecked() && !maxFeeButton.isChecked()) {
                        buttonView.setChecked(true);
                    }
                }
                    break;
                case R.id.max_miner_fee: {
                    if (isChecked) {
                        minFeeButton.setChecked(false);
                        safeFeeButton.setChecked(false);
                        updateFee(2);
                    } else if (!minFeeButton.isChecked() && !safeFeeButton.isChecked()) {
                        buttonView.setChecked(true);
                    }
                }
                    break;
                case R.id.no_dev_fee: {
                    if (isChecked) {
                        medDevFeeButton.setChecked(false);
                        maxDevFeeButton.setChecked(false);
                        updateDevFee(0);
                    } else if (!medDevFeeButton.isChecked() && !maxDevFeeButton.isChecked()) {
                        buttonView.setChecked(true);
                    }
                }
                    break;
                case R.id.med_dev_fee: {
                    if (isChecked) {
                        noDevFeeButton.setChecked(false);
                        maxDevFeeButton.setChecked(false);
                        updateDevFee(1);
                    } else if (!noDevFeeButton.isChecked() && !maxDevFeeButton.isChecked()) {
                        buttonView.setChecked(true);
                    }
                }
                    break;
                case R.id.max_dev_fee: {
                    if (isChecked) {
                        noDevFeeButton.setChecked(false);
                        medDevFeeButton.setChecked(false);
                        updateDevFee(2);
                    } else if (!noDevFeeButton.isChecked() && !medDevFeeButton.isChecked()) {
                        buttonView.setChecked(true);
                    }
                }
                    break;
                }
            }

            private void updateDevFee(int level) {
                devFee = getDevFee(level, balance);
                devFeeView.setText(getString(R.string.tips_for_dev, BTCUtils.formatValue(devFee)));
                updateFee(feeLevel);
            }

            private void updateFee(int level) {
                feeLevel = level;
                fee = getMinerFee(level, devFee, balance, addressStateArg.getUnspentOutputs(),
                        privateKeyInfo.isPublicKeyCompressed);
                minersFeeView.setText(getString(R.string.miners_fee, BTCUtils.formatValue(fee)));
                txDescFinalView.setText(
                        getString(R.string.final_tx_desc, BTCUtils.formatValue(balance - fee - devFee)));
            }

        };

        minFeeButton.setOnCheckedChangeListener(feesSelectorListener);
        safeFeeButton.setOnCheckedChangeListener(feesSelectorListener);
        maxFeeButton.setOnCheckedChangeListener(feesSelectorListener);
        ((ToggleButton) feesSelectorView.findViewById(R.id.no_dev_fee))
                .setOnCheckedChangeListener(feesSelectorListener);
        ((ToggleButton) feesSelectorView.findViewById(R.id.med_dev_fee))
                .setOnCheckedChangeListener(feesSelectorListener);
        ((ToggleButton) feesSelectorView.findViewById(R.id.max_dev_fee))
                .setOnCheckedChangeListener(feesSelectorListener);

        safeFeeButton.setChecked(true);

        if (getDevFee(1, balance) == 0) {
            medDevFeeButton.setEnabled(false);
            maxDevFeeButton.setEnabled(getDevFee(2, balance) > 0);
            noDevFeeButton.setChecked(true);
        } else {
            medDevFeeButton.setChecked(true);
        }

        long minDevFee = getDevFee(0, balance);
        if (getMinerFee(2, minDevFee, balance, addressStateArg.getUnspentOutputs(),
                privateKeyInfo.isPublicKeyCompressed) == balance - minDevFee) {
            maxFeeButton.setEnabled(false);
        }

        if (getMinerFee(1, minDevFee, balance, addressStateArg.getUnspentOutputs(),
                privateKeyInfo.isPublicKeyCompressed) == balance - minDevFee) {
            safeFeeButton.setEnabled(false);
            minFeeButton.setChecked(true);
        }

        new AlertDialog.Builder(SellActivity.this).setView(feesSelectorView)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).setNegativeButton(android.R.string.cancel, null).show();
    }
}