Example usage for android.widget Button Button

List of usage examples for android.widget Button Button

Introduction

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

Prototype

public Button(Context context) 

Source Link

Document

Simple constructor to use when creating a button from code.

Usage

From source file:jp.gr.java_conf.piropiroping.bluetoothcommander.MainActivity.java

private void setCommandButtonListener(String commandName, int commandVal) {
    Button commandButton = new Button(this); // ?
    commandButton.setText(commandName);/*from w  ww  . j  a  va2  s .  co m*/
    commandButton.setTextSize(20);
    commandButton.setBackgroundResource(R.drawable.command_button_background);
    savedCommand.add(commandVal, commandButton); // ???
    commandLayout.removeAllViews(); // ???
    for (int i = 0; i < commandVal + 1; i++) { // ?(?Button + PlusButton)
        commandLayout.addView(savedCommand.get(i));
    }
    commandLayout.addView(plusButton);

    /* ??? */
    commandButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            Button button = (Button) view;
            String name = button.getText().toString();
            try {
                InputStream in = openFileInput(name);
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                String s;
                mOutEditText.getText().clear();
                while ((s = reader.readLine()) != null) {
                    mOutEditText.append(s);
                }
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            setCommandData(); // ASCIIBitmap?
        }
    });

    /* ?? */
    commandButton.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(final View view) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(20);
            delState = true; // ?ON

            final Button button = (Button) view;
            final String name = button.getText().toString();

            AlertDialog.Builder deleteCommandDialog = new AlertDialog.Builder(MainActivity.this);
            deleteCommandDialog.setTitle("??????");
            deleteCommandDialog.setMessage(name);
            deleteCommandDialog.setPositiveButton("??", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // OK button pressed
                    deleteFile(name);
                    commandLayout.removeView(button);
                    savedCommand.remove(button);
                }
            });
            deleteCommandDialog.setNegativeButton("???", null);
            deleteCommandDialog.show();
            return false;
        }
    });
    /* Command delete design (TBD) */
    //        commandButton.setOnTouchListener(new View.OnTouchListener() {
    //            @Override
    //            public boolean onTouch(View view, MotionEvent motionEvent) {
    //                int x = (int) motionEvent.getRawX();
    //                int y = (int) motionEvent.getRawY();
    //
    //                switch (motionEvent.getAction()) {
    //                    case MotionEvent.ACTION_DOWN:
    //                        viewX = view.getLeft();
    //                        viewY = view.getTop();
    //                        currentX = x;
    //                        currentY = y;
    //                        break;
    //                    case MotionEvent.ACTION_MOVE:
    //                        LinearLayout topLayout = (LinearLayout) findViewById(R.id.top_layout);
    ////                        topLayout.addView(view);
    //                        if (delState == true) {
    //                            int ajustX = currentX - x;
    //                            int ajustY = currentY - y;
    //                            viewX = viewX - ajustX;
    //                            viewY = viewY - ajustY;
    //                            view.layout(viewX, viewY, viewX + view.getWidth(), viewY + view.getHeight());
    //                            currentX = x;
    //                            currentY = y;
    //                        }
    //                        break;
    //                    case MotionEvent.ACTION_UP:
    //                        delState = false;
    //                        // if(??)
    //                        //      
    //                        // else
    //                        //      ?xy???
    //
    //                        break;
    //
    //                }
    //                return false;
    //            }
    //        });
}

From source file:com.launcher.silverfish.launcher.appdrawer.TabFragmentHandler.java

