Example usage for android.widget SeekBar setMax

List of usage examples for android.widget SeekBar setMax

Introduction

In this page you can find the example usage for android.widget SeekBar setMax.

Prototype

@Override
    public synchronized void setMax(int max) 

Source Link

Usage

From source file:com.brewcrewfoo.performance.fragments.Advanced.java

public void openDialog(String title, final int min, final int max, final Preference pref, final String path,
        final String key) {
    Resources res = context.getResources();
    String cancel = res.getString(R.string.cancel);
    String ok = res.getString(R.string.ok);
    final EditText settingText;
    LayoutInflater factory = LayoutInflater.from(context);
    final View alphaDialog = factory.inflate(R.layout.seekbar_dialog, null);

    final SeekBar seekbar = (SeekBar) alphaDialog.findViewById(R.id.seek_bar);
    seekbar.setMax(max - min);

    int currentProgress = min;
    if (key.equals("pref_viber")) {
        currentProgress = Integer.parseInt(vib.get_val(path));
    } else {/*  w ww.  ja v a  2 s.  com*/
        currentProgress = Integer.parseInt(Helpers.readOneLine(path));
    }
    if (currentProgress > max)
        currentProgress = max - min;
    else if (currentProgress < min)
        currentProgress = 0;
    else
        currentProgress = currentProgress - min;

    seekbar.setProgress(currentProgress);

    settingText = (EditText) alphaDialog.findViewById(R.id.setting_text);
    settingText.setText(Integer.toString(currentProgress + min));

    settingText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                int val = Integer.parseInt(settingText.getText().toString()) - min;
                seekbar.setProgress(val);
                return true;
            }
            return false;
        }
    });

    settingText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

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

        @Override
        public void afterTextChanged(Editable s) {
            try {
                int val = Integer.parseInt(s.toString());
                if (val > max) {
                    s.replace(0, s.length(), Integer.toString(max));
                    val = max;
                }
                seekbar.setProgress(val - min);
            } catch (NumberFormatException ex) {
            }
        }
    });

    OnSeekBarChangeListener seekBarChangeListener = new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) {
            final int mSeekbarProgress = seekbar.getProgress();
            if (fromUser) {
                settingText.setText(Integer.toString(mSeekbarProgress + min));
            }
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekbar) {
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekbar) {
        }
    };
    seekbar.setOnSeekBarChangeListener(seekBarChangeListener);

    new AlertDialog.Builder(context).setTitle(title).setView(alphaDialog)
            .setNegativeButton(cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // nothing
                }
            }).setPositiveButton(ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int val = min;
                    if (!settingText.getText().toString().equals(""))
                        val = Integer.parseInt(settingText.getText().toString());
                    if (val < min)
                        val = min;
                    seekbar.setProgress(val - min);
                    int newProgress = seekbar.getProgress() + min;
                    new CMDProcessor().su
                            .runWaitFor("busybox echo " + Integer.toString(newProgress) + " > " + path);
                    String v;
                    if (key.equals("pref_viber")) {
                        v = vib.get_val(path);
                        Vibrator vb = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                        vb.vibrate(1000);
                    } else {
                        v = Helpers.readOneLine(path);
                    }
                    final SharedPreferences.Editor editor = mPreferences.edit();
                    editor.putInt(key, Integer.parseInt(v)).commit();
                    pref.setSummary(v);

                }
            }).create().show();
}

