Example usage for android.app Dialog setContentView

List of usage examples for android.app Dialog setContentView

Introduction

In this page you can find the example usage for android.app Dialog setContentView.

Prototype

public void setContentView(@NonNull View view) 

Source Link

Document

Set the screen content to an explicit view.

Usage

From source file:com.mitre.holdshort.MainActivity.java

private void showDisclaimer() {

    final Dialog dialog = new Dialog(MainActivity.this);
    OnClickListener disclaimerBtnClick;//from  w  w w  .  jav a2  s .  c o  m

    dialog.setContentView(R.layout.legal_stuff_dialog);
    dialog.setTitle("RIPPLE - Informed Consent");
    dialog.setCancelable(false);
    dialog.getWindow().setLayout(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

    TextView consent = (TextView) dialog.findViewById(R.id.disclaimerAccept);
    TextView reject = (TextView) dialog.findViewById(R.id.disclaimerReject);

    disclaimerBtnClick = new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (v.getId() == R.id.disclaimerAccept) {
                settings.edit().putBoolean("consent", true).commit();
                dialog.dismiss();
                waiverAccept = true;
                startUp();
            } else {
                finish();
            }

        }

    };

    consent.setOnClickListener(disclaimerBtnClick);
    reject.setOnClickListener(disclaimerBtnClick);
    dialog.show();

}

From source file:de.cachebox_test.splash.java

