Example usage for android.widget ToggleButton setChecked

List of usage examples for android.widget ToggleButton setChecked

Introduction

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

Prototype

@Override
    public void setChecked(boolean checked) 

Source Link

Usage

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

/**
 * Initializes the SSL related UI widget properties and event handlers to deal with user
 * interactions.//from  www.j  a v  a 2  s.c o m
 */
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:org.openremote.android.console.AppSettingsActivity.java

/**
 * Creates the auto layout./*www.  ja v  a2s .  co  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:babybear.akbquiz.ConfigActivity.java

/**
 * ?//  w w  w .  ja  v  a2s .  c  o m
 */
private void init() {

    ToggleButton bgm_toggle = (ToggleButton) findViewById(R.id.bgm_switch);
    ToggleButton sound_toggle = (ToggleButton) findViewById(R.id.sound_switch);
    ToggleButton vibration_toggle = (ToggleButton) findViewById(R.id.config_vibration_switch);
    SeekBar bgm_vol = (SeekBar) findViewById(R.id.bgm_volume);
    SeekBar sound_vol = (SeekBar) findViewById(R.id.sound_volume);
    Button config_playlist = (Button) findViewById(R.id.config_playlist);

    bgm_toggle.setChecked(sp_cfg.getBoolean(Database.KEY_switch_bg, true));
    sound_toggle.setChecked(sp_cfg.getBoolean(Database.KEY_switch_sound, true));
    vibration_toggle.setChecked(sp_cfg.getBoolean(Database.KEY_switch_vibration, true));
    bgm_vol.setProgress(sp_cfg.getInt(Database.KEY_vol_bg, 10));
    sound_vol.setProgress(sp_cfg.getInt(Database.KEY_vol_sound, 10));

    // ?
    loopmode = sp_cfg.getInt(Database.KEY_bgm_loopmode, BgMusic.MODE_LOOP);
    switch (loopmode) {
    case BgMusic.MODE_LOOP:
        ((Button) findViewById(R.id.config_loopmode)).setText(R.string.config_loop);
    case BgMusic.MODE_RANDOM:
        ((Button) findViewById(R.id.config_loopmode)).setText(R.string.config_random);
    case BgMusic.MODE_SINGLE:
        ((Button) findViewById(R.id.config_loopmode)).setText(R.string.config_single);
    }
    // ?

    if (sp_cfg.getBoolean(Database.KEY_use_custom_background, false)) {
        cfgflipper.setBackgroundDrawable(Drawable.createFromPath(customBgImage.getPath()));
    }

    OnClickListener clickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.bgm_switch:
                boolean isBgOn = ((ToggleButton) v).isChecked();
                cfgEditor.putBoolean(Database.KEY_switch_bg, isBgOn);
                Message msg = new Message();
                msg.what = isBgOn ? 1 : 0;
                msg.arg1 = BgMusic.BGHandler.SWITCH_CHANGE;
                BgMusic.bgHandler.sendMessage(msg);
                break;
            case R.id.sound_switch:
                boolean isSoundOn = ((ToggleButton) v).isChecked();
                cfgEditor.putBoolean(Database.KEY_switch_sound, isSoundOn);
                MainMenu.se.setSwitch(isSoundOn);
                break;
            case R.id.config_vibration_switch:
                boolean isVibOn = ((ToggleButton) v).isChecked();
                cfgEditor.putBoolean(Database.KEY_switch_vibration, isVibOn);
                break;
            case R.id.config_playlist:
                if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                    if (!isPlaylistChanged) {
                        loadPlaylistEditor();
                    }

                    cfgflipper.showNext();

                } else {
                    Toast.makeText(ConfigActivity.this, R.string.sdcard_unavailable, Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.config_ranking:
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("market://details?id=" + getPackageName()));
                startActivity(intent);
                break;

            case R.id.config_back:
                cfgEditor.commit();
                finish();
                break;

            case R.id.config_musiclist_back:
            case R.id.config_playlist_back:
                cfgflipper.showPrevious();
                break;

            case R.id.config_update:
                verCode = getVerCode(ConfigActivity.this);
                verName = getVerName(ConfigActivity.this);
                if (getServerVer()) {
                    if (newVerCode > verCode) {
                        doNewVersionUpdate(); // 
                    } else {
                        notNewVersionShow(); // ???
                    }
                }

                break;
            case R.id.config_loopmode:
                changeLoopMode();
                break;
            case R.id.config_quiz_submit:
                Intent intent1 = new Intent(ConfigActivity.this, CollectQuiz.class);
                startActivity(intent1);
                break;
            case R.id.config_change_bgimage:
                customBgImage();
                break;
            case R.id.config_restore_bgimage:
                restoreBgImage();
                break;
            case R.id.call_calendar_editor:
                Intent calendar = new Intent(ConfigActivity.this, CalendarEditor.class);
                startActivity(calendar);
                break;
            case R.id.who_are_we:
                if (aboutFHS == null) {
                    aboutFHS = (new AlertDialog.Builder(ConfigActivity.this)).setTitle(R.string.who_are_we)
                            .setMessage(R.string.about_fhs).setIcon(R.drawable.fhs_logo_48)
                            .setPositiveButton(android.R.string.ok, null).create();
                }
                aboutFHS.show();
                break;
            case R.id.licence:
                if (license == null) {
                    license = (new AlertDialog.Builder(ConfigActivity.this)).setTitle(R.string.license_title)
                            .setIcon(android.R.drawable.stat_sys_warning).setMessage(R.string.license)
                            .setPositiveButton(android.R.string.ok, null).create();
                }
                license.show();
                break;
            }
        }

    };

    bgm_toggle.setOnClickListener(clickListener);
    sound_toggle.setOnClickListener(clickListener);
    vibration_toggle.setOnClickListener(clickListener);
    config_playlist.setOnClickListener(clickListener);

    ((Button) findViewById(R.id.config_back)).setOnClickListener(clickListener);
    ((Button) findViewById(R.id.config_musiclist_back)).setOnClickListener(clickListener);
    ((Button) findViewById(R.id.config_playlist_back)).setOnClickListener(clickListener);
    ((Button) findViewById(R.id.config_update)).setOnClickListener(clickListener);
    ((Button) findViewById(R.id.config_quiz_submit)).setOnClickListener(clickListener);
    ((Button) findViewById(R.id.config_ranking)).setOnClickListener(clickListener);
    ((Button) findViewById(R.id.config_loopmode)).setOnClickListener(clickListener);
    ((Button) findViewById(R.id.config_change_bgimage)).setOnClickListener(clickListener);
    ((Button) findViewById(R.id.config_restore_bgimage)).setOnClickListener(clickListener);
    ((Button) findViewById(R.id.call_calendar_editor)).setOnClickListener(clickListener);
    ((Button) findViewById(R.id.who_are_we)).setOnClickListener(clickListener);
    ((Button) findViewById(R.id.licence)).setOnClickListener(clickListener);

    OnSeekBarChangeListener l_seekbar = new OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
            switch (arg0.getId()) {
            case R.id.bgm_volume:
                cfgEditor.putInt(Database.KEY_vol_bg, arg1);
                Message msg = new Message();
                msg.what = arg1;
                msg.arg1 = BgMusic.BGHandler.VOL_CHANGE;
                BgMusic.bgHandler.sendMessage(msg);
                break;
            case R.id.sound_volume:
                cfgEditor.putInt(Database.KEY_vol_sound, arg1);
                MainMenu.se.setVolume(arg1);
                break;
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar arg0) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar arg0) {

        }

    };
    bgm_vol.setOnSeekBarChangeListener(l_seekbar);
    sound_vol.setOnSeekBarChangeListener(l_seekbar);
}