From source file:com.xperia64.timidityae.TrackFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    reset();//from   w  ww.  j  a v  a 2  s .c o  m

    fileList = new ArrayAdapter<String>(getActivity(), R.layout.row);
    for (int i = 0; i < JNIHandler.MAX_CHANNELS; i++) {
        fileList.add(String.format(getActivity().getResources().getString(R.string.trk_form),
                (getActivity().getResources()
                        .getString(JNIHandler.drums.get(i) ? R.string.trk_drum : R.string.trk_inst2)),
                (i + 1), JNIHandler.drums.get(i) ? 0 : localInst.get(i) + 1, localVol.get(i)));
    }
    channelList.setAdapter(fileList);
    channelList.setOnItemClickListener(new OnItemClickListener() {

        @SuppressLint("InflateParams")
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
            AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
            View v = getActivity().getLayoutInflater().inflate(R.layout.track_dialog, null);
            final Spinner instSpin = (Spinner) v.findViewById(R.id.instSpin);
            instSpin.setClickable(JNIHandler.custInst.get(arg2) && !JNIHandler.drums.get(arg2));
            instSpin.setOnLongClickListener(null);
            instSpin.setEnabled(JNIHandler.custInst.get(arg2) && !JNIHandler.drums.get(arg2));
            List<String> arrayAdapter = new ArrayList<String>();
            final int offset = (!JNIHandler.drums.get(arg2)) ? 0 : 34;
            if (!JNIHandler.drums.get(arg2)) {
                for (String inst : getActivity().getResources().getStringArray(R.array.midi_instruments))
                    arrayAdapter.add(inst);
            } else {
                for (String inst : getActivity().getResources().getStringArray(R.array.midi_drums))
                    arrayAdapter.add(inst);
            }
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_spinner_item, arrayAdapter);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
            } else {
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            }

            dataAdapter.setNotifyOnChange(false);
            if (!JNIHandler.drums.get(arg2)) {
                instSpin.setAdapter(dataAdapter);
                instSpin.setSelection(localInst.get(arg2) - offset);
            }
            final EditText txtVol = (EditText) v.findViewById(R.id.txtVol);
            txtVol.setText(Integer.toString(localVol.get(arg2)));
            txtVol.setClickable(JNIHandler.custVol.get(arg2));
            txtVol.setEnabled(JNIHandler.custVol.get(arg2));

            final SeekBar volSeek = (SeekBar) v.findViewById(R.id.volSeek);
            volSeek.setClickable(JNIHandler.custVol.get(arg2));
            volSeek.setEnabled(JNIHandler.custVol.get(arg2));
            volSeek.setMax(127);
            volSeek.setProgress(localVol.get(arg2));
            volSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

                @Override
                public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
                    if (arg2 && !fromUser) {
                        fromUser = true;
                        txtVol.setText(Integer.toString(arg0.getProgress()));
                    } else {
                        fromUser = false;
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar arg0) {
                }

                @Override
                public void onStopTrackingTouch(SeekBar arg0) {
                }

            });

            txtVol.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    if (!fromUser) {
                        if (s.length() > 0) {
                            int numm = Integer.parseInt(s.toString());
                            if (numm > 127) {
                                fromUser = true;
                                numm = 127;
                            }
                            if (numm < 0) {
                                fromUser = true;
                                numm = 0;
                            }
                            if (fromUser) {
                                txtVol.setText(Integer.toString(numm));
                            }
                            fromUser = true;
                            volSeek.setProgress(numm);
                            fromUser = false;
                        }
                    } else {
                        fromUser = false;
                    }
                }

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

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });
            final CheckBox inst = (CheckBox) v.findViewById(R.id.defInstr);
            inst.setEnabled(!JNIHandler.drums.get(arg2));
            inst.setChecked(!JNIHandler.custInst.get(arg2));
            inst.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton arg0, boolean arg1) {

                    instSpin.setClickable(!arg1);
                    instSpin.setEnabled(!arg1);
                }

            });
            final CheckBox vol = (CheckBox) v.findViewById(R.id.defVol);
            vol.setChecked(!JNIHandler.custVol.get(arg2));
            //System.out.println("Def inst: "+(!JNIHandler.custInst.get(arg2)?"true":"false")+" def vol: "+(!JNIHandler.custVol.get(arg2)?"true":"false"));
            vol.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton arg0, boolean arg1) {

                    volSeek.setClickable(!arg1);
                    volSeek.setEnabled(!arg1);
                    txtVol.setClickable(!arg1);
                    txtVol.setEnabled(!arg1);
                }

            });
            if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                v.setBackgroundColor(Globals.theme == 1 ? Color.WHITE : Color.BLACK);
            b.setView(v);
            b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

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

                    JNIHandler.custInst.set(arg2, !inst.isChecked());
                    JNIHandler.custVol.set(arg2, !vol.isChecked());
                    JNIHandler.setChannelVolumeTimidity(arg2 | (JNIHandler.custVol.get(arg2) ? 0x800 : 0x8000),
                            volSeek.getProgress());
                    JNIHandler.setChannelTimidity(arg2 | (JNIHandler.custInst.get(arg2) ? 0x800 : 0x8000),
                            instSpin.getSelectedItemPosition());
                    if (!JNIHandler.paused && Globals.isPlaying == 0)
                        JNIHandler.seekTo(JNIHandler.currTime);
                    //bigCounter=12;
                    updateList();
                }
            });

            b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            b.setTitle(String.format((getActivity().getResources().getString(R.string.trk_form2)), (arg2 + 1)));
            ddd = b.create();
            ddd.show();
        }

    });
}