@SuppressWarnings("deprecation")
@Override//ww  w .j  a v a 2  s . c o  m
protected void onStart() {
    super.onStart();
    Log.debug(log, "onStart");

    if (android.os.Build.VERSION.SDK_INT >= 23) {
        PermissionCheck.checkNeededPermissions(this);
    }

    // initial GDX
    Gdx.files = new AndroidFiles(this.getAssets(), this.getFilesDir().getAbsolutePath());
    // first, try to find stored preferences of workPath
    androidSetting = this.getSharedPreferences(Global.PREFS_NAME, 0);

    workPath = androidSetting.getString("WorkPath", Environment.getDataDirectory() + "/cachebox");
    boolean askAgain = androidSetting.getBoolean("AskAgain", true);
    showSandbox = androidSetting.getBoolean("showSandbox", false);

    Global.initTheme(this);
    Global.InitIcons(this);

    CB_Android_FileExplorer fileExplorer = new CB_Android_FileExplorer(this);
    PlatformConnector.setGetFileListener(fileExplorer);
    PlatformConnector.setGetFolderListener(fileExplorer);

    String LangPath = androidSetting.getString("Sel_LanguagePath", "");
    if (LangPath.length() == 0) {
        // set default lang

        String locale = Locale.getDefault().getLanguage();
        if (locale.contains("de")) {
            LangPath = "data/lang/de/strings.ini";
        } else if (locale.contains("cs")) {
            LangPath = "data/lang/cs/strings.ini";
        } else if (locale.contains("cs")) {
            LangPath = "data/lang/cs/strings.ini";
        } else if (locale.contains("fr")) {
            LangPath = "data/lang/fr/strings.ini";
        } else if (locale.contains("nl")) {
            LangPath = "data/lang/nl/strings.ini";
        } else if (locale.contains("pl")) {
            LangPath = "data/lang/pl/strings.ini";
        } else if (locale.contains("pt")) {
            LangPath = "data/lang/pt/strings.ini";
        } else if (locale.contains("hu")) {
            LangPath = "data/lang/hu/strings.ini";
        } else {
            LangPath = "data/lang/en-GB/strings.ini";
        }
    }

    new Translation(workPath, FileType.Internal);
    try {
        Translation.LoadTranslation(LangPath);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // check Write permission
    if (!askAgain) {
        if (!FileIO.checkWritePermission(workPath)) {
            askAgain = true;
            if (!ToastEx) {
                ToastEx = true;
                String WriteProtectionMsg = Translation.Get("NoWriteAcces");
                Toast.makeText(splash.this, WriteProtectionMsg, Toast.LENGTH_LONG).show();
            }
        }
    }

    if ((askAgain)) {
        // no saved workPath found -> search sd-cards and if more than 1 is found give the user the possibility to select one

        String externalSd = getExternalSdPath("/CacheBox");

        boolean hasExtSd;
        final String externalSd2 = externalSd;

        if (externalSd != null) {
            hasExtSd = (externalSd.length() > 0) && (!externalSd.equalsIgnoreCase(workPath));
        } else {
            hasExtSd = false;
        }

        // externe SD wurde gefunden != internal
        // oder Tablet Layout mglich
        // -> Auswahldialog anzeigen
        try {
            final Dialog dialog = new Dialog(context) {
                @Override
                public boolean onKeyDown(int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        splash.this.finish();
                    }
                    return super.onKeyDown(keyCode, event);
                }
            };

            dialog.setContentView(R.layout.sdselectdialog);
            TextView title = (TextView) dialog.findViewById(R.id.select_sd_title);
            title.setText(Translation.Get("selectWorkSpace") + "\n\n");
            /*
             * TextView tbLayout = (TextView) dialog.findViewById(R.id.select_sd_layout); tbLayout.setText("\nLayout"); final RadioGroup
             * rgLayout = (RadioGroup) dialog.findViewById(R.id.select_sd_radiogroup); final RadioButton rbHandyLayout = (RadioButton)
             * dialog.findViewById(R.id.select_sd_handylayout); final RadioButton rbTabletLayout = (RadioButton)
             * dialog.findViewById(R.id.select_sd_tabletlayout); rbHandyLayout.setText("Handy-Layout");
             * rbTabletLayout.setText("Tablet-Layout"); if (!GlobalCore.posibleTabletLayout) {
             * rgLayout.setVisibility(RadioGroup.INVISIBLE); rbHandyLayout.setChecked(true); } else { if (GlobalCore.isTab) {
             * rbTabletLayout.setChecked(true); } else { rbHandyLayout.setChecked(true); } }
             */
            final CheckBox cbAskAgain = (CheckBox) dialog.findViewById(R.id.select_sd_askagain);
            cbAskAgain.setText(Translation.Get("AskAgain"));
            cbAskAgain.setChecked(askAgain);
            Button buttonI = (Button) dialog.findViewById(R.id.button1);
            buttonI.setText("Internal SD\n\n" + workPath);
            buttonI.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // close select dialog
                    dialog.dismiss();

                    // show please wait dialog
                    showPleaseWaitDialog();

                    // use internal SD -> nothing to change
                    Thread thread = new Thread() {
                        @Override
                        public void run() {
                            boolean askAgain = cbAskAgain.isChecked();
                            // boolean useTabletLayout = rbTabletLayout.isChecked();
                            saveWorkPath(askAgain/* , useTabletLayout */);
                            dialog.dismiss();
                            startInitial();
                        }
                    };
                    thread.start();
                }
            });
            Button buttonE = (Button) dialog.findViewById(R.id.button2);
            final boolean isSandbox = externalSd == null ? false
                    : externalSd.contains("Android/data/de.cachebox_test");
            if (!hasExtSd) {
                buttonE.setVisibility(Button.INVISIBLE);
            } else {
                String extSdText = isSandbox ? "External SD SandBox\n\n" : "External SD\n\n";
                buttonE.setText(extSdText + externalSd);
            }

            buttonE.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // show KitKat Massage?

                    if (isSandbox && !showSandbox) {
                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

                        // set title
                        alertDialogBuilder.setTitle("KitKat Sandbox");

                        // set dialog message
                        alertDialogBuilder.setMessage(Translation.Get("Desc_Sandbox")).setCancelable(false)
                                .setPositiveButton(Translation.Get("yes"),
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int id) {
                                                // if this button is clicked, run Sandbox Path

                                                showSandbox = true;
                                                Config.AcceptChanges();

                                                // close select dialog
                                                dialog.dismiss();

                                                // show please wait dialog
                                                showPleaseWaitDialog();

                                                // use external SD -> change workPath
                                                Thread thread = new Thread() {
                                                    @Override
                                                    public void run() {
                                                        workPath = externalSd2;
                                                        boolean askAgain = cbAskAgain.isChecked();
                                                        // boolean useTabletLayout = rbTabletLayout.isChecked();
                                                        saveWorkPath(askAgain/* , useTabletLayout */);
                                                        startInitial();
                                                    }
                                                };
                                                thread.start();
                                            }
                                        })
                                .setNegativeButton(Translation.Get("no"),
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int id) {
                                                // if this button is clicked, just close
                                                // the dialog box and do nothing
                                                dialog.cancel();
                                            }
                                        });

                        // create alert dialog
                        AlertDialog alertDialog = alertDialogBuilder.create();

                        // show it
                        alertDialog.show();
                    } else {
                        // close select dialog
                        dialog.dismiss();

                        // show please wait dialog
                        showPleaseWaitDialog();

                        // use external SD -> change workPath
                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                workPath = externalSd2;
                                boolean askAgain = cbAskAgain.isChecked();
                                // boolean useTabletLayout = rbTabletLayout.isChecked();
                                saveWorkPath(askAgain/* , useTabletLayout */);
                                startInitial();
                            }
                        };
                        thread.start();
                    }
                }
            });

            LinearLayout ll = (LinearLayout) dialog.findViewById(R.id.scrollViewLinearLayout);

            // add all Buttons for created Workspaces

            AdditionalWorkPathArray = getAdditionalWorkPathArray();

            for (final String AddWorkPath : AdditionalWorkPathArray) {

                final String Name = FileIO.GetFileNameWithoutExtension(AddWorkPath);

                if (!FileIO.checkWritePermission(AddWorkPath)) {
                    // delete this Work Path
                    deleteWorkPath(AddWorkPath);
                    continue;
                }

                Button buttonW = new Button(context);
                buttonW.setText(Name + "\n\n" + AddWorkPath);

                buttonW.setOnLongClickListener(new OnLongClickListener() {

                    @Override
                    public boolean onLongClick(View v) {

                        // setting the MassageBox then the UI_sizes are not initial in this moment
                        Resources res = splash.this.getResources();
                        float scale = res.getDisplayMetrics().density;
                        float calcBase = 533.333f * scale;

                        FrameLayout frame = (FrameLayout) findViewById(R.id.frameLayout1);
                        int width = frame.getMeasuredWidth();
                        int height = frame.getMeasuredHeight();

                        MessageBox.Builder.WindowWidth = width;
                        MessageBox.Builder.WindowHeight = height;
                        MessageBox.Builder.textSize = (calcBase
                                / res.getDimensionPixelSize(R.dimen.BtnTextSize)) * scale;
                        MessageBox.Builder.ButtonHeight = (int) (50 * scale);

                        // Ask before delete
                        msg = (MessageBox) MessageBox.Show(Translation.Get("shuredeleteWorkspace", Name),
                                Translation.Get("deleteWorkspace"), MessageBoxButtons.YesNo,
                                MessageBoxIcon.Question, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (which == MessageBox.BUTTON_POSITIVE) {
                                            // Delete this Workpath only from Settings don't delete any File
                                            deleteWorkPath(AddWorkPath);
                                        }
                                        // Start again to exclude the old Folder
                                        msg.dismiss();
                                        onStart();
                                    }

                                });

                        dialog.dismiss();
                        return true;
                    }
                });

                buttonW.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // close select dialog
                        dialog.dismiss();

                        // show please wait dialog
                        showPleaseWaitDialog();

                        // use external SD -> change workPath
                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                workPath = AddWorkPath;
                                boolean askAgain = cbAskAgain.isChecked();
                                // boolean useTabletLayout = rbTabletLayout.isChecked();
                                saveWorkPath(askAgain/* , useTabletLayout */);
                                startInitial();
                            }
                        };
                        thread.start();

                    }
                });

                ll.addView(buttonW);
            }

            Button buttonC = (Button) dialog.findViewById(R.id.buttonCreateWorkspace);
            buttonC.setText(Translation.Get("createWorkSpace"));
            buttonC.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // close select dialog
                    dialog.dismiss();
                    getFolderReturnListener = new IgetFolderReturnListener() {

                        @Override
                        public void getFolderReturn(String Path) {
                            if (FileIO.checkWritePermission(Path)) {

                                AdditionalWorkPathArray.add(Path);
                                writeAdditionalWorkPathArray(AdditionalWorkPathArray);
                                // Start again to include the new Folder
                                onStart();
                            } else {
                                String WriteProtectionMsg = Translation.Get("NoWriteAcces");
                                Toast.makeText(splash.this, WriteProtectionMsg, Toast.LENGTH_LONG).show();
                            }
                        }
                    };

                    PlatformConnector.getFolder("", Translation.Get("select_folder"), Translation.Get("select"),
                            getFolderReturnListener);

                }
            });

            dialog.show();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } else {
        if (GlobalCore.displayType == DisplayType.Large || GlobalCore.displayType == DisplayType.xLarge)
            GlobalCore.isTab = isLandscape;

        // restore the saved workPath
        // test whether workPath is available by checking the free size on the SD
        String workPathToTest = workPath.substring(0, workPath.lastIndexOf("/"));
        long bytesAvailable = 0;
        try {
            StatFs stat = new StatFs(workPathToTest);
            bytesAvailable = (long) stat.getBlockSize() * (long) stat.getBlockCount();
        } catch (Exception ex) {
            bytesAvailable = 0;
        }
        if (bytesAvailable == 0) {
            // there is a workPath stored but this workPath is not available at the moment (maybe SD is removed)
            Toast.makeText(splashActivity,
                    "WorkPath " + workPath + " is not available!\nMaybe SD-Card is removed?", Toast.LENGTH_LONG)
                    .show();
            finish();
            return;
        }

        startInitial();
    }

}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

