Example usage for android.widget LinearLayout setOrientation

List of usage examples for android.widget LinearLayout setOrientation

Introduction

In this page you can find the example usage for android.widget LinearLayout setOrientation.

Prototype

public void setOrientation(@OrientationMode int orientation) 

Source Link

Document

Should the layout be a column or a row.

Usage

From source file:com.example.drugsformarinemammals.Dose_Information.java

public LinearLayout createBorderLayout() {
    LinearLayout border_layout = new LinearLayout(this);
    border_layout.setOrientation(LinearLayout.VERTICAL);
    border_layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    border_layout.setBackgroundResource(R.drawable.layout_border);
    return border_layout;
}

From source file:com.farmerbb.taskbar.service.DashboardService.java

@SuppressLint("RtlHardcoded")
private void drawDashboard() {
    windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

    final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
            PixelFormat.TRANSLUCENT);//from w  ww. ja v a  2s  . c om

    // Initialize views
    layout = new LinearLayout(this);
    layout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    layout.setVisibility(View.GONE);
    layout.setAlpha(0);

    SharedPreferences pref = U.getSharedPreferences(this);
    int width = pref.getInt("dashboard_width",
            getApplicationContext().getResources().getInteger(R.integer.dashboard_width));
    int height = pref.getInt("dashboard_height",
            getApplicationContext().getResources().getInteger(R.integer.dashboard_height));

    boolean isPortrait = getApplicationContext().getResources()
            .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    boolean isLandscape = getApplicationContext().getResources()
            .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;

    if (isPortrait) {
        columns = height;
        rows = width;
    }

    if (isLandscape) {
        columns = width;
        rows = height;
    }

    maxSize = columns * rows;

    int backgroundTint = U.getBackgroundTint(this);
    int accentColor = U.getAccentColor(this);
    int accentColorAlt = accentColor;
    accentColorAlt = ColorUtils.setAlphaComponent(accentColorAlt, Color.alpha(accentColorAlt) / 2);

    int cellCount = 0;

    for (int i = 0; i < columns; i++) {
        LinearLayout layout2 = new LinearLayout(this);
        layout2.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, 1));
        layout2.setOrientation(LinearLayout.VERTICAL);

        for (int j = 0; j < rows; j++) {
            DashboardCell cellLayout = (DashboardCell) View.inflate(this, R.layout.dashboard, null);
            cellLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT, 1));
            cellLayout.setBackgroundColor(backgroundTint);
            cellLayout.setOnClickListener(cellOcl);
            cellLayout.setOnHoverListener(cellOhl);

            TextView empty = (TextView) cellLayout.findViewById(R.id.empty);
            empty.setBackgroundColor(accentColorAlt);
            empty.setTextColor(accentColor);

            Bundle bundle = new Bundle();
            bundle.putInt("cellId", cellCount);

            cellLayout.setTag(bundle);
            cells.put(cellCount, cellLayout);
            cellCount++;

            layout2.addView(cellLayout);
        }

        layout.addView(layout2);
    }

    mAppWidgetManager = AppWidgetManager.getInstance(this);
    mAppWidgetHost = new AppWidgetHost(this, APPWIDGET_HOST_ID);
    mAppWidgetHost.startListening();

    for (int i = 0; i < maxSize; i++) {
        int appWidgetId = pref.getInt("dashboard_widget_" + Integer.toString(i), -1);
        if (appWidgetId != -1)
            addWidget(appWidgetId, i, false);
        else if (pref.getBoolean("dashboard_widget_" + Integer.toString(i) + "_placeholder", false))
            addPlaceholder(i);
    }

    mAppWidgetHost.stopListening();

    LocalBroadcastManager.getInstance(this).unregisterReceiver(toggleReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(addWidgetReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(removeWidgetReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(hideReceiver);

    LocalBroadcastManager.getInstance(this).registerReceiver(toggleReceiver,
            new IntentFilter("com.farmerbb.taskbar.TOGGLE_DASHBOARD"));
    LocalBroadcastManager.getInstance(this).registerReceiver(addWidgetReceiver,
            new IntentFilter("com.farmerbb.taskbar.ADD_WIDGET_COMPLETED"));
    LocalBroadcastManager.getInstance(this).registerReceiver(removeWidgetReceiver,
            new IntentFilter("com.farmerbb.taskbar.REMOVE_WIDGET_COMPLETED"));
    LocalBroadcastManager.getInstance(this).registerReceiver(hideReceiver,
            new IntentFilter("com.farmerbb.taskbar.HIDE_DASHBOARD"));

    windowManager.addView(layout, params);

    new Handler().postDelayed(() -> {
        int paddingSize = getResources().getDimensionPixelSize(R.dimen.icon_size);

        switch (U.getTaskbarPosition(DashboardService.this)) {
        case "top_vertical_left":
        case "bottom_vertical_left":
            layout.setPadding(paddingSize, 0, 0, 0);
            break;
        case "top_left":
        case "top_right":
            layout.setPadding(0, paddingSize, 0, 0);
            break;
        case "top_vertical_right":
        case "bottom_vertical_right":
            layout.setPadding(0, 0, paddingSize, 0);
            break;
        case "bottom_left":
        case "bottom_right":
            layout.setPadding(0, 0, 0, paddingSize);
            break;
        }
    }, 100);
}

From source file:org.telegram.ui.ChannelEditTypeActivity.java

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);

    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override/*from  w  w  w  . ja v  a  2 s .c o  m*/
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == done_button) {
                if (donePressed) {
                    return;
                }

                if (!isPrivate && ((currentChat.username == null && nameTextView.length() != 0)
                        || (currentChat.username != null && !currentChat.username
                                .equalsIgnoreCase(nameTextView.getText().toString())))) {
                    if (nameTextView.length() != 0 && !lastNameAvailable) {
                        Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                        if (v != null) {
                            v.vibrate(200);
                        }
                        AndroidUtilities.shakeView(checkTextView, 2, 0);
                        return;
                    }
                }
                donePressed = true;

                String oldUserName = currentChat.username != null ? currentChat.username : "";
                String newUserName = isPrivate ? "" : nameTextView.getText().toString();
                if (!oldUserName.equals(newUserName)) {
                    MessagesController.getInstance().updateChannelUserName(chatId, newUserName);
                }
                finishFragment();
            }
        }
    });

    ActionBarMenu menu = actionBar.createMenu();
    menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56));

    fragmentView = new ScrollView(context);
    fragmentView.setBackgroundColor(ContextCompat.getColor(context, R.color.settings_background));
    ScrollView scrollView = (ScrollView) fragmentView;
    scrollView.setFillViewport(true);
    linearLayout = new LinearLayout(context);
    scrollView.addView(linearLayout, new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));

    linearLayout.setOrientation(LinearLayout.VERTICAL);

    if (currentChat.megagroup) {
        actionBar.setTitle(LocaleController.getString("GroupType", R.string.GroupType));
    } else {
        actionBar.setTitle(LocaleController.getString("ChannelType", R.string.ChannelType));
    }

    LinearLayout linearLayout2 = new LinearLayout(context);
    linearLayout2.setOrientation(LinearLayout.VERTICAL);
    linearLayout2.setElevation(AndroidUtilities.dp(2));
    linearLayout2.setBackgroundColor(ContextCompat.getColor(context, R.color.card_background));
    linearLayout.addView(linearLayout2,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    radioButtonCell1 = new RadioButtonCell(context);
    radioButtonCell1.setElevation(0);
    radioButtonCell1.setBackgroundResource(R.drawable.list_selector);
    if (currentChat.megagroup) {
        radioButtonCell1.setTextAndValue(LocaleController.getString("MegaPublic", R.string.MegaPublic),
                LocaleController.getString("MegaPublicInfo", R.string.MegaPublicInfo), !isPrivate, false);
    } else {
        radioButtonCell1.setTextAndValue(LocaleController.getString("ChannelPublic", R.string.ChannelPublic),
                LocaleController.getString("ChannelPublicInfo", R.string.ChannelPublicInfo), !isPrivate, false);
    }
    linearLayout2.addView(radioButtonCell1,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    radioButtonCell1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!isPrivate) {
                return;
            }
            isPrivate = false;
            updatePrivatePublic();
        }
    });

    radioButtonCell2 = new RadioButtonCell(context);
    radioButtonCell2.setElevation(0);
    radioButtonCell2.setForeground(R.drawable.list_selector);
    if (currentChat.megagroup) {
        radioButtonCell2.setTextAndValue(LocaleController.getString("MegaPrivate", R.string.MegaPrivate),
                LocaleController.getString("MegaPrivateInfo", R.string.MegaPrivateInfo), isPrivate, false);
    } else {
        radioButtonCell2.setTextAndValue(LocaleController.getString("ChannelPrivate", R.string.ChannelPrivate),
                LocaleController.getString("ChannelPrivateInfo", R.string.ChannelPrivateInfo), isPrivate,
                false);
    }
    linearLayout2.addView(radioButtonCell2,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    radioButtonCell2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isPrivate) {
                return;
            }
            isPrivate = true;
            updatePrivatePublic();
        }
    });

    sectionCell = new ShadowSectionCell(context);
    linearLayout.addView(sectionCell,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    linkContainer = new LinearLayout(context);
    linkContainer.setOrientation(LinearLayout.VERTICAL);
    linkContainer.setElevation(AndroidUtilities.dp(2));
    linkContainer.setBackgroundColor(ContextCompat.getColor(context, R.color.card_background));
    linearLayout.addView(linkContainer,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    headerCell = new HeaderCell(context);
    headerCell.setElevation(0);
    headerCell.setBackground(null);
    linkContainer.addView(headerCell);

    publicContainer = new LinearLayout(context);
    publicContainer.setOrientation(LinearLayout.HORIZONTAL);
    linkContainer.addView(publicContainer,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, 17, 7, 17, 0));

    EditText editText = new EditText(context);
    editText.setText("telegram.me/");
    editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    //editText.setHintTextColor(0xff979797);
    editText.setTextColor(ContextCompat.getColor(context, R.color.primary_text));
    editText.setMaxLines(1);
    editText.setLines(1);
    editText.setEnabled(false);
    editText.setBackgroundDrawable(null);
    editText.setPadding(0, 0, 0, 0);
    editText.setSingleLine(true);
    editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
    editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
    publicContainer.addView(editText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 36));

    nameTextView = new EditText(context);
    nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    if (!isPrivate) {
        nameTextView.setText(currentChat.username);
    }
    //nameTextView.setHintTextColor(0xff979797);
    nameTextView.setTextColor(ContextCompat.getColor(context, R.color.primary_text));
    nameTextView.setMaxLines(1);
    nameTextView.setLines(1);
    nameTextView.setBackgroundDrawable(null);
    nameTextView.setPadding(0, 0, 0, 0);
    nameTextView.setSingleLine(true);
    nameTextView.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS | InputType.TYPE_TEXT_FLAG_MULTI_LINE
            | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
    nameTextView.setImeOptions(EditorInfo.IME_ACTION_DONE);
    nameTextView.setHint(
            LocaleController.getString("ChannelUsernamePlaceholder", R.string.ChannelUsernamePlaceholder));
    AndroidUtilities.clearCursorDrawable(nameTextView);
    publicContainer.addView(nameTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36));
    nameTextView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            checkUserName(nameTextView.getText().toString());
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

    privateContainer = new TextBlockCell(context);
    privateContainer.setForeground(R.drawable.list_selector);
    linkContainer.addView(privateContainer);
    privateContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (invite == null) {
                return;
            }
            try {
                android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                android.content.ClipData clip = android.content.ClipData.newPlainText("label", invite.link);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(getParentActivity(),
                        LocaleController.getString("LinkCopied", R.string.LinkCopied), Toast.LENGTH_SHORT)
                        .show();
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }
    });

    checkTextView = new TextView(context);
    checkTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
    checkTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
    checkTextView.setVisibility(View.GONE);
    linkContainer.addView(checkTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 17, 3, 17, 7));

    typeInfoCell = new TextInfoPrivacyCell(context);
    //typeInfoCell.setBackgroundResource(R.drawable.greydivider_bottom);
    linearLayout.addView(typeInfoCell,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    loadingAdminedCell = new LoadingCell(context);
    linearLayout.addView(loadingAdminedCell,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    adminedInfoCell = new TextInfoPrivacyCell(context);
    //adminedInfoCell.setBackgroundResource(R.drawable.greydivider_bottom);
    linearLayout.addView(adminedInfoCell,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    updatePrivatePublic();

    return fragmentView;
}

From source file:com.HumanDecisionSupportSystemsLaboratory.DD_P2P.OrgProfile.java

@Override
protected void onCreate(Bundle arg0) {
    super.onCreate(arg0);
    Intent i = this.getIntent();
    Bundle b = i.getExtras();//from   w  w  w.j av  a 2  s  . c  o  m

    __keys = new CipherSuit[3];
    __keys[KEY_IDX_ECDSA_BIG] = newCipherSuit(Cipher.ECDSA, Cipher.SHA384, ECDSA.P_521);
    __keys[KEY_IDX_ECDSA] = newCipherSuit(Cipher.ECDSA, Cipher.SHA1, ECDSA.P_256);
    __keys[KEY_IDX_RSA] = newCipherSuit(Cipher.RSA, Cipher.SHA512, 1024);

    // top panel setting
    organization_position = b.getInt(Orgs.O_ID);
    organization_LID = b.getString(Orgs.O_LID);
    organization_GIDH = b.getString(Orgs.O_GIDH);

    oLID = Util.lval(organization_LID, -1);
    if (oLID <= 0)
        return;
    this.org = D_Organization.getOrgByLID(oLID, true, false);
    if (org == null)
        return;

    try {
        Identity crt_identity = Identity.getCurrentConstituentIdentity();
        if (crt_identity == null) {
            Log.d(TAG, "No identity");
        } else
            constituent_LID = net.ddp2p.common.config.Identity.getDefaultConstituentIDForOrg(oLID);
    } catch (P2PDDSQLException e1) {
        e1.printStackTrace();
    }

    if (constituent_LID > 0) {
        constituent = D_Constituent.getConstByLID(constituent_LID, true, false);
        Log.d(TAG, "Got const: " + constituent);
    }

    setContentView(R.layout.org_profile);

    forename = (EditText) findViewById(R.id.profile_furname);
    surname = (EditText) findViewById(R.id.profile_surname);
    neiborhood = (Button) findViewById(R.id.profile_neiborhood);
    submit = (Button) findViewById(R.id.submit_profile);
    submit_new = (Button) findViewById(R.id.submit_profile_new);
    if (constituent == null)
        submit.setVisibility(Button.GONE);
    else
        submit.setVisibility(Button.VISIBLE);
    keys = (Spinner) findViewById(R.id.profile_keys);
    hasRightToVote = (CheckedTextView) findViewById(R.id.profile_hasRightToVote);
    email = (EditText) findViewById(R.id.profile_email);
    slogan = (EditText) findViewById(R.id.profile_slogan);
    slogan.setActivated(false);
    profilePic = (TextView) findViewById(R.id.profile_picture);
    profilePicImg = (ImageView) findViewById(R.id.profile_picture_img);
    // eligibility = (Spinner) findViewById(R.id.profile_eligibility);

    if (constituent != null) {
        forename.setText(constituent.getForename());
        surname.setText(constituent.getSurname());
        hasRightToVote.setChecked(Util.ival(constituent.getWeight(), 0) > 0);
        email.setText(constituent.getEmail());
        slogan.setText(constituent.getSlogan());
    }

    custom_fields = (LinearLayout) findViewById(R.id.profile_view);
    custom_index = 8;
    // custom_fields = (LinearLayout) findViewById(R.id.profile_custom);
    // custom_index = 0;

    custom_params = org.params.orgParam;

    if (custom_params == null || custom_params.length == 0) {
        custom_params = new D_OrgParam[0];// 3
        /*
         * custom_params[0] = new D_OrgParam(); custom_params[0].label =
         * "School"; custom_params[0].entry_size = 5; custom_params[1] = new
         * D_OrgParam(); custom_params[1].label = "Street"; custom_params[2]
         * = new D_OrgParam(); custom_params[2].label = "Year";
         * custom_params[2].list_of_values = new
         * String[]{"2010","2011","2012"};
         */
    }
    D_FieldValue[] field_values = null;
    if (constituent != null && constituent.address != null)
        field_values = constituent.address;
    for (int crt_field = 0; crt_field < custom_params.length; crt_field++) {
        D_OrgParam field = custom_params[crt_field];
        LinearLayout custom_entry = new LinearLayout(this);
        custom_entry.setOrientation(LinearLayout.HORIZONTAL);
        custom_entry.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        TextView custom_label = new TextView(this);
        custom_label.setText(field.label);
        custom_entry.addView(custom_label);

        if (field.list_of_values != null && field.list_of_values.length > 0) {
            Log.d(TAG, "spinner:" + field);
            Spinner custom_spin = new Spinner(this);
            ArrayAdapter<String> custom_spin_Adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, field.list_of_values);
            custom_spin_Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            custom_spin.setAdapter(custom_spin_Adapter);
            custom_entry.addView(custom_spin);
            D_FieldValue fv = locateFV(field_values, field);
            if (fv != null) {
                int position = 0;
                for (int k = 0; k <= field.list_of_values.length; k++) {
                    if (Util.equalStrings_null_or_not(field.list_of_values[k], fv.value)) {
                        position = k;
                        break;
                    }
                }
                custom_spin.setSelection(position);
            }
        } else {
            Log.d(TAG, "edit: " + field);
            EditText edit_text = new EditText(this);
            edit_text.setText(field.default_value);
            edit_text.setInputType(InputType.TYPE_CLASS_TEXT);
            if (field.entry_size > 0)
                edit_text.setMinimumWidth(field.entry_size * 60);
            Log.d(TAG, "edit: size=" + field.entry_size);
            custom_entry.addView(edit_text);
            // Button child = new Button(this);
            // child.setText("Test");
            D_FieldValue fv = locateFV(field_values, field);
            if (fv != null)
                edit_text.setText(fv.value);
        }
        custom_fields.addView(custom_entry, custom_index++);
    }

    ArrayAdapter<String> keysAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, m);
    keysAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    keys.setAdapter(keysAdapter);
    keys.setOnItemSelectedListener(new KeysListener());

    if (constituent != null) {
        SK sk = constituent.getSK();
        if (sk != null) {
            Cipher cipher = Cipher.getCipher(sk, null);
            if (cipher instanceof net.ddp2p.ciphersuits.RSA) {
                keys.setSelection(KEY_IDX_RSA, true);
            }
            if (cipher instanceof net.ddp2p.ciphersuits.ECDSA) {
                ECDSA ecdsa = (ECDSA) cipher;
                CipherSuit e = ECDSA.getCipherSuite(ecdsa.getPK());
                if (e.hash_alg == Cipher.SHA1) {
                    keys.setSelection(KEY_IDX_ECDSA, true);
                } else {
                    keys.setSelection(KEY_IDX_ECDSA_BIG, true);
                }
            }
        }
    }

    ArrayAdapter<String> eligibilityAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, m);
    eligibilityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // eligibility.setAdapter(eligibilityAdapter);
    // eligibility.setOnItemSelectedListener(new EligibilityListener());

    hasRightToVote.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            hasRightToVote.setChecked(!hasRightToVote.isChecked());
        }
    });

    setProfilePhoto = (ImageView) findViewById(R.id.org_profile_set_profile_photo);
    /*TODO this part only make the whole stuff slow       
    if (constituent_LID > 0) {
     constituent = D_Constituent.getConstByLID(constituent_LID, true,
       true);
     Log.d(TAG, "Got const: " + constituent);
    }
    */
    /*      boolean gotIcon = false;
          if (constituent != null) {
             if (constituent.getPicture() != null) {
    byte[] icon = constituent.getPicture();
    Bitmap bmp = BitmapFactory.decodeByteArray(icon, 0,
          icon.length - 1);
    setProfilePhoto.setImageBitmap(bmp);
    gotIcon = true;
             }
            
             if (!gotIcon) {
    int imgPath = R.drawable.constitutent_person_icon;
    Bitmap bmp = BitmapFactory.decodeResource(getResources(),
          imgPath);
    setProfilePhoto.setImageBitmap(bmp);
             }
          } else {
             int imgPath = R.drawable.constitutent_person_icon;
             Bitmap bmp = BitmapFactory.decodeResource(getResources(), imgPath);
             setProfilePhoto.setImageBitmap(bmp);
          }
            
          setProfilePhoto.setOnClickListener(new OnClickListener() {
            
             @Override
             public void onClick(View v) {
    if (Build.VERSION.SDK_INT < 19) {
       Intent intent = new Intent();
       intent.setType("image/*");
       intent.setAction(Intent.ACTION_GET_CONTENT);
       startActivityForResult(intent, SELECT_PROFILE_PHOTO);
    } else {
       Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
       intent.setType("image/*");
       startActivityForResult(intent, SELECT_PPROFILE_PHOTO_KITKAT);
    }
             }
          });*/

    submit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String _forename = forename.getText().toString();
            String _surname = surname.getText().toString();
            int _keys = OrgProfile._selectedKey;
            boolean rightToVote = hasRightToVote.isChecked();
            String _weight = rightToVote ? "1" : "0";
            String _email = email.getText().toString();
            String _slogan = slogan.getText().toString();
            boolean external = false;

            if (constituent == null) {
                D_Constituent new_const = D_Constituent.createConstituent(_forename, _surname, _email, oLID,
                        external, _weight, _slogan, OrgProfile.__keys[_keys].cipher,
                        OrgProfile.__keys[_keys].hash_alg, OrgProfile.__keys[_keys].ciphersize, null, null);

                Log.d(TAG, "saved constituent=" + new_const.getNameFull());
                try {
                    // Identity.DEBUG = true;
                    Identity.setCurrentConstituentForOrg(new_const.getLID(), oLID);
                } catch (P2PDDSQLException e) {
                    e.printStackTrace();
                }
                Log.d(TAG, "saved new constituent=" + new_const);
                constituent = new_const;
            } else {
                constituent = D_Constituent.getConstByConst_Keep(constituent);
                constituent.setEmail(_email);
                constituent.setForename(_forename);
                constituent.setSurname(_surname);
                constituent.setWeight(rightToVote);
                constituent.setSlogan(_slogan);
                constituent.setExternal(false);
                constituent.setCreationDate();
                constituent.sign();
                if (constituent.dirty_any())
                    constituent.storeRequest();
                constituent.releaseReference();
                Log.d(TAG, "saved constituent=" + constituent);
                try {
                    // Identity.DEBUG = true;
                    Identity.setCurrentConstituentForOrg(constituent.getLID(), oLID);
                } catch (P2PDDSQLException e) {
                    e.printStackTrace();
                }
                Log.d(TAG, "saved constituent=" + constituent.getLID() + " oLID=" + oLID);
            }
            if (constituent != null) {
                constituent = D_Constituent.getConstByConst_Keep(constituent);
                if (constituent != null) {
                    if (constituent.getSK() != null) {
                        constituent.setPicture(byteIcon);
                        constituent.setCreationDate();
                        constituent.sign();
                        constituent.storeRequest();
                        constituent.releaseReference();
                        Log.d(TAG, "saved constituent pic: " + constituent.getPicture());
                    }
                }
            }

            if (!org.getBroadcasted()) {
                D_Organization _org = D_Organization.getOrgByOrg_Keep(org);
                if (_org != null) {
                    _org.setBroadcasting(true);
                    if (_org.dirty_any())
                        _org.storeRequest();
                    _org.releaseReference();
                    org = _org;
                }
            }
            Log.d(TAG, "saved constituent pic: " + constituent.getPicture());
            Log.d(TAG, "saved constituent Done");
            finish();
        }
    });
    submit_new.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String _forename = forename.getText().toString();
            String _surname = surname.getText().toString();
            int _keys = OrgProfile._selectedKey;
            boolean rightToVote = hasRightToVote.isChecked();
            String _weight = rightToVote ? "1" : "0";
            String _email = email.getText().toString();
            String _slogan = slogan.getText().toString();
            boolean external = false;

            D_Constituent new_const = D_Constituent.createConstituent(_forename, _surname, _email, oLID,
                    external, _weight, _slogan, OrgProfile.__keys[_keys].cipher,
                    OrgProfile.__keys[_keys].hash_alg, OrgProfile.__keys[_keys].ciphersize, null, null);

            Log.d(TAG, "saved constituent=" + new_const.getNameFull());
            try {
                // Identity.DEBUG = true;
                Identity.setCurrentConstituentForOrg(new_const.getLID(), oLID);
                Log.d("CONST", "No Set: oLID=" + oLID + " c=" + new_const.getLID());
            } catch (P2PDDSQLException e) {
                e.printStackTrace();
            }
            constituent = new_const;
            constituent_LID = new_const.getLID();
            if (constituent_LID > 0) {
                constituent = D_Constituent.getConstByLID(constituent_LID, true, true);
                Log.d(TAG, "Got const: " + constituent);
            }

            if (constituent != null) {
                if (constituent.getSK() != null) {
                    constituent.setPicture(byteIcon);
                    constituent.setCreationDate();
                    constituent.sign();
                    constituent.storeRequest();
                    constituent.releaseReference();
                    Log.d(TAG, "saved constituent pic: " + constituent.getPicture());
                }
            }

            if (!org.getBroadcasted()) {
                D_Organization _org = D_Organization.getOrgByOrg_Keep(org);
                if (_org != null) {
                    _org.setBroadcasting(true);
                    if (_org.dirty_any())
                        _org.storeRequest();
                    _org.releaseReference();
                    org = _org;
                }
            }
            Log.d(TAG, "saved constituent=" + new_const);
            finish();
        }
    });
}