From source file:layout.BeaconTabFragment.java

/**
 * Setting up the radio tx power component with a seek bar which reads the supported tx powers
 * and only allows the user to set these. There is also a tracking TextView which shows the
 * numeric representation of the tx power.
 *
 * @param v container for the radio tx power component. This is usually the main container in
 *          the tab. It has to be added to the activity before calling this method.
 */// w  w  w.  j a v  a  2  s.c  o m
private void setUpRadioTxPower(View v) {
    if (txPower != null) {
        v.findViewById(R.id.tx_power_info).setVisibility(View.VISIBLE);

        final TextView txPowerView = (TextView) v.findViewById(R.id.radio_tx_power);
        txPowerView.setText(txPower);
        SeekBar seekBar = (SeekBar) v.findViewById(R.id.tx_power_seek_bar);

        final byte[] allowedValues = capabilities.getSupportedTxPowers();
        final int maxValue = Utils.findMaxValue(allowedValues);
        final int minValue = Utils.findMinValue(allowedValues);

        seekBar.setMax(maxValue - minValue);
        seekBar.setProgress(Integer.parseInt(txPower) - minValue);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int newValue;
                if (allowedValues != null) {
                    newValue = Utils.findValueClosestTo(progress + minValue, allowedValues);
                } else {
                    newValue = progress + minValue;
                }
                seekBar.setProgress(newValue - minValue);
                txPowerView.setText(Integer.toString(newValue));
                BeaconTabFragment.this.txPower = Integer.toString(newValue);
            }
        });
    }
}

From source file:com.brewcrewfoo.performance.fragments.MemSettings.java

public void openDialog(final int idx, int currentProgress, String title, final int min, final int max,
        final Preference pref, final String path, final String key) {
    Resources res = getActivity().getResources();
    String cancel = res.getString(R.string.cancel);
    String ok = res.getString(R.string.ok);
    LayoutInflater factory = LayoutInflater.from(getActivity());
    final View alphaDialog = factory.inflate(R.layout.seekbar_dialog, null);

    final SeekBar seekbar = (SeekBar) alphaDialog.findViewById(R.id.seek_bar);

    seekbar.setMax(max);
    seekbar.setProgress(currentProgress);

    settingText = (EditText) alphaDialog.findViewById(R.id.setting_text);
    settingText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override//  w  ww .j  a  v  a2 s .com
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                int val = Integer.parseInt(settingText.getText().toString());
                seekbar.setProgress(val);
                return true;
            }
            return false;
        }
    });
    settingText.setText(Integer.toString(currentProgress));
    settingText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

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

        @Override
        public void afterTextChanged(Editable s) {
            try {
                int val = Integer.parseInt(s.toString());
                if (val > max) {
                    s.replace(0, s.length(), Integer.toString(max));
                    val = max;
                }
                seekbar.setProgress(val);
            } catch (NumberFormatException ex) {
            }
        }
    });

    OnSeekBarChangeListener seekBarChangeListener = new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) {
            mSeekbarProgress = seekbar.getProgress();
            if (fromUser) {
                settingText.setText(Integer.toString(mSeekbarProgress));
            }
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekbar) {
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekbar) {
        }
    };
    seekbar.setOnSeekBarChangeListener(seekBarChangeListener);

    new AlertDialog.Builder(getActivity()).setTitle(title).setView(alphaDialog)
            .setNegativeButton(cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // nothing
                }
            }).setPositiveButton(ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int val = Integer.parseInt(settingText.getText().toString());
                    if (val < min) {
                        val = min;
                    }
                    seekbar.setProgress(val);
                    int newProgress = seekbar.getProgress();
                    values[idx] = Integer.toString(newProgress * 256);
                    pref.setSummary(newProgress + " MB " + "(" + values[idx] + ")");
                    new CMDProcessor().su
                            .runWaitFor("busybox echo " + implodeArray(values, ",") + " > " + path);
                    final SharedPreferences.Editor editor = mPreferences.edit();
                    editor.putString(key, implodeArray(values, ","));
                    editor.commit();
                }
            }).create().show();

}