public static void view_showAboutDialog(Context context, int titleResourceId, int aboutLayout, int okButtonId) {
    final Dialog dialog = new Dialog(context);
    dialog.setContentView(aboutLayout);
    dialog.setTitle(titleResourceId);// ww w  .j  a  v a  2  s  .  c o m

    Button dialogButton = (Button) dialog.findViewById(okButtonId);
    dialogButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            dialog.dismiss();
        }
    });

    dialog.show();
}

From source file:com.popdeem.sdk.uikit.activity.PDUIClaimActivity.java

private void addRewardDetailsToUI() {
    // Logo/*  ww  w  . j av a  2 s .c o  m*/
    final ImageView logoImageView = (ImageView) findViewById(R.id.pd_reward_star_image_view);
    final String imageUrl = mReward.getCoverImage();
    if (imageUrl == null || imageUrl.isEmpty() || imageUrl.contains("default")) {
        Glide.with(this).load(R.drawable.pd_ui_star_icon).error(R.drawable.pd_ui_star_icon).dontAnimate()
                .placeholder(R.drawable.pd_ui_star_icon).into(logoImageView);
    } else {
        Glide.with(this).load(imageUrl).error(R.drawable.pd_ui_star_icon).dontAnimate()
                .placeholder(R.drawable.pd_ui_star_icon).into(logoImageView);
    }

    // Reward Description
    TextView textView = (TextView) findViewById(R.id.pd_reward_offer_text_view);
    textView.setText(mReward.getDescription());

    // Rules
    textView = (TextView) findViewById(R.id.pd_reward_item_rules_text_view);
    textView.setText(mReward.getRules());
    if (mReward.getRules() == null || mReward.getRules().isEmpty()) {
        textView.setVisibility(View.GONE);
    }

    StringBuilder actionStringBuilder = new StringBuilder("");

    // Action
    final boolean TWITTER_ACTION_REQUIRED = twitterShareForced();
    if (mReward.getAction().equalsIgnoreCase(PDReward.PD_REWARD_ACTION_PHOTO)) {
        actionStringBuilder.append(getString(TWITTER_ACTION_REQUIRED ? R.string.pd_claim_action_tweet_photo
                : R.string.pd_claim_action_photo_camera));
    } else if (mReward.getAction().equalsIgnoreCase(PDReward.PD_REWARD_ACTION_CHECKIN)) {
        actionStringBuilder.append(getString(TWITTER_ACTION_REQUIRED ? R.string.pd_claim_action_tweet_checkin
                : R.string.pd_claim_action_checkin));
    } else {
        actionStringBuilder.append(getString(R.string.pd_claim_action_none));
    }

    // End date
    long timeInSecs = PDNumberUtils.toLong(mReward.getAvailableUntilInSeconds(), -1);
    String convertedTimeString = PDUIUtils.convertTimeToDayAndMonth(timeInSecs);
    if (!convertedTimeString.isEmpty()) {
        actionStringBuilder.append(String.format(Locale.getDefault(), " | Exp %1s", convertedTimeString));
    }

    textView = (TextView) findViewById(R.id.pd_reward_request_text_view);
    textView.setText(actionStringBuilder.toString());
    textView.setVisibility(View.GONE);

    //add photo
    addPhotoView = findViewById(R.id.pd_share_view_icon_holder);
    addedPhotoView = findViewById(R.id.pd_share_view_taken_holder);
    TextView infoView = findViewById(R.id.pd_claim_info_text);

    //already shared button
    LinearLayout alreadySharedButton = findViewById(R.id.pd_claim_already_shared_view);
    TextView alreadySharedText = findViewById(R.id.pd_claim_already_shared_button);

    if (mReward.getAction().equalsIgnoreCase(PDReward.PD_REWARD_ACTION_PHOTO)) {
        alreadySharedText.setText(getResources().getString(R.string.pd_claim_scan_for_already_shared_text));
        infoView.setText(String.format(getResources().getString(R.string.pd_claim_info_photo),
                mReward.getGlobalHashtag()));
    } else {
        alreadySharedText
                .setText(getResources().getString(R.string.pd_claim_scan_for_already_shared_activity_text));
        infoView.setText(String.format(getResources().getString(R.string.pd_claim_info_check_in),
                mReward.getGlobalHashtag()));
    }

    alreadySharedButton.setOnClickListener(this);
    if (mReward.getGlobalHashtag() != null && !mReward.getGlobalHashtag().equalsIgnoreCase("")) {
        //            alreadySharedButton.setText(String.format(getString(R.string.pd_claim_get_already_shared_text), mReward.getGlobalHashtag()));
    } else {
        //            alreadySharedButton.setText(R.string.pd_claim_already_shared_default);
    }

    infoIcon.setVisibility(View.VISIBLE);
    infoIcon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final Dialog dialog = new Dialog(PDUIClaimActivity.this);
            PDUIDialogUtils.setMargins(dialog, 25, 100, 25, 100);
            dialog.setContentView(R.layout.claim_alert_dialog);
            Button claim = (Button) dialog.findViewById(R.id.button_claim);
            Button cancel = (Button) dialog.findViewById(R.id.button_cancel);
            ImageView icon = (ImageView) dialog.findViewById(R.id.icon);

            String imageUrl = mReward.getCoverImage();
            if (imageUrl == null || imageUrl.isEmpty() || imageUrl.contains("default")) {
                Glide.with(PDUIClaimActivity.this).load(R.drawable.pd_ui_star_icon).dontAnimate()
                        .error(R.drawable.pd_ui_star_icon).dontAnimate().placeholder(R.drawable.pd_ui_star_icon)
                        .into(icon);
            } else {

                Glide.with(PDUIClaimActivity.this).load(imageUrl).dontAnimate()
                        .error(R.drawable.pd_ui_star_icon).dontAnimate().placeholder(R.drawable.pd_ui_star_icon)
                        .into(icon);
            }

            claim.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                }
            });
            claim.setText("Close");

            cancel.setVisibility(View.GONE);

            TextView tvTitle = dialog.findViewById(R.id.alertTitle);
            tvTitle.setText(mReward.getDescription());

            TextView message = dialog.findViewById(R.id.message);
            message.setText(mReward.getRules());

            TextView detailsActionText = (TextView) dialog.findViewById(R.id.pd_action_text);
            setActionString(detailsActionText);

            dialog.show();
        }
    });

}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * "Coach mark" (help overlay image)/*from   w  w  w  .j  a va  2  s.c  o  m*/
 * 
 * @param context
 * @param coachMarkLayoutId   Is "Help overlay" layout id in UX talk :-) 
 *             [coach_mark.xml is your coach mark layout]
 * @param coachMarkMasterViewId   is the id of the top most view in coach_mark.xml
 */