From source file:com.mifos.mifosxdroid.online.generatecollectionsheet.GenerateCollectionSheetFragment.java

private void inflateProductiveCollectionTable(CollectionSheetResponse collectionSheetResponse) {

    //Clear old views in case they are present.
    if (tableProductive.getChildCount() > 0) {
        tableProductive.removeAllViews();
    }//from   www. j a v  a  2  s.  c o m

    if (tableAdditional.getVisibility() == View.VISIBLE) {
        tableAdditional.removeAllViews();
        tableAdditional.setVisibility(View.GONE);
    }

    //A List to be used to inflate Attendance Spinners
    ArrayList<String> attendanceTypes = new ArrayList<>();
    attendanceTypeOptions.clear();
    attendanceTypeOptions = presenter.filterAttendanceTypes(collectionSheetResponse.getAttendanceTypeOptions(),
            attendanceTypes);

    //Add the heading Row
    TableRow headingRow = new TableRow(getContext());
    TableRow.LayoutParams headingRowParams = new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    headingRowParams.gravity = Gravity.CENTER;
    headingRowParams.setMargins(0, 0, 0, 10);
    headingRow.setLayoutParams(headingRowParams);

    TextView tvGroupName = new TextView(getContext());
    tvGroupName.setText(collectionSheetResponse.getGroups().get(0).getGroupName());
    tvGroupName.setTypeface(tvGroupName.getTypeface(), Typeface.BOLD);
    tvGroupName.setGravity(Gravity.CENTER);
    headingRow.addView(tvGroupName);

    for (LoanProducts loanProduct : collectionSheetResponse.getLoanProducts()) {
        TextView tvProduct = new TextView(getContext());
        tvProduct.setText(getString(R.string.collection_heading_charges, loanProduct.getName()));
        tvProduct.setTypeface(tvProduct.getTypeface(), Typeface.BOLD);
        tvProduct.setGravity(Gravity.CENTER);
        headingRow.addView(tvProduct);
    }

    TextView tvAttendance = new TextView(getContext());
    tvAttendance.setText(getString(R.string.attendance));
    tvAttendance.setGravity(Gravity.CENTER);
    tvAttendance.setTypeface(tvAttendance.getTypeface(), Typeface.BOLD);
    headingRow.addView(tvAttendance);

    tableProductive.addView(headingRow);

    for (ClientCollectionSheet clientCollectionSheet : collectionSheetResponse.getGroups().get(0)
            .getClients()) {
        //Insert rows
        TableRow row = new TableRow(getContext());
        TableRow.LayoutParams rowParams = new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        rowParams.gravity = Gravity.CENTER;
        rowParams.setMargins(0, 0, 0, 10);
        row.setLayoutParams(rowParams);

        //Column 1: Client Name and Id
        TextView tvClientName = new TextView(getContext());
        tvClientName.setText(
                concatIdWithName(clientCollectionSheet.getClientName(), clientCollectionSheet.getClientId()));
        row.addView(tvClientName);

        //Subsequent columns: The Loan products
        for (LoanProducts loanProduct : collectionSheetResponse.getLoanProducts()) {
            //Since there may be several items in this column, create a container.
            LinearLayout productContainer = new LinearLayout(getContext());
            productContainer.setOrientation(LinearLayout.HORIZONTAL);

            //Iterate through all the loans in of this type and add in the container
            for (LoanCollectionSheet loanCollectionSheet : clientCollectionSheet.getLoans()) {
                if (loanProduct.getName().equals(loanCollectionSheet.getProductShortName())) {
                    //This loan should be shown in this column. So, add it in the container.
                    EditText editText = new EditText(getContext());
                    editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                    editText.setText(String.format(Locale.getDefault(), "%f", 0.0));
                    //Set the loan id as the Tag of the EditText which
                    //will later be used as the identifier for this.
                    editText.setTag(TYPE_LOAN + ":" + loanCollectionSheet.getLoanId());
                    productContainer.addView(editText);
                }
            }
            row.addView(productContainer);
        }

        Spinner spAttendance = new Spinner(getContext());
        setSpinner(spAttendance, attendanceTypes);
        row.addView(spAttendance);

        tableProductive.addView(row);
    }

    if (btnSubmitProductive.getVisibility() != View.VISIBLE) {
        //Show the button the first time sheet is loaded.
        btnSubmitProductive.setVisibility(View.VISIBLE);
        btnSubmitProductive.setOnClickListener(this);
    }

    //If this block has been executed, that the CollectionSheet
    //which is already shown on screen is for center - Productive.
    btnSubmitProductive.setTag(TAG_TYPE_PRODUCTIVE);
}