From source file:org.dharmaseed.android.PlayTalkActivity.java

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

    // Turn on action bar up/home button
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }/*  w  ww. jav  a2s  . co m*/

    // Get the ID of the talk to display
    Intent i = getIntent();
    talkID = (int) i.getLongExtra(NavigationActivity.TALK_DETAIL_EXTRA, 0);

    dbManager = DBManager.getInstance(this);

    // only hit the DB again if we know the talk is different than the one
    // we have saved.
    // for example, if the user selects a talk, exits, and re-opens it, no need
    // to hit the DB again, since we already have that talk saved
    if (talk == null || talk.getId() != talkID) {
        Cursor cursor = getCursor();
        if (cursor.moveToFirst()) {
            // convert DB result to an object
            talk = new Talk(cursor);
            talk.setId(talkID);
        } else {
            Log.e(LOG_TAG, "Could not look up talk, id=" + talkID);
            cursor.close();
            return;
        }
        cursor.close();
    } // else we already have the talk, just re-draw the page

    // Set the talk title
    TextView titleView = (TextView) findViewById(R.id.play_talk_talk_title);
    titleView.setText(talk.getTitle());

    // Set the teacher name
    TextView teacherView = (TextView) findViewById(R.id.play_talk_teacher);
    teacherView.setText(talk.getTeacherName());

    // Set the center name
    TextView centerView = (TextView) findViewById(R.id.play_talk_center);
    centerView.setText(talk.getCenterName());

    // Set the talk description
    TextView descriptionView = (TextView) findViewById(R.id.play_talk_talk_description);
    descriptionView.setText(talk.getDescription());

    // Set teacher photo
    String photoFilename = talk.getPhotoFileName();
    ImageView photoView = (ImageView) findViewById(R.id.play_talk_teacher_photo);
    Log.i(LOG_TAG, "photoFilename: " + photoFilename);
    try {
        FileInputStream photo = openFileInput(photoFilename);
        photoView.setImageBitmap(BitmapFactory.decodeStream(photo));
    } catch (FileNotFoundException e) {
        Drawable icon = ContextCompat.getDrawable(this, R.drawable.dharmaseed_icon);
        photoView.setImageDrawable(icon);
    }

    // set the image of the download button based on whether the talk is
    // downloaded or not
    toggleDownloadImage();

    // Set date
    TextView dateView = (TextView) findViewById(R.id.play_talk_date);
    String recDate = talk.getDate();
    SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        dateView.setText(DateFormat.getDateInstance().format(parser.parse(recDate)));
    } catch (ParseException e) {
        dateView.setText("");
        Log.w(LOG_TAG, "Could not parse talk date for talk ID " + talkID);
    }

    // Get/create a persistent fragment to manage the MediaPlayer instance
    FragmentManager fm = getSupportFragmentManager();
    talkPlayerFragment = (TalkPlayerFragment) fm.findFragmentByTag("talkPlayerFragment");
    if (talkPlayerFragment == null) {
        // add the fragment
        talkPlayerFragment = new TalkPlayerFragment();
        fm.beginTransaction().add(talkPlayerFragment, "talkPlayerFragment").commit();
    } else if (talkPlayerFragment.getMediaPlayer().isPlaying()) {
        setPPButton("ic_media_pause");
    }

    // Set the talk duration
    final TextView durationView = (TextView) findViewById(R.id.play_talk_talk_duration);
    double duration = talk.getDurationInMinutes();
    String durationStr = DateUtils.formatElapsedTime((long) (duration * 60));
    durationView.setText(durationStr);

    // Start a handler to periodically update the seek bar and talk time
    final SeekBar seekBar = (SeekBar) findViewById(R.id.play_talk_seek_bar);
    seekBar.setMax((int) (duration * 60 * 1000));
    userDraggingSeekBar = false;
    userSeekBarPosition = 0;
    seekBar.setOnSeekBarChangeListener(this);
    final Handler handler = new Handler();
    final MediaPlayer mediaPlayer = talkPlayerFragment.getMediaPlayer();
    handler.post(new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, 1000);
            if (talkPlayerFragment.getMediaPrepared() && !userDraggingSeekBar) {
                try {
                    int pos = mediaPlayer.getCurrentPosition();
                    int mpDuration = mediaPlayer.getDuration();
                    seekBar.setMax(mpDuration);
                    seekBar.setProgress(pos);
                    String posStr = DateUtils.formatElapsedTime(pos / 1000);
                    String mpDurStr = DateUtils.formatElapsedTime(mpDuration / 1000);
                    durationView.setText(posStr + "/" + mpDurStr);
                } catch (IllegalStateException e) {
                }
            }
        }
    });
}