public void addTab(String tabName) {
    if (tabName == null || tabName.isEmpty()) {
        throw new IllegalArgumentException("Tab packageName cannot be empty");
    } else {/*from   w w  w. j  a  v  a 2  s.  com*/
        // add the tab to database
        LauncherSQLiteHelper sql = new LauncherSQLiteHelper((App) mActivity.getApplication());
        TabTable tabEntry = sql.addTab(tabName);

        final TabInfo tab = new TabInfo(tabEntry);
        arrTabs.add(tab);

        // create a button for the tab
        LinearLayout tabWidget = (LinearLayout) rootView.findViewById(R.id.custom_tabwidget);

        Button btn = new Button(mActivity.getApplicationContext());
        btn.setText(tab.getLabel());
        arrButton.add(btn);

        // Set the style of the button
        btn.setBackground(settings.getTabButtonStyle());
        btn.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, 1));
        btn.setTextColor(settings.getFontFgColor());

        // Add the button to the tab widget.
        tabWidget.addView(btn);

        // And create a new tab
        TabHost.TabSpec tSpecFragmentId = tHost.newTabSpec(tab.getTag());
        tSpecFragmentId.setIndicator(tab.getLabel());
        tSpecFragmentId.setContent(new DummyTabContent(mActivity.getBaseContext()));
        tHost.addTab(tSpecFragmentId);

        final int tab_id = arrTabs.size() - 1;
        // add click listener to the button
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tabButtonClickListener.onClick(tab, tab_id);
            }
        });
        btn.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                return tabButtonClickListener.onLongClick(tab, tab_id);
            }
        });
    }

}

From source file:com.launcher.silverfish.TabFragmentHandler.java

public void addTab(String tab_name) {
    if (tab_name == null || tab_name.isEmpty()) {
        throw new IllegalArgumentException("Tab name cannot be empty");
    } else {//from   ww  w.  j  a  va2 s . c  o  m
        // add the tab to database
        LauncherSQLiteHelper sql = new LauncherSQLiteHelper(mActivity.getApplicationContext());
        TabTable tab_entry = sql.addTab(tab_name);

        final TabInfo tab = new TabInfo(tab_entry);
        arrTabs.add(tab);

        // create a button for the tab
        LinearLayout tabWidget = (LinearLayout) rootView.findViewById(R.id.custom_tabwidget);

        Button btn = new Button(mActivity.getApplicationContext());
        btn.setText(tab.getLabel());
        arrButton.add(btn);

        // Set the style of the button
        btn.setBackgroundResource(R.drawable.tab_style);
        btn.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, 1));
        btn.setTextColor(Color.WHITE);

        // Add the button to the tab widget.
        tabWidget.addView(btn);

        // And create a new tab
        TabHost.TabSpec tSpecFragmentId = tHost.newTabSpec(tab.getTag());
        tSpecFragmentId.setIndicator(tab.getLabel());
        tSpecFragmentId.setContent(new DummyTabContent(mActivity.getBaseContext()));
        tHost.addTab(tSpecFragmentId);

        final int tab_id = arrTabs.size() - 1;
        // add click listener to the button
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tabButtonClickListener.onClick(tab, tab_id);
            }
        });
        btn.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                return tabButtonClickListener.onLongClick(tab, tab_id);
            }
        });
    }

}

From source file:com.nttec.everychan.http.recaptcha.Recaptcha2fallback.java