public static void dialog_onCoachMark(Context context, int coachMarkLayoutId, int coachMarkMasterViewId,
        int bgColor) {

    final Dialog dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(bgColor));
    dialog.setContentView(coachMarkLayoutId);
    dialog.setCanceledOnTouchOutside(true);

    //for dismissing anywhere you touch
    View masterView = dialog.findViewById(coachMarkMasterViewId);
    masterView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            dialog.dismiss();
        }
    });

    dialog.show();
}

From source file:foam.opensauces.StarwispBuilder.java

public void Update(final StarwispActivity ctx, final String ctxname, JSONArray arr) {
    try {/* w w  w. j a  v  a 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("walk-draggable")) {
            final String name = arr.getString(3);
            int iid = arr.getInt(5);
            DialogCallback(ctx, ctxname, name, WalkDraggable(ctx, name, ctxname, iid));
            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;
        }

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

        // 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);
                }
            }
        }

        // special cases
        if (type.equals("draggable")) {
            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:com.iiordanov.bVNC.RemoteCanvasActivity.java

private void selectColorModel() {

    String[] choices = new String[COLORMODEL.values().length];
    int currentSelection = -1;
    for (int i = 0; i < choices.length; i++) {
        COLORMODEL cm = COLORMODEL.values()[i];
        choices[i] = cm.toString();/*  w  w  w .  java2  s . c o m*/
        if (canvas.isColorModel(cm))
            currentSelection = i;
    }

    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    ListView list = new ListView(this);
    list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, choices));
    list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    list.setItemChecked(currentSelection, true);
    list.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            dialog.dismiss();
            COLORMODEL cm = COLORMODEL.values()[arg2];
            canvas.setColorModel(cm);
            connection.setColorModel(cm.nameString());
            connection.save(database.getWritableDatabase());
            database.close();
            Toast.makeText(RemoteCanvasActivity.this,
                    getString(R.string.info_update_color_model_to) + cm.toString(), Toast.LENGTH_SHORT).show();
        }
    });
    dialog.setContentView(list);
    dialog.show();
}

From source file:com.sentaroh.android.TaskAutomation.Config.ProfileMaintenanceActionProfile.java