From source file:com.esri.squadleader.view.SquadLeaderActivity.java

public SquadLeaderActivity() throws SocketException {
    super();/*from ww w  .j a v a  2  s  .  c o m*/
    chemLightCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            for (int j = 0; j < group.getChildCount(); j++) {
                final ToggleButton view = (ToggleButton) group.getChildAt(j);
                view.setChecked(view.getId() == checkedId);
            }
        }
    };

    defaultOnSingleTapListener = createDefaultOnSingleTapListener();
}

From source file:nz.Intelx.DroidNetLogin.DroidNetLoginActivity.java

private void updateUI() {

    LoginFragment Login_Fragment = (LoginFragment) getSupportFragmentManager()
            .findFragmentByTag("android:switcher:" + R.id.pager + ":0");

    if (Login_Fragment != null && Login_Fragment.getView() != null) {
        TextView t = (TextView) Login_Fragment.getActivity().findViewById(R.id.Status);
        TextView t2 = (TextView) Login_Fragment.getActivity().findViewById(R.id.Usage);
        TextView t3 = (TextView) Login_Fragment.getActivity().findViewById(R.id.proxy_status);
        ToggleButton b = (ToggleButton) Login_Fragment.getActivity().findViewById(R.id.Auto);

        Status = preferences.getInt("Status", -1);
        Proxy = preferences.getBoolean("Proxy", false);
        IP_Usage = preferences.getInt("IP_Usage", 0);

        switch (Status) {
        case 1:/* w w w  .  j  a v a2s .c  om*/
            t.setText("Status: Logging in");
            break;
        case 2:
            t.setText("Status: Connected!");
            break;
        case 3:
            t.setText("Status: Disconnected");
            break;
        case 4:
            t.setText("Status: Error");
            break;
        }

        BigDecimal Usage = new BigDecimal(IP_Usage);

        t2.setText("Usage: " + Usage.divide(new BigDecimal(1000)) + " MB");

        if (Proxy) {
            t3.setText("Proxy: Started");
        } else {
            t3.setText("Proxy: Stopped");
        }

        if (Proxy_Option) {
            if (Status == 2 && Proxy == true) {
                b.setChecked(true);
            } else {
                b.setChecked(false);
            }
        } else {
            if (Status == 2) {
                b.setChecked(true);
            } else {
                b.setChecked(false);
            }
        }

    }
}