@Override
public void handle(final Activity activity, final CancellableTask task, final Callback callback) {
    try {/*from   w  w w . j a va 2  s  . c o m*/
        final HttpClient httpClient = ((HttpChanModule) MainApplication.getInstance().getChanModule(chanName))
                .getHttpClient();
        final String usingURL = scheme + RECAPTCHA_FALLBACK_URL + publicKey
                + (sToken != null && sToken.length() > 0 ? ("&stoken=" + sToken) : "");
        String refererURL = baseUrl != null && baseUrl.length() > 0 ? baseUrl : usingURL;
        Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, refererURL) };
        String htmlChallenge;
        if (lastChallenge != null && lastChallenge.getLeft().equals(usingURL)) {
            htmlChallenge = lastChallenge.getRight();
        } else {
            htmlChallenge = HttpStreamer.getInstance().getStringFromUrl(usingURL,
                    HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient,
                    null, task, false);
        }
        lastChallenge = null;

        Matcher challengeMatcher = Pattern.compile("name=\"c\" value=\"([\\w-]+)").matcher(htmlChallenge);
        if (challengeMatcher.find()) {
            final String challenge = challengeMatcher.group(1);
            HttpResponseModel responseModel = HttpStreamer.getInstance().getFromUrl(
                    scheme + RECAPTCHA_IMAGE_URL + challenge + "&k=" + publicKey,
                    HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient,
                    null, task);
            try {
                InputStream imageStream = responseModel.stream;
                final Bitmap challengeBitmap = BitmapFactory.decodeStream(imageStream);

                final String message;
                Matcher messageMatcher = Pattern.compile("imageselect-message(?:.*?)>(.*?)</div>")
                        .matcher(htmlChallenge);
                if (messageMatcher.find())
                    message = RegexUtils.removeHtmlTags(messageMatcher.group(1));
                else
                    message = null;

                final Bitmap candidateBitmap;
                Matcher candidateMatcher = Pattern
                        .compile("fbc-imageselect-candidates(?:.*?)src=\"data:image/(?:.*?);base64,([^\"]*)\"")
                        .matcher(htmlChallenge);
                if (candidateMatcher.find()) {
                    Bitmap bmp = null;
                    try {
                        byte[] imgData = Base64.decode(candidateMatcher.group(1), Base64.DEFAULT);
                        bmp = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
                    } catch (Exception e) {
                    }
                    candidateBitmap = bmp;
                } else
                    candidateBitmap = null;

                activity.runOnUiThread(new Runnable() {
                    final int maxX = 3;
                    final int maxY = 3;
                    final boolean[] isSelected = new boolean[maxX * maxY];

                    @SuppressLint("InlinedApi")
                    @Override
                    public void run() {
                        LinearLayout rootLayout = new LinearLayout(activity);
                        rootLayout.setOrientation(LinearLayout.VERTICAL);

                        if (candidateBitmap != null) {
                            ImageView candidateView = new ImageView(activity);
                            candidateView.setImageBitmap(candidateBitmap);
                            int picSize = (int) (activity.getResources().getDisplayMetrics().density * 50
                                    + 0.5f);
                            candidateView.setLayoutParams(new LinearLayout.LayoutParams(picSize, picSize));
                            candidateView.setScaleType(ImageView.ScaleType.FIT_XY);
                            rootLayout.addView(candidateView);
                        }

                        if (message != null) {
                            TextView textView = new TextView(activity);
                            textView.setText(message);
                            CompatibilityUtils.setTextAppearance(textView, android.R.style.TextAppearance);
                            textView.setLayoutParams(
                                    new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                            LinearLayout.LayoutParams.WRAP_CONTENT));
                            rootLayout.addView(textView);
                        }

                        FrameLayout frame = new FrameLayout(activity);
                        frame.setLayoutParams(
                                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));

                        final ImageView imageView = new ImageView(activity);
                        imageView.setLayoutParams(new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        imageView.setImageBitmap(challengeBitmap);
                        frame.addView(imageView);

                        final LinearLayout selector = new LinearLayout(activity);
                        selector.setLayoutParams(new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                        AppearanceUtils.callWhenLoaded(imageView, new Runnable() {
                            @Override
                            public void run() {
                                selector.setLayoutParams(new FrameLayout.LayoutParams(imageView.getWidth(),
                                        imageView.getHeight()));
                            }
                        });
                        selector.setOrientation(LinearLayout.VERTICAL);
                        selector.setWeightSum(maxY);
                        for (int y = 0; y < maxY; ++y) {
                            LinearLayout subSelector = new LinearLayout(activity);
                            subSelector.setLayoutParams(new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));
                            subSelector.setOrientation(LinearLayout.HORIZONTAL);
                            subSelector.setWeightSum(maxX);
                            for (int x = 0; x < maxX; ++x) {
                                FrameLayout switcher = new FrameLayout(activity);
                                switcher.setLayoutParams(new LinearLayout.LayoutParams(0,
                                        LinearLayout.LayoutParams.MATCH_PARENT, 1f));
                                switcher.setTag(new int[] { x, y });
                                switcher.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        int[] coord = (int[]) v.getTag();
                                        int index = coord[1] * maxX + coord[0];
                                        isSelected[index] = !isSelected[index];
                                        v.setBackgroundColor(isSelected[index] ? Color.argb(128, 0, 255, 0)
                                                : Color.TRANSPARENT);
                                    }
                                });
                                subSelector.addView(switcher);
                            }
                            selector.addView(subSelector);
                        }

                        frame.addView(selector);
                        rootLayout.addView(frame);

                        Button checkButton = new Button(activity);
                        checkButton.setLayoutParams(
                                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));
                        checkButton.setText(android.R.string.ok);
                        rootLayout.addView(checkButton);

                        ScrollView dlgView = new ScrollView(activity);
                        dlgView.addView(rootLayout);

                        final Dialog dialog = new Dialog(activity);
                        dialog.setTitle("Recaptcha");
                        dialog.setContentView(dlgView);
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                if (!task.isCancelled()) {
                                    callback.onError("Cancelled");
                                }
                            }
                        });
                        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT);
                        dialog.show();

                        checkButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                if (task.isCancelled())
                                    return;
                                Async.runAsync(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                                            pairs.add(new BasicNameValuePair("c", challenge));
                                            for (int i = 0; i < isSelected.length; ++i)
                                                if (isSelected[i])
                                                    pairs.add(new BasicNameValuePair("response",
                                                            Integer.toString(i)));

                                            HttpRequestModel request = HttpRequestModel.builder()
                                                    .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8"))
                                                    .setCustomHeaders(new Header[] {
                                                            new BasicHeader(HttpHeaders.REFERER, usingURL) })
                                                    .build();
                                            String response = HttpStreamer.getInstance().getStringFromUrl(
                                                    usingURL, request, httpClient, null, task, false);
                                            String hash = "";
                                            Matcher matcher = Pattern.compile(
                                                    "fbc-verification-token(?:.*?)<textarea[^>]*>([^<]*)<",
                                                    Pattern.DOTALL).matcher(response);
                                            if (matcher.find())
                                                hash = matcher.group(1);

                                            if (hash.length() > 0) {
                                                Recaptcha2solved.push(publicKey, hash);
                                                activity.runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        callback.onSuccess();
                                                    }
                                                });
                                            } else {
                                                lastChallenge = Pair.of(usingURL, response);
                                                throw new RecaptchaException(
                                                        "incorrect answer (hash is empty)");
                                            }
                                        } catch (final Exception e) {
                                            Logger.e(TAG, e);
                                            if (task.isCancelled())
                                                return;
                                            handle(activity, task, callback);
                                        }
                                    }
                                });
                            }
                        });
                    }
                });
            } finally {
                responseModel.release();
            }
        } else
            throw new Exception("can't parse recaptcha challenge answer");
    } catch (final Exception e) {
        Logger.e(TAG, e);
        if (!task.isCancelled()) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    callback.onError(e.getMessage() != null ? e.getMessage() : e.toString());
                }
            });
        }
    }
}