From source file:com.doubleTwist.drawerlib.exampleapp.ExampleFragment.java

private void setupSettingsPanel(int panel, View v) {
    TextView label1 = (TextView) v.findViewById(R.id.progress1_label);
    TextView label2 = (TextView) v.findViewById(R.id.progress2_label);
    TextView label3 = (TextView) v.findViewById(R.id.progress3_label);
    TextView label4 = (TextView) v.findViewById(R.id.progress4_label);

    SeekBar seek1 = (SeekBar) v.findViewById(R.id.progress1);
    SeekBar seek2 = (SeekBar) v.findViewById(R.id.progress2);
    SeekBar seek3 = (SeekBar) v.findViewById(R.id.progress3);
    SeekBar seek4 = (SeekBar) v.findViewById(R.id.progress4);

    boolean centerContent = panel == ADrawerLayout.NO_DRAWER;

    if (label1 != null)
        label1.setText(centerContent ? "X axis paralax [-1, 1]" : "Scale");
    if (seek1 != null) {
        seek1.setMax(1000);
        seek1.setOnSeekBarChangeListener(this);
    }/* w w  w  .java  2  s.c  om*/

    if (label2 != null)
        label2.setText(centerContent ? "Y axis paralax [-1, 1]" : "Alpha");
    if (seek2 != null) {
        seek2.setMax(1000);
        seek2.setOnSeekBarChangeListener(this);
    }

    if (label3 != null)
        label3.setText(centerContent ? "Content dim" : "Rot X");
    if (seek3 != null) {
        seek3.setMax(1000);
        seek3.setOnSeekBarChangeListener(this);
    }

    if (centerContent) {
        label4.setVisibility(View.GONE);
        seek4.setVisibility(View.GONE);
    } else {
        if (label4 != null)
            label4.setText("Rot Y");
        if (seek4 != null) {
            seek4.setMax(1000);
            seek4.setOnSeekBarChangeListener(this);
        }
    }
}

From source file:com.albertcbraun.cms50fw.alert.MainUIFragment.java

private void setUpSeekBar(SharedPreferences defaultSettingsPreference, SeekBar seekBar,
        TextView correspondingTextView, Integer correspondingInteger,
        @SuppressWarnings("SameParameterValue") String maxValueSharedPrefsKeyName, int defaultMaxValue,
        String currentValueSharedPrefsKeyName, int defaultCurrValue) {

    SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBarChangeListener(getActivity(),
            correspondingTextView, correspondingInteger, currentValueSharedPrefsKeyName);

    seekBar.setMax(defaultSettingsPreference.getInt(maxValueSharedPrefsKeyName, defaultMaxValue));
    int currValue = defaultSettingsPreference.getInt(currentValueSharedPrefsKeyName, defaultCurrValue);
    correspondingTextView.setText(String.valueOf(currValue));
    seekBar.setProgress(currValue);//ww  w. j  a v  a2  s .c  om
    seekBar.setOnSeekBarChangeListener(seekBarChangeListener);
}

From source file:de.ktran.anno1404warenrechner.views.PopulationNumberDialog.java