From source file:org.zeroxlab.zeroxbenchmark.Benchmark.java

private void initViews() {
        /*/*from  w w w. ja  v a  2s  .com*/
        mRun = (Button)findViewById(R.id.btn_run);
        mRun.setOnClickListener(this);
            
        mShow = (Button)findViewById(R.id.btn_show);
        mShow.setOnClickListener(this);
        mShow.setClickable(false);
            
        mLinearLayout = (LinearLayout)findViewById(R.id.list_container);
        mMainView = (LinearLayout)findViewById(R.id.main_view);
            
        mBannerInfo = (TextView)findViewById(R.id.banner_info);
        mBannerInfo.setText("Hello!\nSelect cases to Run.\nUploaded results:\nhttp://0xbenchmark.appspot.com");
        */

        mTabHost = getTabHost();

        int length = mCases.size();
        mCheckList = new CheckBox[length];
        mDesc = new TextView[length];
        for (int i = 0; i < length; i++) {
            mCheckList[i] = new CheckBox(this);
            mCheckList[i].setText(mCases.get(i).getTitle());
            mDesc[i] = new TextView(this);
            mDesc[i].setText(mCases.get(i).getDescription());
            mDesc[i].setTextSize(mDesc[i].getTextSize() - 2);
            mDesc[i].setPadding(42, 0, 10, 10);
        }

        TabContentFactory mTCF = new TabContentFactory() {
            public View createTabContent(String tag) {
                ViewGroup.LayoutParams fillParent = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                        ViewGroup.LayoutParams.FILL_PARENT);
                ViewGroup.LayoutParams fillWrap = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                LinearLayout.LayoutParams wrapContent = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                wrapContent.gravity = Gravity.CENTER;
                LinearLayout.LayoutParams weightedFillWrap = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                weightedFillWrap.weight = 1;

                if (tag.equals(MAIN)) {
                    LinearLayout mMainView = new LinearLayout(Benchmark.this);
                    mMainView.setOrientation(1);
                    ScrollView mListScroll = new ScrollView(Benchmark.this);

                    LinearLayout mMainViewContainer = new LinearLayout(Benchmark.this);
                    mMainViewContainer.setOrientation(1);
                    ImageView mIconView = new ImageView(Benchmark.this);
                    mIconView.setImageResource(R.drawable.icon);

                    TextView mBannerInfo = new TextView(Benchmark.this);
                    mBannerInfo.setText("0xbench\nSelect benchmarks in the tabs,\nor batch select:");

                    d2CheckBox = new CheckBox(Benchmark.this);
                    d2CheckBox.setText(D2);
                    d2CheckBox.setOnClickListener(Benchmark.this);

                    d3CheckBox = new CheckBox(Benchmark.this);
                    d3CheckBox.setText(D3);
                    d3CheckBox.setOnClickListener(Benchmark.this);

                    mathCheckBox = new CheckBox(Benchmark.this);
                    mathCheckBox.setText(MATH);
                    mathCheckBox.setOnClickListener(Benchmark.this);

                    vmCheckBox = new CheckBox(Benchmark.this);
                    vmCheckBox.setText(VM);
                    vmCheckBox.setOnClickListener(Benchmark.this);

                    nativeCheckBox = new CheckBox(Benchmark.this);
                    nativeCheckBox.setText(NATIVE);
                    nativeCheckBox.setOnClickListener(Benchmark.this);

                    miscCheckBox = new CheckBox(Benchmark.this);
                    miscCheckBox.setText(MISC);
                    miscCheckBox.setOnClickListener(Benchmark.this);

                    TextView mWebInfo = new TextView(Benchmark.this);
                    mWebInfo.setText("Uploaded results:\nhttp://0xbenchmark.appspot.com");

                    LinearLayout mButtonContainer = new LinearLayout(Benchmark.this);
                    mRun = new Button(Benchmark.this);
                    mShow = new Button(Benchmark.this);
                    mRun.setText("Run");
                    mShow.setText("Show");
                    mRun.setOnClickListener(Benchmark.this);
                    mShow.setOnClickListener(Benchmark.this);
                    mButtonContainer.addView(mRun, weightedFillWrap);
                    mButtonContainer.addView(mShow, weightedFillWrap);
                    WebView mTracker = new WebView(Benchmark.this);
                    mTracker.clearCache(true);
                    mTracker.setWebViewClient(new WebViewClient() {
                        public void onPageFinished(WebView view, String url) {
                            Log.i(TAG, "Tracker: " + view.getTitle() + " -> " + url);
                        }

                        public void onReceivedError(WebView view, int errorCode, String description,
                                String failingUrl) {
                            Log.e(TAG, "Track err: " + description);
                        }
                    });
                    mTracker.loadUrl(trackerUrl);
                    mMainViewContainer.addView(mIconView, wrapContent);
                    mMainViewContainer.addView(mBannerInfo);
                    mMainViewContainer.addView(mathCheckBox);
                    mMainViewContainer.addView(d2CheckBox);
                    mMainViewContainer.addView(d3CheckBox);
                    mMainViewContainer.addView(vmCheckBox);
                    mMainViewContainer.addView(nativeCheckBox);
                    mMainViewContainer.addView(miscCheckBox);
                    mMainViewContainer.addView(mWebInfo);
                    mMainViewContainer.addView(mButtonContainer, fillWrap);
                    mMainViewContainer.addView(mTracker, 0, 0);
                    mListScroll.addView(mMainViewContainer, fillParent);
                    mMainView.addView(mListScroll, fillWrap);

                    return mMainView;

                }

                LinearLayout mMainView = new LinearLayout(Benchmark.this);
                mMainView.setOrientation(1);
                ScrollView mListScroll = new ScrollView(Benchmark.this);
                LinearLayout mListContainer = new LinearLayout(Benchmark.this);
                mListContainer.setOrientation(1);
                mListScroll.addView(mListContainer, fillParent);
                mMainView.addView(mListScroll, fillWrap);

                boolean gray = true;
                int length = mCases.size();
                Log.i(TAG, "L: " + length);
                Log.i(TAG, "TCF: " + tag);
                for (int i = 0; i < length; i++) {
                    if (!mCategory.get(tag).contains(mCases.get(i)))
                        continue;
                    Log.i(TAG, "Add: " + i);
                    mListContainer.addView(mCheckList[i], fillWrap);
                    mListContainer.addView(mDesc[i], fillWrap);
                    if (gray) {
                        int color = 0xFF333333; //ARGB
                        mCheckList[i].setBackgroundColor(color);
                        mDesc[i].setBackgroundColor(color);
                    }
                    gray = !gray;
                }
                return mMainView;
            }
        };

        mTabHost.addTab(mTabHost.newTabSpec(MAIN).setIndicator(MAIN, getResources().getDrawable(R.drawable.ic_eye))
                .setContent(mTCF));
        mTabHost.addTab(mTabHost.newTabSpec(D2).setIndicator(D2, getResources().getDrawable(R.drawable.ic_2d))
                .setContent(mTCF));
        mTabHost.addTab(mTabHost.newTabSpec(D3).setIndicator(D3, getResources().getDrawable(R.drawable.ic_3d))
                .setContent(mTCF));
        mTabHost.addTab(mTabHost.newTabSpec(MATH).setIndicator(MATH, getResources().getDrawable(R.drawable.ic_pi))
                .setContent(mTCF));
        mTabHost.addTab(mTabHost.newTabSpec(VM).setIndicator(VM, getResources().getDrawable(R.drawable.ic_vm))
                .setContent(mTCF));
        mTabHost.addTab(mTabHost.newTabSpec(NATIVE)
                .setIndicator(NATIVE, getResources().getDrawable(R.drawable.ic_c)).setContent(mTCF));
        mTabHost.addTab(mTabHost.newTabSpec(MISC).setIndicator(MISC, getResources().getDrawable(R.drawable.ic_misc))
                .setContent(mTCF));
    }