From source file:tinygsn.gui.android.ActivityViewData.java

private void addTableViewModeCustomize() {
    table_view_mode = (TableLayout) findViewById(R.id.table_view_mode);
    table_view_mode.removeAllViews();//w ww.j  a  v a  2s .  c o  m

    // Row From
    TableRow row = new TableRow(this);
    TextView txt = new TextView(this);
    txt.setText("From: ");
    txt.setTextColor(Color.parseColor("#000000"));
    row.addView(txt);

    //      Date time = new Date();
    startTime = new Date();
    startTime.setMinutes(startTime.getMinutes() - 1);
    endTime = new Date();

    // Start Time
    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
    txtStartTime = new TextView(this);
    txtStartTime.setText(formatter.format(startTime) + "");
    txtStartTime.setTextColor(Color.parseColor("#000000"));
    txtStartTime.setBackgroundColor(Color.parseColor("#61a7db"));
    row.addView(txtStartTime);

    txtStartTime.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            new TimePickerDialog(context, startTimeSetListener, dateAndTime.get(Calendar.HOUR_OF_DAY) - 1,
                    dateAndTime.get(Calendar.MINUTE), true).show();
        }
    });

    // Add space
    txt = new TextView(this);
    txt.setText("     ");
    row.addView(txt);

    // Start Date
    formatter = new SimpleDateFormat("dd/MM/yyyy");
    // txtStartDate, txtStartTime
    txtStartDate = new TextView(this);
    txtStartDate.setText(formatter.format(startTime) + "");
    txtStartDate.setTextColor(Color.parseColor("#000000"));
    txtStartDate.setBackgroundColor(Color.parseColor("#61a7db"));
    row.addView(txtStartDate);

    txtStartDate.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            new DatePickerDialog(context, startDateSetListener, dateAndTime.get(Calendar.YEAR),
                    dateAndTime.get(Calendar.MONTH), dateAndTime.get(Calendar.DAY_OF_MONTH)).show();
        }
    });

    table_view_mode.addView(row);

    // Add a space row
    row = new TableRow(this);
    txt = new TextView(this);
    txt.setText("-");
    row.addView(txt);
    table_view_mode.addView(row);

    // Row To
    row = new TableRow(this);
    txt = new TextView(this);
    txt.setText("To");
    txt.setTextColor(Color.parseColor("#000000"));
    row.addView(txt);

    // End Time
    formatter = new SimpleDateFormat("HH:mm:ss");
    txtEndTime = new TextView(this);
    txtEndTime.setText(formatter.format(endTime) + "");
    txtEndTime.setTextColor(Color.parseColor("#000000"));
    txtEndTime.setBackgroundColor(Color.parseColor("#61a7db"));
    row.addView(txtEndTime);

    txtEndTime.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            new TimePickerDialog(context, endTimeSetListener, dateAndTime.get(Calendar.HOUR_OF_DAY),
                    dateAndTime.get(Calendar.MINUTE), true).show();
        }
    });

    // Add space
    txt = new TextView(this);
    txt.setText("     ");
    row.addView(txt);

    // End Date
    formatter = new SimpleDateFormat("dd/MM/yyyy");
    // txtStartDate, txtStartTime
    txtEndDate = new TextView(this);
    txtEndDate.setText(formatter.format(endTime) + "");
    txtEndDate.setTextColor(Color.parseColor("#000000"));
    txtEndDate.setBackgroundColor(Color.parseColor("#61a7db"));
    row.addView(txtEndDate);

    txtEndDate.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            new DatePickerDialog(context, endDateSetListener, dateAndTime.get(Calendar.YEAR),
                    dateAndTime.get(Calendar.MONTH), dateAndTime.get(Calendar.DAY_OF_MONTH)).show();
        }
    });

    table_view_mode.addView(row);

    // Row
    row = new TableRow(this);
    Button detailBtn = new Button(this);
    detailBtn.setTextSize(TEXT_SIZE + 4);
    detailBtn.setText("Detail");
    detailBtn.setTextColor(Color.parseColor("#000000"));
    detailBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

    Button plotDataBtn = new Button(this);
    plotDataBtn.setTextSize(TEXT_SIZE + 4);
    plotDataBtn.setText("Plot data");
    plotDataBtn.setTextColor(Color.parseColor("#000000"));
    plotDataBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            viewChart();
        }
    });

    TableRow.LayoutParams params = new TableRow.LayoutParams();
    // params.addRule(TableRow.LayoutParams.FILL_PARENT);
    params.span = 2;

    row.addView(detailBtn, params);
    row.addView(plotDataBtn, params);
    row.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    table_view_mode.addView(row);

}