@SuppressLint({ "SetTextI18n", "InflateParams" })
@NonNull/*from  w w w.jav a 2 s .  co  m*/
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    TypedArray attributes = getContext().obtainStyledAttributes(theme, R.styleable.SimpleNumberPicker);

    LayoutInflater inflater = getActivity().getLayoutInflater();

    View view;
    if (populationType instanceof PopulationType) {
        view = inflater.inflate(R.layout.number_picker, null);
    } else {
        view = inflater.inflate(R.layout.house_number_picker, null);
        seekBar = (SeekBar) view.findViewById(R.id.houseNumberPickerPopLimit);
        advancementText = (TextView) view.findViewById(R.id.houseNumberPickerPopLimitDesc);

        if (seekBar == null || advancementText == null)
            throw new IllegalStateException("Not all views could be found.");
        if (populationType == PopulationType.Civilization.OCCIDENTAL) {
            seekBar.setMax(3);
            seekBar.setProgress(3);

            setAdvancementText(3, PopulationType.Civilization.OCCIDENTAL);
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    setAdvancementText(progress, PopulationType.Civilization.OCCIDENTAL);
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                }
            });
        } else if (populationType == PopulationType.Civilization.ORIENTAL) {
            seekBar.setMax(1);
            seekBar.setProgress(1);

            setAdvancementText(1, PopulationType.Civilization.ORIENTAL);
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    setAdvancementText(progress, PopulationType.Civilization.ORIENTAL);
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                }
            });
        }
    }

    // Init number
    int color = attributes.getColor(R.styleable.SimpleNumberPicker_snpKeyColor,
            ContextCompat.getColor(getContext(), android.R.color.secondary_text_light));
    numberTextView = (TextView) view.findViewById(R.id.tv_hex_number);
    numberTextView.setTextColor(color);
    if (null != savedInstanceState && savedInstanceState.containsKey(ARG_SAVED_VALUE))
        numberTextView.setText(savedInstanceState.getString(ARG_SAVED_VALUE));
    else if (forceHouse)
        numberTextView.setText("");
    // Init backspace
    color = attributes.getColor(R.styleable.SimpleNumberPicker_snpBackspaceColor,
            ContextCompat.getColor(getContext(), android.R.color.secondary_text_light));
    backspaceButton = (ImageButton) view.findViewById(R.id.key_backspace);
    backspaceButton.setImageDrawable(
            ThemeUtil.makeSelector(getContext(), R.drawable.snp_ic_backspace_black_24dp, color));
    backspaceButton.setOnClickListener(v -> {
        if (numberTextView.getText().length() == 1 && forceHouse)
            return;

        CharSequence number = numberTextView.getText().subSequence(0, numberTextView.getText().length() - 1);
        if (1 == number.length() && '-' == number.charAt(0))
            number = "";
        numberTextView.setText(number);
        onNumberChanged();
    });
    backspaceButton.setOnLongClickListener(v -> {
        numberTextView.setText("");
        onNumberChanged();
        return true;
    });

    // Create dialog
    dialog = new AlertDialog.Builder(getContext(), theme).setView(view)
            .setPositiveButton(android.R.string.ok, (dialog12, which) -> {
                String result = numberTextView.getText().toString();
                if (result.isEmpty())
                    result = "0";
                result = result.replace(',', '.');
                result = result.replace("", "-");
                if (result.equals("-"))
                    result = "0";
                final int number = Integer.parseInt(result);

                handleDialogFinish(number);
                dismiss();
            }).setNegativeButton(android.R.string.cancel, (dialog1, which) -> dismiss()).create();

    // Init dialog
    color = attributes.getColor(R.styleable.SimpleNumberPicker_snpDialogBackground,
            ContextCompat.getColor(getContext(), android.R.color.white));
    if (dialog.getWindow() != null) {
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(color));
    }

    // Init keys
    View.OnClickListener listener = v -> {
        int key = (int) v.getTag();
        String id = numberTextView.getText() + Integer.toString(key);
        numberTextView.setText(id);
        onNumberChanged();
    };

    color = attributes.getColor(R.styleable.SimpleNumberPicker_snpKeyColor,
            ThemeUtil.getThemeAccentColor(getContext()));
    TypedArray ids = getResources().obtainTypedArray(R.array.snp_key_ids);
    for (int i = 0; i < NB_KEYS; i++) {
        TextView key = (TextView) view.findViewById(ids.getResourceId(i, -1));
        key.setTag(i);
        key.setOnClickListener(listener);
        key.setTextColor(color);
    }

    // Init sign
    TextView sign = (TextView) view.findViewById(R.id.key_house);
    if (!this.forceHouse) {
        sign.setTextColor(color);
        sign.setOnClickListener(v -> {
            String number = numberTextView.getText().toString();
            if (number.startsWith("")) {
                numberTextView.setText(number.substring(1));
            } else {
                numberTextView.setText("" + number);
            }
            onNumberChanged();
        });
    } else {
        sign.setVisibility(View.GONE);
    }

    ids.recycle();
    attributes.recycle();

    return dialog;
}