From source file:com.aware.ui.ESM_UI.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    //      getActivity().getWindow().setType(WindowManager.LayoutParams.TYPE_PRIORITY_PHONE);
    //      getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    //        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    //        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

    builder = new AlertDialog.Builder(getActivity());
    inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

    TAG = Aware.getSetting(getActivity().getApplicationContext(), Aware_Preferences.DEBUG_TAG).length() > 0
            ? Aware.getSetting(getActivity().getApplicationContext(), Aware_Preferences.DEBUG_TAG)
            : TAG;/*from   w w  w  .  j a v  a 2s.  com*/

    Cursor visible_esm = getActivity().getContentResolver().query(ESM_Data.CONTENT_URI, null,
            ESM_Data.STATUS + "=" + ESM.STATUS_NEW, null, ESM_Data.TIMESTAMP + " ASC LIMIT 1");
    if (visible_esm != null && visible_esm.moveToFirst()) {
        esm_id = visible_esm.getInt(visible_esm.getColumnIndex(ESM_Data._ID));

        //Fixed: set the esm as not new anymore, to avoid displaying the same ESM twice due to changes in orientation
        ContentValues update_state = new ContentValues();
        update_state.put(ESM_Data.STATUS, ESM.STATUS_VISIBLE);
        getActivity().getContentResolver().update(ESM_Data.CONTENT_URI, update_state,
                ESM_Data._ID + "=" + esm_id, null);

        esm_type = visible_esm.getInt(visible_esm.getColumnIndex(ESM_Data.TYPE));
        expires_seconds = visible_esm.getInt(visible_esm.getColumnIndex(ESM_Data.EXPIRATION_THREASHOLD));

        builder.setTitle(visible_esm.getString(visible_esm.getColumnIndex(ESM_Data.TITLE)));

        View ui = null;
        switch (esm_type) {
        case ESM.TYPE_ESM_TEXT:
            ui = inflater.inflate(R.layout.esm_text, null);
            break;
        case ESM.TYPE_ESM_RADIO:
            ui = inflater.inflate(R.layout.esm_radio, null);
            break;
        case ESM.TYPE_ESM_CHECKBOX:
            ui = inflater.inflate(R.layout.esm_checkbox, null);
            break;
        case ESM.TYPE_ESM_LIKERT:
            ui = inflater.inflate(R.layout.esm_likert, null);
            break;
        case ESM.TYPE_ESM_QUICK_ANSWERS:
            ui = inflater.inflate(R.layout.esm_quick, null);
            break;
        }

        final View layout = ui;
        builder.setView(layout);
        current_dialog = builder.create();
        sContext = current_dialog.getContext();

        TextView esm_instructions = (TextView) layout.findViewById(R.id.esm_instructions);
        esm_instructions.setText(visible_esm.getString(visible_esm.getColumnIndex(ESM_Data.INSTRUCTIONS)));

        switch (esm_type) {
        case ESM.TYPE_ESM_TEXT:
            final EditText feedback = (EditText) layout.findViewById(R.id.esm_feedback);
            Button cancel_text = (Button) layout.findViewById(R.id.esm_cancel);
            cancel_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    inputManager.hideSoftInputFromWindow(feedback.getWindowToken(), 0);
                    current_dialog.cancel();
                }
            });
            Button submit_text = (Button) layout.findViewById(R.id.esm_submit);
            submit_text.setText(visible_esm.getString(visible_esm.getColumnIndex(ESM_Data.SUBMIT)));
            submit_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    inputManager.hideSoftInputFromWindow(feedback.getWindowToken(), 0);

                    if (expires_seconds > 0 && expire_monitor != null)
                        expire_monitor.cancel(true);

                    ContentValues rowData = new ContentValues();
                    rowData.put(ESM_Data.ANSWER_TIMESTAMP, System.currentTimeMillis());
                    rowData.put(ESM_Data.ANSWER, feedback.getText().toString());
                    rowData.put(ESM_Data.STATUS, ESM.STATUS_ANSWERED);

                    sContext.getContentResolver().update(ESM_Data.CONTENT_URI, rowData,
                            ESM_Data._ID + "=" + esm_id, null);

                    Intent answer = new Intent(ESM.ACTION_AWARE_ESM_ANSWERED);
                    getActivity().sendBroadcast(answer);

                    if (Aware.DEBUG)
                        Log.d(TAG, "Answer:" + rowData.toString());

                    current_dialog.dismiss();
                }
            });
            break;
        case ESM.TYPE_ESM_RADIO:
            try {
                final RadioGroup radioOptions = (RadioGroup) layout.findViewById(R.id.esm_radio);
                final JSONArray radios = new JSONArray(
                        visible_esm.getString(visible_esm.getColumnIndex(ESM_Data.RADIOS)));

                for (int i = 0; i < radios.length(); i++) {
                    final RadioButton radioOption = new RadioButton(getActivity());
                    radioOption.setId(i);
                    radioOption.setText(radios.getString(i));
                    radioOptions.addView(radioOption);

                    if (radios.getString(i).equals("Other")) {
                        radioOption.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                final Dialog editOther = new Dialog(getActivity());
                                editOther.setTitle("Can you be more specific, please?");
                                editOther.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                                editOther.getWindow().setGravity(Gravity.TOP);
                                editOther.getWindow().setLayout(LayoutParams.MATCH_PARENT,
                                        LayoutParams.WRAP_CONTENT);

                                LinearLayout editor = new LinearLayout(getActivity());
                                editor.setOrientation(LinearLayout.VERTICAL);

                                editOther.setContentView(editor);
                                editOther.show();

                                final EditText otherText = new EditText(getActivity());
                                editor.addView(otherText);

                                Button confirm = new Button(getActivity());
                                confirm.setText("OK");
                                confirm.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if (otherText.length() > 0)
                                            radioOption.setText(otherText.getText());
                                        inputManager.hideSoftInputFromWindow(otherText.getWindowToken(), 0);
                                        editOther.dismiss();
                                    }
                                });
                                editor.addView(confirm);
                            }
                        });
                    }
                }
                Button cancel_radio = (Button) layout.findViewById(R.id.esm_cancel);
                cancel_radio.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        current_dialog.cancel();
                    }
                });
                Button submit_radio = (Button) layout.findViewById(R.id.esm_submit);
                submit_radio.setText(visible_esm.getString(visible_esm.getColumnIndex(ESM_Data.SUBMIT)));
                submit_radio.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        if (expires_seconds > 0 && expire_monitor != null)
                            expire_monitor.cancel(true);

                        ContentValues rowData = new ContentValues();
                        rowData.put(ESM_Data.ANSWER_TIMESTAMP, System.currentTimeMillis());

                        RadioGroup radioOptions = (RadioGroup) layout.findViewById(R.id.esm_radio);
                        if (radioOptions.getCheckedRadioButtonId() != -1) {
                            RadioButton selected = (RadioButton) radioOptions
                                    .getChildAt(radioOptions.getCheckedRadioButtonId());
                            rowData.put(ESM_Data.ANSWER, selected.getText().toString());
                        }
                        rowData.put(ESM_Data.STATUS, ESM.STATUS_ANSWERED);

                        sContext.getContentResolver().update(ESM_Data.CONTENT_URI, rowData,
                                ESM_Data._ID + "=" + esm_id, null);

                        Intent answer = new Intent(ESM.ACTION_AWARE_ESM_ANSWERED);
                        getActivity().sendBroadcast(answer);

                        if (Aware.DEBUG)
                            Log.d(TAG, "Answer:" + rowData.toString());

                        current_dialog.dismiss();
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
            break;
        case ESM.TYPE_ESM_CHECKBOX:
            try {
                final LinearLayout checkboxes = (LinearLayout) layout.findViewById(R.id.esm_checkboxes);
                final JSONArray checks = new JSONArray(
                        visible_esm.getString(visible_esm.getColumnIndex(ESM_Data.CHECKBOXES)));

                for (int i = 0; i < checks.length(); i++) {
                    final CheckBox checked = new CheckBox(getActivity());
                    checked.setText(checks.getString(i));
                    checked.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
                            if (isChecked) {
                                if (buttonView.getText().equals("Other")) {
                                    checked.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            final Dialog editOther = new Dialog(getActivity());
                                            editOther.setTitle("Can you be more specific, please?");
                                            editOther.getWindow()
                                                    .setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                                            editOther.getWindow().setGravity(Gravity.TOP);
                                            editOther.getWindow().setLayout(LayoutParams.MATCH_PARENT,
                                                    LayoutParams.WRAP_CONTENT);

                                            LinearLayout editor = new LinearLayout(getActivity());
                                            editor.setOrientation(LinearLayout.VERTICAL);
                                            editOther.setContentView(editor);
                                            editOther.show();

                                            final EditText otherText = new EditText(getActivity());
                                            editor.addView(otherText);

                                            Button confirm = new Button(getActivity());
                                            confirm.setText("OK");
                                            confirm.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    if (otherText.length() > 0) {
                                                        inputManager.hideSoftInputFromWindow(
                                                                otherText.getWindowToken(), 0);
                                                        selected_options
                                                                .remove(buttonView.getText().toString());
                                                        checked.setText(otherText.getText());
                                                        selected_options.add(otherText.getText().toString());
                                                    }
                                                    editOther.dismiss();
                                                }
                                            });
                                            editor.addView(confirm);
                                        }
                                    });
                                } else {
                                    selected_options.add(buttonView.getText().toString());
                                }
                            } else {
                                selected_options.remove(buttonView.getText().toString());
                            }
                        }
                    });
                    checkboxes.addView(checked);
                }
                Button cancel_checkbox = (Button) layout.findViewById(R.id.esm_cancel);
                cancel_checkbox.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        current_dialog.cancel();
                    }
                });
                Button submit_checkbox = (Button) layout.findViewById(R.id.esm_submit);
                submit_checkbox.setText(visible_esm.getString(visible_esm.getColumnIndex(ESM_Data.SUBMIT)));
                submit_checkbox.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        if (expires_seconds > 0 && expire_monitor != null)
                            expire_monitor.cancel(true);

                        ContentValues rowData = new ContentValues();
                        rowData.put(ESM_Data.ANSWER_TIMESTAMP, System.currentTimeMillis());

                        if (selected_options.size() > 0) {
                            rowData.put(ESM_Data.ANSWER, selected_options.toString());
                        }

                        rowData.put(ESM_Data.STATUS, ESM.STATUS_ANSWERED);

                        sContext.getContentResolver().update(ESM_Data.CONTENT_URI, rowData,
                                ESM_Data._ID + "=" + esm_id, null);

                        Intent answer = new Intent(ESM.ACTION_AWARE_ESM_ANSWERED);
                        getActivity().sendBroadcast(answer);

                        if (Aware.DEBUG)
                            Log.d(TAG, "Answer:" + rowData.toString());

                        current_dialog.dismiss();
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
            break;
        case ESM.TYPE_ESM_LIKERT:
            final RatingBar ratingBar = (RatingBar) layout.findViewById(R.id.esm_likert);
            ratingBar.setMax(visible_esm.getInt(visible_esm.getColumnIndex(ESM_Data.LIKERT_MAX)));
            ratingBar.setStepSize(
                    (float) visible_esm.getDouble(visible_esm.getColumnIndex(ESM_Data.LIKERT_STEP)));
            ratingBar.setNumStars(visible_esm.getInt(visible_esm.getColumnIndex(ESM_Data.LIKERT_MAX)));

            TextView min_label = (TextView) layout.findViewById(R.id.esm_min);
            min_label.setText(visible_esm.getString(visible_esm.getColumnIndex(ESM_Data.LIKERT_MIN_LABEL)));

            TextView max_label = (TextView) layout.findViewById(R.id.esm_max);
            max_label.setText(visible_esm.getString(visible_esm.getColumnIndex(ESM_Data.LIKERT_MAX_LABEL)));

            Button cancel = (Button) layout.findViewById(R.id.esm_cancel);
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    current_dialog.cancel();
                }
            });
            Button submit = (Button) layout.findViewById(R.id.esm_submit);
            submit.setText(visible_esm.getString(visible_esm.getColumnIndex(ESM_Data.SUBMIT)));
            submit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (expires_seconds > 0 && expire_monitor != null)
                        expire_monitor.cancel(true);

                    ContentValues rowData = new ContentValues();
                    rowData.put(ESM_Data.ANSWER_TIMESTAMP, System.currentTimeMillis());
                    rowData.put(ESM_Data.ANSWER, ratingBar.getRating());
                    rowData.put(ESM_Data.STATUS, ESM.STATUS_ANSWERED);

                    sContext.getContentResolver().update(ESM_Data.CONTENT_URI, rowData,
                            ESM_Data._ID + "=" + esm_id, null);

                    Intent answer = new Intent(ESM.ACTION_AWARE_ESM_ANSWERED);
                    getActivity().sendBroadcast(answer);

                    if (Aware.DEBUG)
                        Log.d(TAG, "Answer:" + rowData.toString());

                    current_dialog.dismiss();
                }
            });
            break;
        case ESM.TYPE_ESM_QUICK_ANSWERS:
            try {
                final JSONArray answers = new JSONArray(
                        visible_esm.getString(visible_esm.getColumnIndex(ESM_Data.QUICK_ANSWERS)));
                final LinearLayout answersHolder = (LinearLayout) layout.findViewById(R.id.esm_answers);

                //If we have more than 3 possibilities, better that the UI is vertical for UX
                if (answers.length() > 3) {
                    answersHolder.setOrientation(LinearLayout.VERTICAL);
                }

                for (int i = 0; i < answers.length(); i++) {
                    final Button answer = new Button(getActivity());
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                            LayoutParams.WRAP_CONTENT, 1.0f);
                    answer.setLayoutParams(params);
                    answer.setText(answers.getString(i));
                    answer.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            if (expires_seconds > 0 && expire_monitor != null)
                                expire_monitor.cancel(true);

                            ContentValues rowData = new ContentValues();
                            rowData.put(ESM_Data.ANSWER_TIMESTAMP, System.currentTimeMillis());
                            rowData.put(ESM_Data.STATUS, ESM.STATUS_ANSWERED);
                            rowData.put(ESM_Data.ANSWER, (String) answer.getText());

                            sContext.getContentResolver().update(ESM_Data.CONTENT_URI, rowData,
                                    ESM_Data._ID + "=" + esm_id, null);

                            Intent answer = new Intent(ESM.ACTION_AWARE_ESM_ANSWERED);
                            getActivity().sendBroadcast(answer);

                            if (Aware.DEBUG)
                                Log.d(TAG, "Answer:" + rowData.toString());

                            current_dialog.dismiss();
                        }
                    });
                    answersHolder.addView(answer);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            break;
        }
    }
    if (visible_esm != null && !visible_esm.isClosed())
        visible_esm.close();

    //Start dialog visibility threshold
    if (expires_seconds > 0) {
        expire_monitor = new ESMExpireMonitor(System.currentTimeMillis(), expires_seconds, esm_id);
        expire_monitor.execute();
    }

    //Fixed: doesn't dismiss the dialog if touched outside or ghost touches
    current_dialog.setCanceledOnTouchOutside(false);

    return current_dialog;
}