From source file:org.odk.collect.android.widgets.QuestionWidget.java

protected Button getSimpleButton(String text) {
    Button button = new Button(getContext());
    button.setId(ViewIds.generateViewId());
    button.setText(text);//  w  ww .  j a v a  2s.  c o m
    button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontsize);
    button.setPadding(20, 20, 20, 20);

    TableLayout.LayoutParams params = new TableLayout.LayoutParams();
    params.setMargins(7, 5, 7, 5);

    button.setLayoutParams(params);
    return button;
}

From source file:bruce.kk.brucetodos.MainActivity.java

/**
 * ???/*from w  ww. j  av a2 s. co m*/
 *
 * @param position
 */
private void modifyItem(final int position) {
    final UnFinishItem item = dataList.get(position);
    LogDetails.d(item);
    LinearLayout linearLayout = new LinearLayout(MainActivity.this);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    linearLayout.setLayoutParams(layoutParams);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    linearLayout.setBackgroundColor(getResources().getColor(android.R.color.black));

    final EditText editText = new EditText(MainActivity.this);
    editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
    editText.setTextColor(getResources().getColor(android.R.color.holo_green_light));
    editText.setHint(item.content);
    editText.setHintTextColor(getResources().getColor(android.R.color.holo_orange_dark));

    linearLayout.addView(editText);

    Button btnModify = new Button(MainActivity.this);
    btnModify.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    btnModify.setText("");
    btnModify.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
    btnModify.setTextColor(getResources().getColor(android.R.color.holo_blue_bright));
    btnModify.setBackgroundColor(getResources().getColor(android.R.color.black));

    linearLayout.addView(btnModify);

    Button btnDeleteItem = new Button(MainActivity.this);
    btnDeleteItem.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    btnDeleteItem.setText("");
    btnDeleteItem.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
    btnDeleteItem.setTextColor(getResources().getColor(android.R.color.holo_blue_bright));
    btnDeleteItem.setBackgroundColor(getResources().getColor(android.R.color.black));

    linearLayout.addView(btnDeleteItem);

    final PopupWindow popupWindow = new PopupWindow(linearLayout, ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    popupWindow.setBackgroundDrawable(new BitmapDrawable()); // ?
    popupWindow.setTouchable(true);
    popupWindow.setFocusable(true);
    popupWindow.setOutsideTouchable(true);
    popupWindow.showAtLocation(contentMain, Gravity.CENTER, 0, 0);

    btnModify.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            LogDetails.d(": " + editText.getText().toString());
            if (!TextUtils.isEmpty(editText.getText().toString().trim())) {
                Date date = new Date();
                item.content = editText.getText().toString().trim();
                item.modifyDay = date;
                item.finishDay = null;
                ProgressDialogUtils.showProgressDialog();
                presenter.modifyItem(item);
                dataList.set(position, item);
                refreshData(true);
                popupWindow.dismiss();
            } else {
                Toast.makeText(MainActivity.this, "~", Toast.LENGTH_SHORT).show();
            }
        }
    });
    btnDeleteItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dataList.remove(position);
            presenter.deleteItem(item);
            refreshData(false);
            popupWindow.dismiss();
        }
    });
}