From source file:mx.klozz.xperience.tweaker.fragments.VoltageControlSettings.java

private void showDialog(final int min, final int step, final int total) {
    final LayoutInflater factory = LayoutInflater.from(context);
    final View voltageDialog = factory.inflate(R.layout.voltage_dialog, null);

    final SeekBar voltageSeek = (SeekBar) voltageDialog.findViewById(R.id.voltageSeek);
    final TextView voltageMeter = (TextView) voltageDialog.findViewById(R.id.voltageMeter);

    final String savedMv = mVoltage.getSavedMV();
    final int savedVolt = Integer.parseInt(savedMv);

    voltageMeter.setText(savedMv + um);//from  www  . j av a 2  s .c om
    voltageSeek.setMax(total);
    voltageSeek.setProgress(getNearestStepIndex(savedVolt, vmin, vstep, nvsteps));
    voltageSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar sb, int progress, boolean fromUser) {
            if (fromUser) {
                final String volt = Integer.toString(progress * step + min);
                voltageMeter.setText(volt + um);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });
    new AlertDialog.Builder(context).setTitle(mVoltage.getFreq() + " kHz").setView(voltageDialog)
            .setPositiveButton(getResources().getString(R.string.ps_volt_save),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                            final String value = Integer.toString(voltageSeek.getProgress() * step + min);
                            SharedPreferences.Editor editor = mPreferences.edit();
                            editor.putString(mVoltage.getFreq(), value).commit();
                            mVoltage.setSavedMV(value);
                            mAdapter.notifyDataSetChanged();
                        }
                    })
            .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    dialog.cancel();
                }
            }).create().show();
}