From source file:foam.jellyfish.StarwispBuilder.java

public void Update(final StarwispActivity ctx, final String ctxname, JSONArray arr) {
    try {/*from   ww  w.  j av a2  s . co m*/

        String type = arr.getString(0);
        final Integer id = arr.getInt(1);
        String token = arr.getString(2);

        Log.i("starwisp", "Update: " + type + " " + id + " " + token);

        // non widget commands
        if (token.equals("toast")) {
            Toast msg = Toast.makeText(ctx.getBaseContext(), arr.getString(3), Toast.LENGTH_SHORT);
            msg.show();
            return;
        }

        if (type.equals("replace-fragment")) {
            int ID = arr.getInt(1);
            String name = arr.getString(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            FragmentTransaction ft = ctx.getSupportFragmentManager().beginTransaction();

            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

            //ft.setCustomAnimations(
            //    R.animator.card_flip_right_in, R.animator.card_flip_right_out,
            //    R.animator.card_flip_left_in, R.animator.card_flip_left_out);
            ft.replace(ID, fragment);
            //ft.addToBackStack(null);
            ft.commit();
            return;
        }

        if (token.equals("dialog-fragment")) {
            FragmentManager fm = ctx.getSupportFragmentManager();
            final int ID = arr.getInt(3);
            final JSONArray lp = arr.getJSONArray(4);
            final String name = arr.getString(5);

            final Dialog dialog = new Dialog(ctx);
            dialog.setTitle("Title...");

            LinearLayout inner = new LinearLayout(ctx);
            inner.setId(ID);
            inner.setLayoutParams(BuildLayoutParams(lp));

            dialog.setContentView(inner);

            //                Fragment fragment = ActivityManager.GetFragment(name);
            //                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            //                fragmentTransaction.add(ID,fragment);
            //                fragmentTransaction.commit();

            dialog.show();

            /*                DialogFragment df = new DialogFragment() {
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                LinearLayout inner = new LinearLayout(ctx);
                inner.setId(ID);
                inner.setLayoutParams(BuildLayoutParams(lp));
                    
                return inner;
            }
                    
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                Dialog ret = super.onCreateDialog(savedInstanceState);
                Log.i("starwisp","MAKINGDAMNFRAGMENT");
                    
                Fragment fragment = ActivityManager.GetFragment(name);
                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
                fragmentTransaction.add(1,fragment);
                fragmentTransaction.commit();
                return ret;
            }
                            };
                            df.show(ctx.getFragmentManager(), "foo");
            */
        }

        if (token.equals("time-picker-dialog")) {

            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            TimePickerDialog d = new TimePickerDialog(ctx, null, hour, minute, true);
            d.show();
            return;
        }
        ;

        if (token.equals("make-directory")) {
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(3));
            file.mkdirs();
            return;
        }

        if (token.equals("list-files")) {
            final String name = arr.getString(3);
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(5));
            // todo, should probably call callback with empty list
            if (file != null) {
                File list[] = file.listFiles();

                if (list != null) {
                    String code = "(";
                    for (int i = 0; i < list.length; i++) {
                        code += " \"" + list[i].getName() + "\"";
                    }
                    code += ")";

                    DialogCallback(ctx, ctxname, name, code);
                }
            }
            return;
        }

        if (token.equals("delayed")) {
            final String name = arr.getString(3);
            final int d = arr.getInt(5);
            Runnable timerThread = new Runnable() {
                public void run() {
                    DialogCallback(ctx, ctxname, name, "");
                }
            };
            m_Handler.removeCallbacksAndMessages(null);
            m_Handler.postDelayed(timerThread, d);
            return;
        }

        if (token.equals("network-connect")) {
            if (m_NetworkManager.state == NetworkManager.State.IDLE) {
                final String name = arr.getString(3);
                final String ssid = arr.getString(5);
                m_NetworkManager.Start(ssid, (StarwispActivity) ctx, name, this);
            }
            return;
        }

        if (token.equals("http-request")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http request");
                final String name = arr.getString(3);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "normal", name);
            }
            return;
        }

        if (token.equals("http-download")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http dl request");
                final String filename = arr.getString(4);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "download", filename);
            }
            return;
        }

        if (token.equals("send-mail")) {
            final String to[] = new String[1];
            to[0] = arr.getString(3);
            final String subject = arr.getString(4);
            final String body = arr.getString(5);

            JSONArray attach = arr.getJSONArray(6);
            ArrayList<String> paths = new ArrayList<String>();
            for (int a = 0; a < attach.length(); a++) {
                Log.i("starwisp", attach.getString(a));
                paths.add(attach.getString(a));
            }

            email(ctx, to[0], "", subject, body, paths);
        }

        if (token.equals("date-picker-dialog")) {
            final Calendar c = Calendar.getInstance();
            int day = c.get(Calendar.DAY_OF_MONTH);
            int month = c.get(Calendar.MONTH);
            int year = c.get(Calendar.YEAR);

            final String name = arr.getString(3);

            // Create a new instance of TimePickerDialog and return it
            DatePickerDialog d = new DatePickerDialog(ctx, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int month, int day) {
                    DialogCallback(ctx, ctxname, name, day + " " + month + " " + year);
                }
            }, year, month, day);
            d.show();
            return;
        }
        ;

        if (token.equals("alert-dialog")) {

            final String name = arr.getString(3);
            final String msg = arr.getString(5);

            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int result = 0;
                    if (which == DialogInterface.BUTTON_POSITIVE)
                        result = 1;
                    DialogCallback(ctx, ctxname, name, "" + result);
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
            builder.setMessage(msg).setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();

            return;
        }

        if (token.equals("start-activity")) {
            ActivityManager.StartActivity(ctx, arr.getString(3), arr.getInt(4), arr.getString(5));
            return;
        }

        if (token.equals("start-activity-goto")) {
            ActivityManager.StartActivityGoto(ctx, arr.getString(3), arr.getString(4));
            return;
        }

        if (token.equals("finish-activity")) {
            ctx.setResult(arr.getInt(3));
            ctx.finish();
            return;
        }

        ///////////////////////////////////////////////////////////

        // now try and find the widget
        View vv = ctx.findViewById(id);
        if (vv == null) {
            Log.i("starwisp", "Can't find widget : " + id);
            return;
        }

        // tokens that work on everything
        if (token.equals("hide")) {
            vv.setVisibility(View.GONE);
            return;
        }

        if (token.equals("show")) {
            vv.setVisibility(View.VISIBLE);
            return;
        }

        // tokens that work on everything
        if (token.equals("set-enabled")) {
            vv.setEnabled(arr.getInt(3) == 1);
            return;
        }

        // special cases
        if (type.equals("linear-layout")) {
            LinearLayout v = (LinearLayout) vv;
            if (token.equals("contents")) {
                v.removeAllViews();
                JSONArray children = arr.getJSONArray(3);
                for (int i = 0; i < children.length(); i++) {
                    Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
                }
            }
        }

        if (type.equals("button-grid")) {
            Log.i("starwisp", "button-grid update");
            LinearLayout horiz = (LinearLayout) vv;
            if (token.equals("grid-buttons")) {
                Log.i("starwisp", "button-grid contents");
                horiz.removeAllViews();

                JSONArray params = arr.getJSONArray(3);
                String buttontype = params.getString(0);
                int height = params.getInt(1);
                int textsize = params.getInt(2);
                LinearLayout.LayoutParams lp = BuildLayoutParams(params.getJSONArray(3));
                final JSONArray buttons = params.getJSONArray(4);
                final int count = buttons.length();
                int vertcount = 0;
                LinearLayout vert = null;

                for (int i = 0; i < count; i++) {
                    JSONArray button = buttons.getJSONArray(i);

                    if (vertcount == 0) {
                        vert = new LinearLayout(ctx);
                        vert.setId(0);
                        vert.setOrientation(LinearLayout.VERTICAL);
                        horiz.addView(vert);
                    }
                    vertcount = (vertcount + 1) % height;

                    if (buttontype.equals("button")) {
                        Button b = new Button(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("toggle")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                String arg = "#f";
                                if (((ToggleButton) v).isChecked())
                                    arg = "#t";
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("single")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                try {
                                    for (int i = 0; i < count; i++) {
                                        JSONArray button = buttons.getJSONArray(i);
                                        int bid = button.getInt(0);
                                        if (bid != v.getId()) {
                                            ToggleButton tb = (ToggleButton) ctx.findViewById(bid);
                                            tb.setChecked(false);
                                        }
                                    }
                                } catch (JSONException e) {
                                    Log.e("starwisp", "Error parsing data " + e.toString());
                                }

                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    }

                }
            }
        }

        /*
                    if (type.equals("grid-layout")) {
        GridLayout v = (GridLayout)vv;
        if (token.equals("contents")) {
            v.removeAllViews();
            JSONArray children = arr.getJSONArray(3);
            for (int i=0; i<children.length(); i++) {
                Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
            }
        }
                    }
        */
        if (type.equals("view-pager")) {
            ViewPager v = (ViewPager) vv;
            if (token.equals("switch")) {
                v.setCurrentItem(arr.getInt(3));
            }
            if (token.equals("pages")) {
                final JSONArray items = arr.getJSONArray(3);
                v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {
                    @Override
                    public int getCount() {
                        return items.length();
                    }

                    @Override
                    public Fragment getItem(int position) {
                        try {
                            String fragname = items.getString(position);
                            return ActivityManager.GetFragment(fragname);
                        } catch (JSONException e) {
                            Log.e("starwisp", "Error parsing data " + e.toString());
                        }
                        return null;
                    }
                });
            }
        }

        if (type.equals("image-view")) {
            ImageView v = (ImageView) vv;
            if (token.equals("image")) {
                int iid = ctx.getResources().getIdentifier(arr.getString(3), "drawable", ctx.getPackageName());
                v.setImageResource(iid);
            }
            if (token.equals("external-image")) {
                Bitmap bitmap = BitmapFactory.decodeFile(arr.getString(3));
                v.setImageBitmap(bitmap);
            }
            return;
        }

        if (type.equals("text-view") || type.equals("debug-text-view")) {
            Log.i("starwisp", "text-view...");
            TextView v = (TextView) vv;
            if (token.equals("text")) {
                if (type.equals("debug-text-view")) {
                    //v.setMovementMethod(new ScrollingMovementMethod());
                }
                v.setText(arr.getString(3));
            }
            return;
        }

        if (type.equals("edit-text")) {
            EditText v = (EditText) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }
            return;
        }

        if (type.equals("button")) {
            Button v = (Button) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = (ToggleButton) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
                return;
            }

            if (token.equals("checked")) {
                if (arr.getInt(3) == 0)
                    v.setChecked(false);
                else
                    v.setChecked(true);
                return;
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        /*
                    if (type.equals("canvas")) {
        StarwispCanvas v = (StarwispCanvas)vv;
        if (token.equals("drawlist")) {
            v.SetDrawList(arr.getJSONArray(3));
        }
        return;
                    }
                
                    if (type.equals("camera-preview")) {
        final CameraPreview v = (CameraPreview)vv;
                
        if (token.equals("take-picture")) {
            final String path = ((StarwispActivity)ctx).m_AppDir+arr.getString(3);
                
            v.TakePicture(
                new PictureCallback() {
                    public void onPictureTaken(byte[] data, Camera camera) {
                        String datetime = getDateTime();
                        String filename = path+datetime + ".jpg";
                        SaveData(filename,data);
                        v.Shutdown();
                        ctx.finish();
                    }
                });
        }
                
        if (token.equals("shutdown")) {
            v.Shutdown();
        }
                
        return;
                    }
        */
        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            if (token.equals("max")) {
                // android seekbar bug workaround
                int p = v.getProgress();
                v.setMax(0);
                v.setProgress(0);
                v.setMax(arr.getInt(3));
                v.setProgress(1000);

                // not working.... :(
            }
        }

        if (type.equals("spinner")) {
            Spinner v = (Spinner) vv;

            if (token.equals("selection")) {
                v.setSelection(arr.getInt(3));
            }

            if (token.equals("array")) {
                final JSONArray items = arr.getJSONArray(3);
                ArrayList<String> spinnerArray = new ArrayList<String>();

                for (int i = 0; i < items.length(); i++) {
                    spinnerArray.add(items.getString(i));
                }

                ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx,
                        android.R.layout.simple_spinner_item, spinnerArray) {
                    public View getView(int position, View convertView, ViewGroup parent) {
                        View v = super.getView(position, convertView, parent);
                        ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                        return v;
                    }
                };

                v.setAdapter(spinnerArrayAdapter);

                final int wid = id;
                // need to update for new values
                v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
                        try {
                            CallbackArgs(ctx, ctxname, wid, "\"" + items.getString(pos) + "\"");
                        } catch (JSONException e) {
                            Log.e("starwisp", "Error parsing data " + e.toString());
                        }
                    }

                    public void onNothingSelected(AdapterView<?> v) {
                    }
                });

            }
            return;
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing data " + e.toString());
    }
}