From source file:com.hichinaschool.flashcards.anki.multimediacard.activity.MultimediaCardEditorActivity.java

private void createNewViewer(LinearLayout linearLayout, final IField field, final int index) {

    final MultimediaCardEditorActivity context = this;

    switch (field.getType()) {
    case TEXT://from  www. j  a va 2  s  .c  om

        // Create a text field and an edit button, opening editing for
        // the
        // text field

        TextView textView = new TextView(this);
        textView.setText(field.getText());
        linearLayout.addView(textView, LinearLayout.LayoutParams.MATCH_PARENT);

        break;

    case IMAGE:

        ImageView imgView = new ImageView(this);
        //
        // BitmapFactory.Options options = new BitmapFactory.Options();
        // options.inSampleSize = 2;
        // Bitmap bm = BitmapFactory.decodeFile(myJpgPath, options);
        // jpgView.setImageBitmap(bm);

        LinearLayout.LayoutParams p = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

        File f = new File(field.getImagePath());

        Bitmap b = BitmapUtil.decodeFile(f, getMaxImageSize());

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.ECLAIR) {
            b = ExifUtil.rotateFromCamera(f, b);
        }

        imgView.setImageBitmap(b);

        imgView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        imgView.setAdjustViewBounds(true);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        int height = metrics.heightPixels;
        int width = metrics.widthPixels;

        imgView.setMaxHeight((int) Math.round(height * 0.6));
        imgView.setMaxWidth((int) Math.round(width * 0.7));
        linearLayout.addView(imgView, p);

        break;
    case AUDIO:
        AudioView audioView = AudioView.createPlayerInstance(this, R.drawable.av_play, R.drawable.av_pause,
                R.drawable.av_stop, field.getAudioPath());
        linearLayout.addView(audioView);
        break;

    default:
        Log.e("multimedia editor", "Unsupported field type found");
        break;
    }

    Button editButtonText = new Button(this);
    editButtonText.setText(gtxt(R.string.multimedia_editor_activity_edit_button));
    linearLayout.addView(editButtonText, LinearLayout.LayoutParams.MATCH_PARENT);

    editButtonText.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(context, EditFieldActivity.class);
            putExtrasAndStartEditActivity(field, index, i);
        }

    });
}

From source file:info.semanticsoftware.semassist.android.activity.SemanticAssistantsActivity.java

/** Presents additional information about a specific assistant.
 * @return a dynamically generated linear layout
 *//*from w ww .  j  av a  2  s .  co m*/