final static private void editActivityExtraDataItem(final GlobalParameters mGlblParms, final int sel_pos) {
    // ??//from  www.j  av a 2s  .com
    final Dialog dialog = new Dialog(mGlblParms.context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    //      dialog.getWindow().setSoftInputMode(
    //                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    dialog.setContentView(R.layout.edit_activity_extra_data_item_dlg);
    final TextView dlg_msg = (TextView) dialog.findViewById(R.id.edit_activity_extra_data_item_msg);
    //      final TextView dlg_title = (TextView) dialog.findViewById(R.id.edit_activity_extra_data_item_title);

    //      CommonDialog.setDlgBoxSizeLimit(dialog,true);
    final Button btn_cancel = (Button) dialog.findViewById(R.id.edit_activity_extra_data_item_cancel_btn);
    final Button btn_ok = (Button) dialog.findViewById(R.id.edit_activity_extra_data_item_ok_btn);

    final EditText et_key = (EditText) dialog.findViewById(R.id.edit_activity_extra_data_item_key);
    final EditText et_string = (EditText) dialog.findViewById(R.id.edit_activity_extra_data_item_data_string);
    final EditText et_int = (EditText) dialog.findViewById(R.id.edit_activity_extra_data_item_data_int);
    final CheckBox cb_array = (CheckBox) dialog.findViewById(R.id.edit_activity_extra_data_item_array);
    final Button btn_add_array = (Button) dialog.findViewById(R.id.edit_activity_extra_data_item_add_array);
    final ListView lv_array = (ListView) dialog.findViewById(R.id.edit_activity_extra_data_item_array_listview);
    final TextView lv_spacer = (TextView) dialog.findViewById(R.id.edit_activity_extra_data_item_array_spacer);

    final Spinner spinnerExtraDataType = (Spinner) dialog
            .findViewById(R.id.edit_activity_extra_data_item_data_type);
    final CustomSpinnerAdapter adapterExtraDataType = new CustomSpinnerAdapter(mGlblParms.context,
            R.layout.custom_simple_spinner_item);
    adapterExtraDataType.setTextColor(Color.BLACK);
    setSpinnerExtraDataType(mGlblParms, dialog, spinnerExtraDataType, adapterExtraDataType,
            PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_STRING);

    final Spinner spinnerExtraDataBoolean = (Spinner) dialog
            .findViewById(R.id.edit_activity_extra_data_item_data_boolean);
    final CustomSpinnerAdapter adapterExtraDataBoolean = new CustomSpinnerAdapter(mGlblParms.context,
            R.layout.custom_simple_spinner_item);
    adapterExtraDataBoolean.setTextColor(Color.BLACK);
    setSpinnerExtraDataBoolean(mGlblParms, dialog, spinnerExtraDataBoolean, adapterExtraDataBoolean, "false");

    final Button update_apply = (Button) dialog
            .findViewById(R.id.edit_activity_extra_data_item_data_update_apply);
    final Button update_cancel = (Button) dialog
            .findViewById(R.id.edit_activity_extra_data_item_data_update_cancel);
    update_apply.setVisibility(Button.GONE);
    update_cancel.setVisibility(Button.GONE);
    spinnerExtraDataBoolean.setVisibility(Spinner.GONE);
    et_string.setVisibility(EditText.GONE);
    et_int.setVisibility(EditText.GONE);
    btn_add_array.setVisibility(Button.GONE);
    lv_array.setVisibility(ListView.GONE);
    lv_spacer.setVisibility(TextView.VISIBLE);

    final ArrayList<DataArrayEditListItem> aed_array_list = new ArrayList<DataArrayEditListItem>();
    final AdapterDataArrayEditList aed_array_adapter = new AdapterDataArrayEditList(mGlblParms.context,
            R.layout.data_array_edit_list_item, aed_array_list);
    lv_array.setAdapter(aed_array_adapter);
    setActivityExtraDataEditItemViewVisibility(mGlblParms, dialog, aed_array_adapter, spinnerExtraDataType);

    cb_array.setChecked(false);
    if (sel_pos != -1) {
        et_key.setEnabled(false);
        et_key.setTextColor(Color.WHITE);
        et_key.selectAll();
        et_key.setText(mGlblParms.activityExtraDataEditListAdapter.getItem(sel_pos).key_value);
        if (mGlblParms.activityExtraDataEditListAdapter.getItem(sel_pos).data_type
                .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_STRING)) {
            et_string.setText(mGlblParms.activityExtraDataEditListAdapter.getItem(sel_pos).data_value);
            spinnerExtraDataType.setSelection(0);
        } else if (mGlblParms.activityExtraDataEditListAdapter.getItem(sel_pos).data_type
                .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_INT)) {
            et_int.setText(mGlblParms.activityExtraDataEditListAdapter.getItem(sel_pos).data_value);
            spinnerExtraDataType.setSelection(1);
        } else if (mGlblParms.activityExtraDataEditListAdapter.getItem(sel_pos).data_type
                .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_BOOLEAN)) {
            spinnerExtraDataType.setSelection(2);
            if (mGlblParms.activityExtraDataEditListAdapter.getItem(sel_pos).data_value.equals("false"))
                spinnerExtraDataBoolean.setSelection(0);
            else
                spinnerExtraDataBoolean.setSelection(1);
        }
        mGlblParms.currentSelectedExtraDataType = spinnerExtraDataType.getSelectedItem().toString();
        if (mGlblParms.activityExtraDataEditListAdapter.getItem(sel_pos).data_value_array
                .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_ARRAY_YES)) {
            cb_array.setChecked(true);
            et_string.setText("");
            et_int.setText("");
            createActivityExtraDataArrayList(aed_array_adapter,
                    mGlblParms.activityExtraDataEditListAdapter.getItem(sel_pos));
            aed_array_adapter.notifyDataSetChanged();
            update_apply.setVisibility(Button.GONE);
            update_cancel.setVisibility(Button.GONE);
            spinnerExtraDataBoolean.setVisibility(Spinner.GONE);
            et_string.setVisibility(EditText.GONE);
            et_int.setVisibility(EditText.GONE);
            btn_add_array.setVisibility(Button.VISIBLE);
            lv_array.setVisibility(ListView.VISIBLE);
            lv_spacer.setVisibility(TextView.GONE);
        } else {
            cb_array.setChecked(false);
            update_apply.setVisibility(Button.GONE);
            update_cancel.setVisibility(Button.GONE);
            spinnerExtraDataBoolean.setVisibility(Spinner.GONE);
            et_string.setVisibility(EditText.GONE);
            et_int.setVisibility(EditText.GONE);
            btn_add_array.setVisibility(Button.GONE);
            lv_array.setVisibility(ListView.GONE);
            lv_spacer.setVisibility(TextView.VISIBLE);
            if (mGlblParms.activityExtraDataEditListAdapter.getItem(sel_pos).data_type
                    .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_STRING)) {
                et_string.setVisibility(EditText.VISIBLE);
            } else if (mGlblParms.activityExtraDataEditListAdapter.getItem(sel_pos).data_type
                    .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_INT)) {
                et_int.setVisibility(EditText.VISIBLE);
            } else if (mGlblParms.activityExtraDataEditListAdapter.getItem(sel_pos).data_type
                    .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_BOOLEAN)) {
                spinnerExtraDataBoolean.setVisibility(Spinner.VISIBLE);
            }
        }
    }

    btn_add_array.setOnClickListener(new OnClickListener() {
        @Override
        final public void onClick(View arg0) {
            String n_data = "";
            if (spinnerExtraDataType.getSelectedItem()
                    .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_STRING)) {
                n_data = "";
            } else if (spinnerExtraDataType.getSelectedItem()
                    .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_INT)) {
                n_data = "0";
            } else if (spinnerExtraDataType.getSelectedItem()
                    .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_BOOLEAN)) {
                n_data = "false";
            }
            DataArrayEditListItem aeda_item = new DataArrayEditListItem();
            aeda_item.data_value = n_data;
            aed_array_adapter.add(aeda_item);
            aed_array_adapter.notifyDataSetChanged();
        }
    });

    NotifyEvent ntfy = new NotifyEvent(mGlblParms.context);
    ntfy.setListener(new NotifyEventListener() {
        @Override
        final public void positiveResponse(Context c, Object[] o) {
            spinnerExtraDataType.setEnabled(false);
            String c_data = (String) o[0];
            if (spinnerExtraDataType.getSelectedItem()
                    .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_STRING)) {
                et_string.setText(c_data);
                spinnerExtraDataBoolean.setVisibility(Spinner.GONE);
                et_string.setVisibility(EditText.VISIBLE);
                et_int.setVisibility(EditText.GONE);
                et_string.requestFocus();
            } else if (spinnerExtraDataType.getSelectedItem()
                    .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_INT)) {
                et_int.setText(c_data);
                spinnerExtraDataBoolean.setVisibility(Spinner.GONE);
                et_string.setVisibility(EditText.GONE);
                et_int.setVisibility(EditText.VISIBLE);
                et_int.requestFocus();
            } else if (spinnerExtraDataType.getSelectedItem()
                    .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_BOOLEAN)) {
                if (c_data.equals("false"))
                    spinnerExtraDataBoolean.setSelection(0);
                else
                    spinnerExtraDataBoolean.setSelection(1);
                spinnerExtraDataBoolean.setVisibility(Spinner.VISIBLE);
                et_string.setVisibility(EditText.GONE);
                et_int.setVisibility(EditText.GONE);
            }
            update_apply.setVisibility(Button.VISIBLE);
            update_cancel.setVisibility(Button.VISIBLE);
            btn_ok.setEnabled(false);
            btn_cancel.setEnabled(false);
            cb_array.setEnabled(false);
            btn_add_array.setEnabled(false);

        }

        @Override
        final public void negativeResponse(Context c, Object[] o) {
        }
    });
    aed_array_adapter.setEditBtnNotifyListener(ntfy);
    update_apply.setVisibility(Button.GONE);
    update_cancel.setVisibility(Button.GONE);
    update_apply.setOnClickListener(new View.OnClickListener() {
        final public void onClick(View v) {
            boolean no_err = auditActivityExtraData(mGlblParms, dialog, spinnerExtraDataType,
                    spinnerExtraDataBoolean);
            if (!no_err)
                return;
            int pos = -1;
            for (int i = 0; i < aed_array_list.size(); i++) {
                if (aed_array_list.get(i).while_edit) {
                    pos = i;
                    break;
                }
            }
            if (spinnerExtraDataType.getSelectedItem()
                    .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_STRING)) {
                aed_array_list.get(pos).data_value = et_string.getText().toString();
                aed_array_list.get(pos).while_edit = false;
            } else if (spinnerExtraDataType.getSelectedItem()
                    .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_INT)) {
                aed_array_list.get(pos).data_value = et_int.getText().toString();
                aed_array_list.get(pos).while_edit = false;
            } else if (spinnerExtraDataType.getSelectedItem()
                    .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_BOOLEAN)) {
                String n_boolean = "true";
                if (spinnerExtraDataBoolean.getSelectedItem().toString().equals("false"))
                    n_boolean = "false";
                aed_array_list.get(pos).data_value = n_boolean;
                aed_array_list.get(pos).while_edit = false;
            }
            et_string.setText("");
            et_int.setText("");
            et_string.setVisibility(EditText.GONE);
            et_int.setVisibility(EditText.GONE);
            spinnerExtraDataBoolean.setVisibility(Spinner.GONE);
            aed_array_adapter.notifyDataSetChanged();
            update_apply.setVisibility(Button.GONE);
            update_cancel.setVisibility(Button.GONE);
            spinnerExtraDataType.setEnabled(true);
            btn_ok.setEnabled(true);
            btn_cancel.setEnabled(true);
            cb_array.setEnabled(true);
            btn_add_array.setEnabled(true);
        }
    });
    update_cancel.setOnClickListener(new View.OnClickListener() {
        final public void onClick(View v) {
            for (int i = 0; i < aed_array_list.size(); i++) {
                aed_array_list.get(i).while_edit = false;
            }
            et_string.setText("");
            et_int.setText("");
            et_string.setVisibility(EditText.GONE);
            et_int.setVisibility(EditText.GONE);
            spinnerExtraDataBoolean.setVisibility(Spinner.GONE);
            aed_array_adapter.notifyDataSetChanged();
            update_apply.setVisibility(Button.GONE);
            update_cancel.setVisibility(Button.GONE);
            spinnerExtraDataType.setEnabled(true);
            btn_ok.setEnabled(true);
            btn_cancel.setEnabled(true);
            cb_array.setEnabled(true);
            btn_add_array.setEnabled(true);
        }
    });

    // CANCEL?
    btn_cancel.setOnClickListener(new View.OnClickListener() {
        final public void onClick(View v) {
            dialog.dismiss();
        }
    });
    // OK?
    btn_ok.setOnClickListener(new View.OnClickListener() {
        final public void onClick(View v) {
            ActivityExtraDataItem aedi = null;
            if (sel_pos == -1) {//Add item
                if (et_key.getText().toString().equals("")) {
                    dlg_msg.setText(mGlblParms.context
                            .getString(R.string.msgs_edit_profile_action_activity_extra_data_key_name_missing));
                    return;
                }
                aedi = new ActivityExtraDataItem();
            } else {//Edit item
                aedi = mGlblParms.activityExtraDataEditListAdapter.getItem(sel_pos);
            }
            aedi.key_value = et_key.getText().toString();
            if (cb_array.isChecked()) {
                if (aed_array_list.size() == 0) {
                    dlg_msg.setText(mGlblParms.context.getString(
                            R.string.msgs_edit_profile_action_activity_extra_data_array_data_missing));
                    return;
                }
                aedi.data_value_array = PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_ARRAY_YES;
                aedi.data_type = spinnerExtraDataType.getSelectedItem().toString();
                aedi.data_value = "";
                //               Log.v("","array size="+aed_array_list.size());
                for (int i = 0; i < aed_array_list.size(); i++) {
                    if (aedi.data_type.equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_STRING)) {
                        //                     aedi.data_value+="\u00a0"+aed_array_list.get(i).array_data_value+"\u0003";
                        aedi.data_value += aed_array_list.get(i).data_value + "\u0003";
                        //                     GeneralUtilities.hexString("String",aed_array_list.get(i).array_data_value.getBytes(),0,aed_array_list.get(i).array_data_value.getBytes().length);
                    } else {
                        aedi.data_value += aed_array_list.get(i).data_value + "\u0003";
                        //                     GeneralUtilities.hexString("int",aed_array_list.get(i).data_value.getBytes(),0,aed_array_list.get(i).data_value.getBytes().length);
                    }
                }
                //               GeneralUtilities.hexString("test",aedi.data_value.getBytes(),0,aedi.data_value.getBytes().length);
                //               Log.v("","dv="+aedi.data_value.replaceAll("\u0003", ";"));
            } else {
                boolean no_err = auditActivityExtraData(mGlblParms, dialog, spinnerExtraDataType,
                        spinnerExtraDataBoolean);
                if (!no_err)
                    return;
                else {
                    aedi.data_value_array = PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_ARRAY_NO;
                    aedi.data_type = spinnerExtraDataType.getSelectedItem().toString();
                    if (spinnerExtraDataType.getSelectedItem().toString()
                            .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_STRING)) {
                        aedi.data_value = et_string.getText().toString();
                    } else if (spinnerExtraDataType.getSelectedItem().toString()
                            .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_INT)) {
                        aedi.data_value = et_int.getText().toString();
                    } else if (spinnerExtraDataType.getSelectedItem().toString()
                            .equals(PROFILE_ACTION_TYPE_ACTIVITY_EXTRA_DATA_VALUE_BOOLEAN)) {
                        if (spinnerExtraDataBoolean.getSelectedItem().toString().equals("false"))
                            aedi.data_value = "false";
                        else
                            aedi.data_value = "true";
                    }
                }
            }
            if (sel_pos == -1)
                mGlblParms.activityExtraDataEditListAdapter.add(aedi);
            if (mGlblParms.activityExtraDataEditListAdapter.getItem(0).key_value.equals(""))
                mGlblParms.activityExtraDataEditListAdapter.remove(0);
            mGlblParms.activityExtraDataEditListAdapter.notifyDataSetChanged();

            dialog.dismiss();
        }
    });
    // Cancel?
    dialog.setOnCancelListener(new Dialog.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface arg0) {
            btn_cancel.performClick();
        }
    });
    //      dialog.setCancelable(false);
    dialog.show();
}