From source file:foam.mongoose.StarwispBuilder.java

public void Update(final StarwispActivity ctx, final String ctxname, JSONArray arr) {
    try {//from   w  w w  .java  2s.c o m

        String type = arr.getString(0);
        final Integer id = arr.getInt(1);
        String token = arr.getString(2);

        //Log.i("starwisp", "Update: "+type+" "+id+" "+token);

        // non widget commands
        if (token.equals("toast")) {
            Toast msg = Toast.makeText(ctx.getBaseContext(), arr.getString(3), Toast.LENGTH_SHORT);
            msg.show();
            return;
        }

        if (token.equals("play-sound")) {
            String name = arr.getString(3);

            if (name.equals("ping")) {
                MediaPlayer mp = MediaPlayer.create(ctx, R.raw.ping);
                mp.start();
            }
            if (name.equals("active")) {
                MediaPlayer mp = MediaPlayer.create(ctx, R.raw.active);
                mp.start();
            }
        }

        if (token.equals("vibrate")) {
            Vibrator v = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(arr.getInt(3));
        }

        if (type.equals("replace-fragment")) {
            int ID = arr.getInt(1);
            String name = arr.getString(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            FragmentTransaction ft = ctx.getSupportFragmentManager().beginTransaction();

            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

            //ft.setCustomAnimations(
            //    R.animator.card_flip_right_in, R.animator.card_flip_right_out,
            //    R.animator.card_flip_left_in, R.animator.card_flip_left_out);
            ft.replace(ID, fragment);
            //ft.addToBackStack(null);
            ft.commit();
            return;
        }

        if (token.equals("dialog-fragment")) {
            FragmentManager fm = ctx.getSupportFragmentManager();
            final int ID = arr.getInt(3);
            final JSONArray lp = arr.getJSONArray(4);
            final String name = arr.getString(5);

            final Dialog dialog = new Dialog(ctx);
            dialog.setTitle("Title...");

            LinearLayout inner = new LinearLayout(ctx);
            inner.setId(ID);
            inner.setLayoutParams(BuildLayoutParams(lp));

            dialog.setContentView(inner);

            //                Fragment fragment = ActivityManager.GetFragment(name);
            //                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            //                fragmentTransaction.add(ID,fragment);
            //                fragmentTransaction.commit();

            dialog.show();

            /*                DialogFragment df = new DialogFragment() {
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                LinearLayout inner = new LinearLayout(ctx);
                inner.setId(ID);
                inner.setLayoutParams(BuildLayoutParams(lp));
                    
                return inner;
            }
                    
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                Dialog ret = super.onCreateDialog(savedInstanceState);
                Log.i("starwisp","MAKINGDAMNFRAGMENT");
                    
                Fragment fragment = ActivityManager.GetFragment(name);
                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
                fragmentTransaction.add(1,fragment);
                fragmentTransaction.commit();
                return ret;
            }
                            };
                            df.show(ctx.getFragmentManager(), "foo");
            */
        }

        if (token.equals("time-picker-dialog")) {

            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            TimePickerDialog d = new TimePickerDialog(ctx, null, hour, minute, true);
            d.show();
            return;
        }
        ;

        if (token.equals("make-directory")) {
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(3));
            file.mkdirs();
            return;
        }

        if (token.equals("list-files")) {
            final String name = arr.getString(3);
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(5));
            // todo, should probably call callback with empty list
            if (file != null) {
                File list[] = file.listFiles();

                if (list != null) {
                    String code = "(";
                    for (int i = 0; i < list.length; i++) {
                        code += " \"" + list[i].getName() + "\"";
                    }
                    code += ")";

                    DialogCallback(ctx, ctxname, name, code);
                }
            }
            return;
        }

        if (token.equals("gps-start")) {
            final String name = arr.getString(3);

            if (m_LocationManager == null) {
                m_LocationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
                m_GPS = new DorisLocationListener(m_LocationManager);
            }

            m_GPS.Start((StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("delayed")) {
            final String name = arr.getString(3);
            final int d = arr.getInt(5);
            Runnable timerThread = new Runnable() {
                public void run() {
                    DialogCallback(ctx, ctxname, name, "");
                }
            };
            m_Handler.removeCallbacksAndMessages(null);
            m_Handler.postDelayed(timerThread, d);
            return;
        }

        if (token.equals("network-connect")) {
            final String name = arr.getString(3);
            final String ssid = arr.getString(5);
            m_NetworkManager.Start(ssid, (StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("http-request")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http request");
                final String name = arr.getString(3);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "normal", name);
            }
            return;
        }

        if (token.equals("http-download")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http dl request");
                final String filename = arr.getString(4);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "download", filename);
            }
            return;
        }

        if (token.equals("send-mail")) {
            final String to[] = new String[1];
            to[0] = arr.getString(3);
            final String subject = arr.getString(4);
            final String body = arr.getString(5);

            JSONArray attach = arr.getJSONArray(6);
            ArrayList<String> paths = new ArrayList<String>();
            for (int a = 0; a < attach.length(); a++) {
                Log.i("starwisp", attach.getString(a));
                paths.add(attach.getString(a));
            }

            email(ctx, to[0], "", subject, body, paths);
        }

        if (token.equals("date-picker-dialog")) {
            final Calendar c = Calendar.getInstance();
            int day = c.get(Calendar.DAY_OF_MONTH);
            int month = c.get(Calendar.MONTH);
            int year = c.get(Calendar.YEAR);

            final String name = arr.getString(3);

            // Create a new instance of TimePickerDialog and return it
            DatePickerDialog d = new DatePickerDialog(ctx, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int month, int day) {
                    DialogCallback(ctx, ctxname, name, day + " " + month + " " + year);
                }
            }, year, month, day);
            d.show();
            return;
        }
        ;

        if (token.equals("alert-dialog")) {

            final String name = arr.getString(3);
            final String msg = arr.getString(5);

            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int result = 0;
                    if (which == DialogInterface.BUTTON_POSITIVE)
                        result = 1;
                    DialogCallback(ctx, ctxname, name, "" + result);
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
            builder.setMessage(msg).setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();

            return;
        }

        if (token.equals("start-activity")) {
            ActivityManager.StartActivity(ctx, arr.getString(3), arr.getInt(4), arr.getString(5));
            return;
        }

        if (token.equals("start-activity-goto")) {
            ActivityManager.StartActivityGoto(ctx, arr.getString(3), arr.getString(4));
            return;
        }

        if (token.equals("finish-activity")) {
            ctx.setResult(arr.getInt(3));
            ctx.finish();
            return;
        }

        ///////////////////////////////////////////////////////////

        // problem associating the id number
        if (id == 0)
            return;

        // now try and find the widget
        View vv = ctx.findViewById(id);
        if (vv == null) {
            Log.i("starwisp", "Can't find widget : " + id);
            return;
        }

        // tokens that work on everything
        if (token.equals("hide")) {
            vv.setVisibility(View.GONE);
            return;
        }

        if (token.equals("show")) {
            vv.setVisibility(View.VISIBLE);
            return;
        }

        // tokens that work on everything
        if (token.equals("set-enabled")) {
            vv.setEnabled(arr.getInt(3) == 1);
            return;
        }

        // special cases
        if (type.equals("linear-layout")) {
            LinearLayout v = (LinearLayout) vv;
            if (token.equals("contents")) {
                v.removeAllViews();
                JSONArray children = arr.getJSONArray(3);
                for (int i = 0; i < children.length(); i++) {
                    Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
                }
            }
        }

        if (type.equals("button-grid")) {
            LinearLayout horiz = (LinearLayout) vv;
            if (token.equals("grid-buttons")) {
                horiz.removeAllViews();

                JSONArray params = arr.getJSONArray(3);
                String buttontype = params.getString(0);
                int height = params.getInt(1);
                int textsize = params.getInt(2);
                LinearLayout.LayoutParams lp = BuildLayoutParams(params.getJSONArray(3));
                final JSONArray buttons = params.getJSONArray(4);
                final int count = buttons.length();
                int vertcount = 0;
                LinearLayout vert = null;

                for (int i = 0; i < count; i++) {
                    JSONArray button = buttons.getJSONArray(i);

                    if (vertcount == 0) {
                        vert = new LinearLayout(ctx);
                        vert.setId(0);
                        vert.setOrientation(LinearLayout.VERTICAL);
                        horiz.addView(vert);
                    }
                    vertcount = (vertcount + 1) % height;

                    if (buttontype.equals("button")) {
                        Button b = new Button(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("toggle")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                String arg = "#f";
                                if (((ToggleButton) v).isChecked())
                                    arg = "#t";
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("single")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                try {
                                    for (int i = 0; i < count; i++) {
                                        JSONArray button = buttons.getJSONArray(i);
                                        int bid = button.getInt(0);
                                        if (bid != v.getId()) {
                                            ToggleButton tb = (ToggleButton) ctx.findViewById(bid);
                                            tb.setChecked(false);
                                        }
                                    }
                                } catch (JSONException e) {
                                    Log.e("starwisp", "Error parsing data " + e.toString());
                                }

                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    }

                }
            }
        }

        /*
                    if (type.equals("grid-layout")) {
        GridLayout v = (GridLayout)vv;
        if (token.equals("contents")) {
            v.removeAllViews();
            JSONArray children = arr.getJSONArray(3);
            for (int i=0; i<children.length(); i++) {
                Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
            }
        }
                    }
        */
        if (type.equals("view-pager")) {
            ViewPager v = (ViewPager) vv;
            if (token.equals("switch")) {
                v.setCurrentItem(arr.getInt(3));
            }
            if (token.equals("pages")) {
                final JSONArray items = arr.getJSONArray(3);
                v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {
                    @Override
                    public int getCount() {
                        return items.length();
                    }

                    @Override
                    public Fragment getItem(int position) {
                        try {
                            String fragname = items.getString(position);
                            return ActivityManager.GetFragment(fragname);
                        } catch (JSONException e) {
                            Log.e("starwisp", "Error parsing data " + e.toString());
                        }
                        return null;
                    }
                });
            }
        }

        if (type.equals("image-view")) {
            ImageView v = (ImageView) vv;
            if (token.equals("image")) {
                int iid = ctx.getResources().getIdentifier(arr.getString(3), "drawable", ctx.getPackageName());
                v.setImageResource(iid);
            }
            if (token.equals("external-image")) {
                Bitmap bitmap = BitmapFactory.decodeFile(arr.getString(3));
                v.setImageBitmap(bitmap);
            }
            return;
        }

        if (type.equals("text-view") || type.equals("debug-text-view")) {
            TextView v = (TextView) vv;
            if (token.equals("text")) {
                if (type.equals("debug-text-view")) {
                    //v.setMovementMethod(new ScrollingMovementMethod());
                }
                v.setText(arr.getString(3));
            }
            return;
        }

        if (type.equals("edit-text")) {
            EditText v = (EditText) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }
            if (token.equals("request-focus")) {
                v.requestFocus();
                InputMethodManager imm = (InputMethodManager) ctx
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
            }
            return;
        }

        if (type.equals("button")) {
            Button v = (Button) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = (ToggleButton) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
                return;
            }

            if (token.equals("checked")) {
                if (arr.getInt(3) == 0)
                    v.setChecked(false);
                else
                    v.setChecked(true);
                return;
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("canvas")) {
            StarwispCanvas v = (StarwispCanvas) vv;
            if (token.equals("drawlist")) {
                v.SetDrawList(arr.getJSONArray(3));
            }
            return;
        }

        if (type.equals("camera-preview")) {
            final CameraPreview v = (CameraPreview) vv;

            if (token.equals("take-picture")) {
                final String path = ((StarwispActivity) ctx).m_AppDir + arr.getString(3);

                v.TakePicture(new PictureCallback() {
                    public void onPictureTaken(byte[] data, Camera camera) {
                        String datetime = getDateTime();
                        String filename = path + datetime + ".jpg";
                        SaveData(filename, data);
                        v.Shutdown();
                        ctx.finish();
                    }
                });
            }

            if (token.equals("shutdown")) {
                v.Shutdown();
            }

            return;
        }

        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            if (token.equals("max")) {
                // android seekbar bug workaround
                int p = v.getProgress();
                v.setMax(0);
                v.setProgress(0);
                v.setMax(arr.getInt(3));
                v.setProgress(1000);

                // not working.... :(
            }
        }

        if (type.equals("spinner")) {
            Spinner v = (Spinner) vv;

            if (token.equals("selection")) {
                v.setSelection(arr.getInt(3));
            }

            if (token.equals("array")) {
                final JSONArray items = arr.getJSONArray(3);
                ArrayList<String> spinnerArray = new ArrayList<String>();

                for (int i = 0; i < items.length(); i++) {
                    spinnerArray.add(items.getString(i));
                }

                ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx,
                        android.R.layout.simple_spinner_item, spinnerArray) {
                    public View getView(int position, View convertView, ViewGroup parent) {
                        View v = super.getView(position, convertView, parent);
                        ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                        return v;
                    }
                };

                v.setAdapter(spinnerArrayAdapter);

                final int wid = id;
                // need to update for new values
                v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
                        try {
                            CallbackArgs(ctx, ctxname, wid, "\"" + items.getString(pos) + "\"");
                        } catch (JSONException e) {
                            Log.e("starwisp", "Error parsing data " + e.toString());
                        }
                    }

                    public void onNothingSelected(AdapterView<?> v) {
                    }
                });

            }
            return;
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing data " + e.toString());
    }
}

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);/* w  ww  .  ja va2s .  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.coinprism.wallet.fragment.BalanceTab.java

/**
 * Constructs the UI when the activity is first rendered.
 *
 * @param rootView the rootView of the fragment
 *//* ww w  . j a va  2 s  .com*/
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:com.aniruddhc.acemusic.player.EqualizerActivity.EqualizerActivity.java

/**
 * Initializes the ActionBar.//  ww w  .  jav  a2 s .  c o m
 */
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);

}