private LinearLayout getServiceDescLayout() {
    final LinearLayout output = new LinearLayout(this);
    final RelativeLayout topButtonsLayout = new RelativeLayout(this);
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

    final Button btnBack = new Button(this);
    btnBack.setText(R.string.btnAllServices);
    btnBack.setId(5);
    btnBack.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            output.setVisibility(View.GONE);
            getListView().setVisibility(View.VISIBLE);
            lblAvAssist.setVisibility(View.VISIBLE);
        }
    });

    topButtonsLayout.addView(btnBack);

    final Button btnInvoke = new Button(this);
    btnInvoke.setText(R.string.btnInvokeLabel);
    btnInvoke.setId(6);

    btnInvoke.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            new InvocationTask().execute();
        }
    });

    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, btnInvoke.getId());
    btnInvoke.setLayoutParams(layoutParams);
    topButtonsLayout.addView(btnInvoke);

    output.addView(topButtonsLayout);

    TableLayout serviceInfoTbl = new TableLayout(this);
    output.addView(serviceInfoTbl);

    serviceInfoTbl.setColumnShrinkable(1, true);

    /* FIRST ROW */
    TableRow rowServiceName = new TableRow(this);

    TextView lblServiceName = new TextView(this);
    lblServiceName.setText(R.string.lblServiceName);
    lblServiceName.setTextAppearance(getApplicationContext(), R.style.titleText);

    TextView txtServiceName = new TextView(this);
    txtServiceName.setText(selectedService);
    txtServiceName.setTextAppearance(getApplicationContext(), R.style.normalText);
    txtServiceName.setPadding(10, 0, 0, 0);

    rowServiceName.addView(lblServiceName);
    rowServiceName.addView(txtServiceName);

    /* SECOND ROW */
    TableRow rowServiceDesc = new TableRow(this);

    TextView lblServiceDesc = new TextView(this);
    lblServiceDesc.setText(R.string.lblServiceDesc);
    lblServiceDesc.setTextAppearance(getApplicationContext(), R.style.titleText);

    TextView txtServiceDesc = new TextView(this);
    txtServiceDesc.setTextAppearance(getApplicationContext(), R.style.normalText);
    txtServiceDesc.setPadding(10, 0, 0, 0);
    List<GateRuntimeParameter> params = null;
    ServiceInfoForClientArray list = getServices();
    for (int i = 0; i < list.getItem().size(); i++) {
        if (list.getItem().get(i).getServiceName().equals(selectedService)) {
            txtServiceDesc.setText(list.getItem().get(i).getServiceDescription());
            params = list.getItem().get(i).getParams();
            break;
        }
    }

    TextView lblParams = new TextView(this);
    lblParams.setText(R.string.lblServiceParams);
    lblParams.setTextAppearance(getApplicationContext(), R.style.titleText);
    output.addView(lblParams);

    LayoutParams txtParamsAttrbs = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    LinearLayout paramsLayout = new LinearLayout(this);
    paramsLayout.setId(0);

    if (params.size() > 0) {
        ScrollView scroll = new ScrollView(this);
        scroll.setLayoutParams(txtParamsAttrbs);
        paramsLayout.setOrientation(LinearLayout.VERTICAL);
        scroll.addView(paramsLayout);
        for (int j = 0; j < params.size(); j++) {
            TextView lblParamName = new TextView(this);
            lblParamName.setText(params.get(j).getParamName());
            EditText tview = new EditText(this);
            tview.setId(1);
            tview.setText(params.get(j).getDefaultValueString());
            LayoutParams txtViewLayoutParams = new LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT);
            tview.setLayoutParams(txtViewLayoutParams);
            paramsLayout.addView(lblParamName);
            paramsLayout.addView(tview);
        }
        output.addView(scroll);
    } else {
        TextView lblParamName = new TextView(this);
        lblParamName.setText(R.string.lblRTParams);
        output.addView(lblParamName);
    }

    rowServiceDesc.addView(lblServiceDesc);
    rowServiceDesc.addView(txtServiceDesc);

    serviceInfoTbl.addView(rowServiceName);
    serviceInfoTbl.addView(rowServiceDesc);

    output.setOrientation(LinearLayout.VERTICAL);
    output.setGravity(Gravity.TOP);

    return output;
}