From source file:com.example.yudiandrean.socioblood.FeedActivity.java

@SuppressLint("NewApi")
@Override/*from w  ww.  j ava2 s.co  m*/
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    final Dialog d = new Dialog(context);
    setContentView(R.layout.feed_activity);
    postrequest = (TextView) findViewById(R.id.editText);

    WindowManager manager = (WindowManager) getSystemService(Activity.WINDOW_SERVICE);
    final int width, height;
    ActionBar.LayoutParams params;

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
        width = manager.getDefaultDisplay().getWidth();
        height = manager.getDefaultDisplay().getHeight();
    } else {
        Point point = new Point();
        manager.getDefaultDisplay().getSize(point);
        width = point.x;
        height = point.y;
    }

    session = new SessionManager(getApplicationContext());

    // Check if user is already logged in or not
    if (!session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(FeedActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    listView = (ListView) findViewById(R.id.list);
    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
    feedItems = new ArrayList<FeedItem>();

    listAdapter = new FeedListAdapter(this, feedItems);
    listView.setAdapter(listAdapter);

    swipeRefreshLayout.setOnRefreshListener(this);

    // add button listener
    postrequest.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            try {
                d.requestWindowFeature(Window.FEATURE_NO_TITLE);
                d.setContentView(R.layout.post_request);
                WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
                lp.copyFrom(d.getWindow().getAttributes());
                lp.width = width;
                lp.height = height;
                d.getWindow().setAttributes(lp);
            } catch (AndroidRuntimeException e) {
            } catch (Exception e) {
            }

            final Spinner rhesusspinner = (Spinner) d.findViewById(R.id.rhesus_spinner);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(FeedActivity.this,
                    android.R.layout.simple_spinner_dropdown_item) {

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {

                    View v = super.getView(position, convertView, parent);
                    if (position == getCount()) {
                        ((TextView) v.findViewById(android.R.id.text1)).setText("");
                        ((TextView) v.findViewById(android.R.id.text1)).setHint(getItem(getCount())); //"Hint to be displayed"
                    }

                    return v;
                }

                @Override
                public int getCount() {
                    return super.getCount() - 1; // you dont display last item. It is used as hint.
                }

            };

            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            adapter.add("+");
            adapter.add("-");
            adapter.add("Rhesus");

            rhesusspinner.setAdapter(adapter);
            rhesusspinner.setSelection(adapter.getCount()); //display hint

            final Spinner bloodspinner = (Spinner) d.findViewById(R.id.bloodtype_spinner);
            ArrayAdapter<String> bloodadapter = new ArrayAdapter<String>(FeedActivity.this,
                    android.R.layout.simple_spinner_dropdown_item) {

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {

                    View v = super.getView(position, convertView, parent);
                    if (position == getCount()) {
                        ((TextView) v.findViewById(android.R.id.text1)).setText("");
                        ((TextView) v.findViewById(android.R.id.text1)).setHint(getItem(getCount())); //"Hint to be displayed"
                    }

                    return v;
                }

                @Override
                public int getCount() {
                    return super.getCount() - 1; // you dont display last item. It is used as hint.
                }

            };

            bloodadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            bloodadapter.add("O");
            bloodadapter.add("A");
            bloodadapter.add("B");
            bloodadapter.add("AB");
            bloodadapter.add("Desired Type");

            bloodspinner.setAdapter(bloodadapter);
            bloodspinner.setSelection(bloodadapter.getCount()); //display hint

            //Buttons-Editexts
            Button btnpost = (Button) d.findViewById(R.id.post);
            final EditText userInput = (EditText) d.findViewById(R.id.editTextDialogUserInput);

            d.show();

            btnpost.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (bloodspinner.getSelectedItem().toString().equals("Desired Type")) {
                        Toast.makeText(getApplicationContext(), "Input Blood Type!", Toast.LENGTH_SHORT).show();
                    } else if (rhesusspinner.getSelectedItem().toString().equals("Rhesus")) {
                        Toast.makeText(getApplicationContext(), "Input Rhesus!", Toast.LENGTH_SHORT).show();
                    } else if (userInput.getText().toString().equals("")) {
                        Toast.makeText(getApplicationContext(), "Input your request message!",
                                Toast.LENGTH_SHORT).show();
                    } else {

                        int uid = session.currentUID();

                        String message = userInput.getText().toString();
                        String post_bloodtype = bloodspinner.getSelectedItem().toString();
                        String post_rhesus = rhesusspinner.getSelectedItem().toString();

                        NetAsync(d, view, uid, message, post_bloodtype, post_rhesus);

                    }
                }
            });

        }
    });

    //        // We first check for cached request
    //        Cache cache = FeedController.getInstance().getRequestQueue().getCache();
    //        Entry entry = cache.get(URL_FEED);
    //        if (entry != null) {
    //            // fetch the data from cache
    //            try {
    //                String data = new String(entry.data, "UTF-8");
    //                try {
    //                    parseJsonFeed(new JSONObject(data));
    //                } catch (JSONException e) {
    //                    e.printStackTrace();
    //                }
    //            } catch (UnsupportedEncodingException e) {
    //                e.printStackTrace();
    //            }
    //
    //        } else {
    // making fresh volley request and getting json

    /**
     * Showing Swipe Refresh animation on activity create
     * As animation won't start on onCreate, post runnable is used
     */
    swipeRefreshLayout.post(new Runnable() {
        @Override
        public void run() {
            swipeRefreshLayout.setRefreshing(true);
            getTimelineAsync();
        }
    });

}