From source file:com.wallerlab.compcellscope.Image_Gallery.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image__gallery);
    counter = 0;//w  ww.j  a v a  2  s  .c  o m
    final ImageView currPic = new ImageView(this);

    DisplayMetrics metrics = this.getResources().getDisplayMetrics();
    final int screen_width = metrics.widthPixels;

    SharedPreferences settings = getSharedPreferences(Folder_Chooser.PREFS_NAME, 0);
    //SharedPreferences.Editor edit = settings.edit();
    String path = settings.getString(Folder_Chooser.location_name,
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString());

    //Log.d(LOG, "  |  " + path + " |  ");
    TextView text1 = (TextView) findViewById(R.id.text1);
    final TextView text2 = (TextView) findViewById(R.id.text2);

    text1.setText(path);

    File directory = new File(path);

    // get all the files from a directory
    File[] dump_files = directory.listFiles();
    Log.d(LOG, dump_files.length + " ");

    final File[] fList = removeElements(dump_files, "info.json");

    Log.d(LOG, "Filtered Length: " + fList.length);

    Arrays.sort(fList, new Comparator<File>() {
        @Override
        public int compare(File file, File file2) {
            String one = file.toString();
            String two = file2.toString();
            //Log.d(LOG, "one: " + one);
            //Log.d(LOG, "two: " + two);
            int num_one = Integer.parseInt(one.substring(one.lastIndexOf("(") + 1, one.lastIndexOf(")")));
            int num_two = Integer.parseInt(two.substring(two.lastIndexOf("(") + 1, two.lastIndexOf(")")));
            return num_one - num_two;
        }
    });

    try {
        writeJsonFile(fList);
    } catch (JSONException e) {
        Log.d(LOG, "JSON WRITE FAILED");
    }
    //List names programattically
    LinearLayout myLinearLayout = (LinearLayout) findViewById(R.id.linear_table);
    final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, screen_width + 4);

    myLinearLayout.setOrientation(LinearLayout.VERTICAL);

    if (fList != null) {
        File cur_pic = fList[0];

        BitmapFactory.Options opts = new BitmapFactory.Options();
        Log.d(LOG, "\n File Location: " + cur_pic.getAbsolutePath() + " \n" + " Parent: "
                + cur_pic.getParent().toString() + "\n");

        Bitmap myImage = BitmapFactory.decodeFile(cur_pic.getAbsolutePath(), opts);

        currPic.setLayoutParams(params);
        currPic.setImageBitmap(myImage);
        currPic.setId(View.generateViewId());
        text2.setText(cur_pic.getName());
    }

    myLinearLayout.addView(currPic);

    //Seekbar
    seekBar = (SeekBar) findViewById(R.id.seekBar);
    seekBar.setEnabled(true);
    seekBar.setMax(fList.length - 1);
    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        int progress = 0;
        int length = fList.length;

        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            setCounter(i);
            if (getCounter() <= fList.length) {
                File cur_pic = fList[getCounter()];
                BitmapFactory.Options opts = new BitmapFactory.Options();
                opts.inJustDecodeBounds = true;
                Bitmap myImage = BitmapFactory.decodeFile(cur_pic.getAbsolutePath(), opts);
                int image_width = opts.outWidth;
                int image_height = opts.outHeight;
                int sampleSize = image_width / screen_width;
                opts.inSampleSize = sampleSize;

                text2.setText(cur_pic.getName());

                opts.inJustDecodeBounds = false;
                myImage = BitmapFactory.decodeFile(cur_pic.getAbsolutePath(), opts);

                currPic.setImageBitmap(myImage);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    //Make Button Layout
    LinearLayout buttonLayout = new LinearLayout(this);
    buttonLayout.setOrientation(LinearLayout.HORIZONTAL);

    LinearLayout.LayoutParams LLParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f);
    buttonLayout.setLayoutParams(LLParams);
    buttonLayout.setId(View.generateViewId());

    //Button Layout Params
    LinearLayout.LayoutParams param_button = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);

    //Prev Pic
    Button prevPic = new Button(this);
    prevPic.setText("Previous");
    prevPic.setId(View.generateViewId());
    prevPic.setLayoutParams(param_button);

    prevPic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (fList != null) {
                decrementCounter();
                if (getCounter() >= 0) {
                    File cur_pic = fList[getCounter()];
                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    Bitmap myImage = BitmapFactory.decodeFile(cur_pic.getAbsolutePath(), opts);
                    int image_width = opts.outWidth;
                    int image_height = opts.outHeight;
                    int sampleSize = image_width / screen_width;
                    opts.inSampleSize = sampleSize;

                    text2.setText(cur_pic.getName());

                    opts.inJustDecodeBounds = false;
                    myImage = BitmapFactory.decodeFile(cur_pic.getAbsolutePath(), opts);
                    //Log.d(LOG, getCounter() + "");
                    seekBar.setProgress(getCounter());
                    currPic.setImageBitmap(myImage);

                } else {
                    setCounter(0);
                }

            } else {
                Toast.makeText(Image_Gallery.this, "There are no pictures in this folder", Toast.LENGTH_SHORT);
                setCounter(getCounter() - 1);
            }
        }
    });

    buttonLayout.addView(prevPic);

    // Next Picture  Button
    Button nextPic = new Button(this);
    nextPic.setText("Next");
    nextPic.setId(View.generateViewId());
    nextPic.setLayoutParams(param_button);

    buttonLayout.addView(nextPic);
    nextPic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (fList != null) {
                incrementCounter();
                if (getCounter() < fList.length) {
                    File cur_pic = fList[getCounter()];
                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    Bitmap myImage = BitmapFactory.decodeFile(cur_pic.getAbsolutePath(), opts);
                    int image_width = opts.outWidth;
                    int image_height = opts.outHeight;
                    int sampleSize = image_width / screen_width;
                    opts.inSampleSize = sampleSize;

                    text2.setText(cur_pic.getName());

                    opts.inJustDecodeBounds = false;
                    myImage = BitmapFactory.decodeFile(cur_pic.getAbsolutePath(), opts);
                    //Log.d(LOG, getCounter() + "");
                    seekBar.setProgress(getCounter());

                    currPic.setImageBitmap(myImage);
                } else {
                    setCounter(getCounter() - 1);
                }

            } else {
                Toast.makeText(Image_Gallery.this, "There are no pictures in this folder", Toast.LENGTH_SHORT);
                setCounter(getCounter() - 1);
            }
        }
    });

    myLinearLayout.addView(buttonLayout);
}