From source file:com.vonglasow.michael.satstat.ui.RadioSectionFragment.java

private final void addWifiResult(ScanResult result) {
    // needed to pass a persistent reference to the OnClickListener
    final ScanResult r = result;
    android.view.View.OnClickListener clis = new android.view.View.OnClickListener() {

        @Override/*from   w ww .j  a  v a  2 s . c o m*/
        public void onClick(View v) {
            onWifiEntryClick(r.BSSID);
        }
    };

    LinearLayout wifiLayout = new LinearLayout(wifiAps.getContext());
    wifiLayout.setLayoutParams(
            new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    wifiLayout.setOrientation(LinearLayout.HORIZONTAL);
    wifiLayout.setWeightSum(22);
    wifiLayout.setMeasureWithLargestChildEnabled(false);

    ImageView wifiType = new ImageView(wifiAps.getContext());
    wifiType.setLayoutParams(new TableRow.LayoutParams(0, LayoutParams.MATCH_PARENT, 3));
    if (WifiCapabilities.isAdhoc(result)) {
        wifiType.setImageResource(R.drawable.ic_content_wifi_adhoc);
    } else if ((WifiCapabilities.isEnterprise(result))
            || (WifiCapabilities.getScanResultSecurity(result) == WifiCapabilities.EAP)) {
        wifiType.setImageResource(R.drawable.ic_content_wifi_eap);
    } else if (WifiCapabilities.getScanResultSecurity(result) == WifiCapabilities.PSK) {
        wifiType.setImageResource(R.drawable.ic_content_wifi_psk);
    } else if (WifiCapabilities.getScanResultSecurity(result) == WifiCapabilities.WEP) {
        wifiType.setImageResource(R.drawable.ic_content_wifi_wep);
    } else if (WifiCapabilities.getScanResultSecurity(result) == WifiCapabilities.OPEN) {
        wifiType.setImageResource(R.drawable.ic_content_wifi_open);
    } else {
        wifiType.setImageResource(R.drawable.ic_content_wifi_unknown);
    }

    wifiType.setScaleType(ScaleType.CENTER);
    wifiLayout.addView(wifiType);

    TableLayout wifiDetails = new TableLayout(wifiAps.getContext());
    wifiDetails.setLayoutParams(new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 19));
    TableRow innerRow1 = new TableRow(wifiAps.getContext());
    TextView newMac = new TextView(wifiAps.getContext());
    newMac.setLayoutParams(new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 14));
    newMac.setTextAppearance(wifiAps.getContext(), android.R.style.TextAppearance_Medium);
    newMac.setText(result.BSSID);
    innerRow1.addView(newMac);
    TextView newCh = new TextView(wifiAps.getContext());
    newCh.setLayoutParams(new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 2));
    newCh.setTextAppearance(wifiAps.getContext(), android.R.style.TextAppearance_Medium);
    newCh.setText(getChannelFromFrequency(result.frequency));
    innerRow1.addView(newCh);
    TextView newLevel = new TextView(wifiAps.getContext());
    newLevel.setLayoutParams(new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 3));
    newLevel.setTextAppearance(wifiAps.getContext(), android.R.style.TextAppearance_Medium);
    newLevel.setText(String.valueOf(result.level));
    innerRow1.addView(newLevel);
    innerRow1.setOnClickListener(clis);
    wifiDetails.addView(innerRow1,
            new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

    TableRow innerRow2 = new TableRow(wifiAps.getContext());
    TextView newSSID = new TextView(wifiAps.getContext());
    newSSID.setLayoutParams(new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 19));
    newSSID.setTextAppearance(wifiAps.getContext(), android.R.style.TextAppearance_Small);
    newSSID.setText(result.SSID);
    innerRow2.addView(newSSID);
    innerRow2.setOnClickListener(clis);
    wifiDetails.addView(innerRow2,
            new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

    wifiLayout.addView(wifiDetails);
    wifiLayout.setOnClickListener(clis);
    wifiAps.addView(wifiLayout);
}