From source file:com.updetector.MainActivity.java

/**
* Handle Setting click/*w  w w  .  jav a  2s .c  om*/
*/
private void handleSettings() {
    final Dialog dialog = new Dialog(this);
    dialog.setTitle(R.string.menu_item_settings);
    dialog.setContentView(R.layout.settings);

    final SharedPreferences mPrefs = getSharedPreferences(Constants.SHARED_PREFERENCES, Context.MODE_PRIVATE);
    final Editor editor = mPrefs.edit();

    final ToggleButton logOnButton = (ToggleButton) dialog.findViewById(R.id.log_on);
    logOnButton.setChecked(mPrefs.getBoolean(Constants.LOGGING_ON, false));

    final Button btDeviceSelectButton = (Button) dialog.findViewById(R.id.bt_device_button);
    btDeviceSelectButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (mBluetoothAdapter.isEnabled()) {
                selectBluetoothDevice();
            } else {
                Toast.makeText(getApplicationContext(), "Please enable your Bluetooth first.",
                        Toast.LENGTH_SHORT).show();
            }

        }
    });

    final Button applyButton = (Button) dialog.findViewById(R.id.apply_button);
    final Button cancelButton = (Button) dialog.findViewById(R.id.cancel_button);
    applyButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (logOnButton.isChecked())
                editor.putBoolean(Constants.LOGGING_ON, true);
            else
                editor.putBoolean(Constants.LOGGING_ON, false);
            editor.commit();
            dialog.cancel();
        }
    });

    cancelButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            dialog.cancel();
        }
    });
    dialog.show();
}