From source file:org.apache.cordova.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject//from  w ww.  java  2  s .  c o m
 */
public String showWebPage(final String url, HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         *
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        public void run() {
            // Let's create the main dialog
            dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    closeDialog();
                }
            });

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            //Please, no more black! 
            toolbar.setBackgroundColor(android.graphics.Color.LTGRAY);
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            Button back = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            back.setText("<");
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            Button forward = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            forward.setText(">");
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close button
            Button close = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            close.setText(buttonLabel);
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new WebView(cordova.getActivity());
            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginState(android.webkit.WebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                CookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                CookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            toolbar.addView(actionButtonContainer);
            toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(inAppWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.oonhee.oojs.inappbrowser.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject// www .ja v  a2s .c  o m
 */
public String showWebPage(final String url, HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         *
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        public void run() {
            // Let's create the main dialog
            dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    closeDialog();
                }
            });

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            //Please, no more black! 
            toolbar.setBackgroundColor(android.graphics.Color.LTGRAY);
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            Button back = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            back.setText("<");
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            Button forward = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            forward.setText(">");
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close button
            Button close = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            close.setText(buttonLabel);
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new AmazonWebView(cordova.getActivity());

            CordovaActivity app = (CordovaActivity) cordova.getActivity();
            cordova.getFactory().initializeWebView(inAppWebView, 0x00FF00, false, null);

            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            AmazonWebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            AmazonWebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginState(com.amazon.android.webkit.AmazonWebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                AmazonCookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                AmazonCookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            toolbar.addView(actionButtonContainer);
            toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(inAppWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}