List of usage examples for android.widget Button Button
public Button(Context context)
From source file:terse.a1.TerseActivity.java
private void viewPath9display(String path, LayoutParams widgetParams) { String explain;//from ww w . jav a 2 s . c o m if (terp_error != null) { explain = "terp_error = " + terp_error; } else { try { terp.say("Sending to terp: %s", path); final Dict d = terp.handleUrl(path, taQuery); explain = "DEFAULT EXPLANATION:\n\n" + d.toString(); Str TYPE = d.cls.terp.newStr("type"); Str VALUE = d.cls.terp.newStr("value"); Str TITLE = d.cls.terp.newStr("title"); Str type = (Str) d.dict.get(TYPE); Ur value = d.dict.get(VALUE); Ur title = d.dict.get(TITLE); // { // double ticks = Static.floatAt(d, "ticks", -1); // double nanos = Static.floatAt(d, "nanos", -1); // Toast.makeText( // getApplicationContext(), // Static.fmt("%d ticks, %.3f secs", (long) ticks, // (double) nanos / 1e9), Toast.LENGTH_SHORT) // .show(); // } if (type.str.equals("list") && value instanceof Vec) { final ArrayList<Ur> v = ((Vec) value).vec; final ArrayList<String> labels = new ArrayList<String>(); final ArrayList<String> links = new ArrayList<String>(); for (int i = 0; i < v.size(); i++) { Ur item = v.get(i); String label = item instanceof Str ? ((Str) item).str : item.toString(); if (item instanceof Vec && ((Vec) item).vec.size() == 2) { // OLD STYLE label = ((Vec) item).vec.get(0).toString(); Matcher m = LINK_P.matcher(label); if (m.lookingAt()) { label = m.group(2) + " " + m.group(3); } label += " [" + ((Vec) item).vec.get(1).toString().length() + "]"; links.add(null); // Use old style, not links. } else { // NEW STYLE label = item.toString(); if (label.charAt(0) == '/') { String link = Terp.WHITE_PLUS.split(label, 2)[0]; links.add(link); } else { links.add(""); } } labels.add(label); } if (labels.size() != links.size()) terp.toss("lables#%d links#%d", labels.size(), links.size()); ListView listv = new ListView(this); listv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, labels)); listv.setLayoutParams(widgetParams); listv.setTextFilterEnabled(true); listv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // When clicked, show a toast with the TextView text // Toast.makeText(getApplicationContext(), // ((TextView) view).getText(), // Toast.LENGTH_SHORT).show(); String toast_text = ((TextView) view).getText().toString(); // if (v.get(position) instanceof Vec) { if (links.get(position) == null) { // OLD STYLE Vec pair = (Vec) v.get(position); if (pair.vec.size() == 2) { if (pair.vec.get(0) instanceof Str) { String[] words = ((Str) pair.vec.get(0)).str.split("\\|"); Log.i("TT-WORDS", terp.arrayToString(words)); toast_text += "\n\n" + Static.arrayToString(words); if (words[1].equals("link")) { Uri uri = new Uri.Builder().scheme("terse").path(words[2]).build(); Intent intent = new Intent("android.intent.action.MAIN", uri); intent.setClass(getApplicationContext(), TerseActivity.class); startActivity(intent); } } } } else { // NEW STYLE terp.say("NEW STYLE LIST SELECT #%d link=<%s> label=<%s>", position, links.get(position), labels.get(position)); if (links.get(position).length() > 0) { Uri uri = new Uri.Builder().scheme("terse").path(links.get(position)).build(); Intent intent = new Intent("android.intent.action.MAIN", uri); intent.setClass(getApplicationContext(), TerseActivity.class); startActivity(intent); } } // } // Toast.makeText(getApplicationContext(), // ((TextView) view).getText(), // Toast.LENGTH_SHORT).show(); } }); setContentView(listv); return; } else if (type.str.equals("edit") && value instanceof Str) { final EditText ed = new EditText(this); ed.setText(taSaveMe == null ? value.toString() : taSaveMe); ed.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); ed.setLayoutParams(widgetParams); // ed.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22); ed.setTextAppearance(this, R.style.teletype); ed.setBackgroundColor(Color.BLACK); ed.setGravity(Gravity.TOP); ed.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET); ed.setVerticalFadingEdgeEnabled(true); ed.setVerticalScrollBarEnabled(true); ed.setOnKeyListener(new 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)) { // // Perform action on key press // Toast.makeText(TerseActivity.this, ed.getText(), // Toast.LENGTH_SHORT).show(); // return true; // } return false; } }); Button btn = new Button(this); btn.setText("Save"); btn.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on clicks String text = ed.getText().toString(); text = Parser.charSubsts(text); Toast.makeText(TerseActivity.this, text, Toast.LENGTH_SHORT).show(); String action = stringAt(d, "action"); String query = ""; String f1 = stringAt(d, "field1"); String v1 = stringAt(d, "value1"); String f2 = stringAt(d, "field2"); String v2 = stringAt(d, "value2"); f1 = (f1 == null) ? "f1null" : f1; v1 = (v1 == null) ? "v1null" : v1; f2 = (f2 == null) ? "f2null" : f2; v2 = (v2 == null) ? "v2null" : v2; startTerseActivity(action, query, stringAt(d, "field1"), stringAt(d, "value1"), stringAt(d, "field2"), stringAt(d, "value2"), "text", text); } }); LinearLayout linear = new LinearLayout(this); linear.setOrientation(LinearLayout.VERTICAL); linear.addView(btn); linear.addView(ed); setContentView(linear); return; } else if (type.str.equals("draw") && value instanceof Vec) { Vec v = ((Vec) value); DrawView dv = new DrawView(this, v.vec, d); dv.setLayoutParams(widgetParams); setContentView(dv); return; } else if (type.str.equals("live")) { Blk blk = value.mustBlk(); Blk event = Static.urAt(d, "event").asBlk(); TerseSurfView tsv = new TerseSurfView(this, blk, event); setContentView(tsv); return; } else if (type.str.equals("fnord")) { Blk blk = value.mustBlk(); Blk event = Static.urAt(d, "event").asBlk(); FnordView fnord = new FnordView(this, blk, event); setContentView(fnord); return; } else if (type.str.equals("world") && value instanceof Str) { String newWorld = value.toString(); if (Terp.WORLD_P.matcher(newWorld).matches()) { world = newWorld; resetTerp(); explain = Static.fmt("Switching to world <%s>\nUse menu to go Home.", world); Toast.makeText(getApplicationContext(), explain, Toast.LENGTH_LONG).show(); } else { terp.toss("Bad world syntax (must be 3 letters then 0 to 3 digits: <%s>", newWorld); } // Fall thru for explainv.setText(explain). } else if (type.str.equals("text")) { explain = "<<< " + title + " >>>\n\n" + value.toString(); // Fall thru for explainv.setText(explain). } else if (type.str.equals("html")) { final WebView webview = new WebView(this); // webview.loadData(value.toString(), "text/html", null); webview.loadDataWithBaseURL("terse://terse", value.toString(), "text/html", "UTF-8", null); webview.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // terp.say("WebView UrlLoading: url=%s", url); URI uri = URI.create("" + url); // terp.say("WebView UrlLoading: URI=%s", uri); terp.say("WebView UrlLoading: getPath=%s", uri.getPath()); terp.say("WebView UrlLoading: getQuery=%s", uri.getQuery()); // Toast.makeText(getApplicationContext(), // uri.toASCIIString(), Toast.LENGTH_SHORT) // .show(); // webview.invalidate(); // // TextView quick = new // TextView(TerseActivity.this); // quick.setText(uri.toASCIIString()); // quick.setBackgroundColor(Color.BLACK); // quick.setTextColor(Color.WHITE); // setContentView(quick); startTerseActivity(uri.getPath(), uri.getQuery()); return true; } }); // webview.setWebChromeClient(new WebChromeClient()); webview.getSettings().setBuiltInZoomControls(true); // webview.getSettings().setJavaScriptEnabled(true); webview.getSettings().setDefaultFontSize(18); webview.getSettings().setNeedInitialFocus(true); webview.getSettings().setSupportZoom(true); webview.getSettings().setSaveFormData(true); setContentView(webview); // ScrollView scrollv = new ScrollView(this); // scrollv.addView(webview); // setContentView(scrollv); return; } else { explain = "Unknown page type: " + type.str + " with vaule type: " + value.cls + "\n\n##############\n\n"; explain += value.toString(); // Fall thru for explainv.setText(explain). } } catch (Exception ex) { ex.printStackTrace(); explain = Static.describe(ex); } } TextView explainv = new TextView(this); explainv.setText(explain); explainv.setBackgroundColor(Color.BLACK); explainv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24); explainv.setTextColor(Color.YELLOW); SetContentViewWithHomeButtonAndScroll(explainv); }
From source file:com.mdlive.sav.MDLiveProviderDetails.java
/** * Successful Response Handler for Load Provider Info.Here the Profile image of * the Particular provider will be displayed.Along with that the Provider's * speciality,about the Provider , license and the languages will also be * displayed.Along with this Provider's affilitations will also be displayed * */// w w w .j a va2 s . co m private void handleSuccessResponse(JSONObject response) { // DEBUGGING. o.uwechue Log.d("MDLProviderDetails", "*********\nHTTP Response: " + response); try { //Fetch Data From the Services Log.d("Response details", "******************\n*******************\n" + response.toString()); JsonParser parser = new JsonParser(); JsonObject responObj = (JsonObject) parser.parse(response.toString()); JsonObject profileobj = responObj.get("doctor_profile").getAsJsonObject(); JsonObject providerdetObj = profileobj.get("provider_details").getAsJsonObject(); JsonObject appointment_slot = profileobj.get("appointment_slot").getAsJsonObject(); JsonArray available_hour = appointment_slot.get("available_hour").getAsJsonArray(); boolean isDoctorWithPatient = false; LinearLayout layout = (LinearLayout) findViewById(R.id.panelMessageFiles); String str_timeslot = ""; /*str_phys_avail_id = "",*/ SharedPreferences sharedpreferences = getSharedPreferences(PreferenceConstants.MDLIVE_USER_PREFERENCES, Context.MODE_PRIVATE); str_Availability_Type = sharedpreferences .getString(PreferenceConstants.PROVIDER_AVAILABILITY_TYPE_PREFERENCES, ""); String str_avail_status = sharedpreferences .getString(PreferenceConstants.PROVIDER_AVAILABILITY_STATUS_PREFERENCES, ""); if (str_avail_status.equalsIgnoreCase("true")) { if (str_Availability_Type.equalsIgnoreCase("video or phone")) { isDoctorAvailableNow = true; } else if (str_Availability_Type.equalsIgnoreCase("phone")) { isDoctorAvailableNow = true; } else if (str_Availability_Type.equalsIgnoreCase("video")) { isDoctorAvailableNow = true; } else if (str_Availability_Type.equalsIgnoreCase("With Patient")) { isDoctorAvailableNow = false; } else { isDoctorAvailableNow = false; } } else { isDoctorAvailableNow = false; } if (layout.getChildCount() > 0) { layout.removeAllViews(); } videoList.clear(); phoneList.clear(); for (int i = 0; i < available_hour.size(); i++) { JsonObject availabilityStatus = available_hour.get(i).getAsJsonObject(); String str_availabilityStatus = ""; if (MdliveUtils.checkJSONResponseHasString(availabilityStatus, "status")) { str_availabilityStatus = availabilityStatus.get("status").getAsString(); if (str_availabilityStatus.equals("Available")) { JsonArray timeSlotArray = availabilityStatus.get("time_slot").getAsJsonArray(); for (int j = 0; j < timeSlotArray.size(); j++) { JsonObject timeSlotObj = timeSlotArray.get(j).getAsJsonObject(); if (MdliveUtils.checkJSONResponseHasString(timeSlotObj, "appointment_type") && MdliveUtils.checkJSONResponseHasString(timeSlotObj, "timeslot")) { str_appointmenttype = timeSlotObj.get("appointment_type").getAsString(); str_timeslot = timeSlotObj.get("timeslot").getAsString(); selectedTimestamp = timeSlotObj.get("timeslot").getAsString(); Log.d("***TIMESLOT***", "****\n****\nTimeslot: [" + selectedTimestamp + "]"); if (MdliveUtils.checkJSONResponseHasString(timeSlotObj, "phys_availability_id")) { str_phys_avail_id = timeSlotObj.get("phys_availability_id").getAsString(); } else { str_phys_avail_id = null; } HashMap<String, String> map = new HashMap<String, String>(); map.put("timeslot", str_timeslot); map.put("phys_id", (str_phys_avail_id == null) ? "" : str_phys_avail_id + ""); map.put("appointment_type", str_appointmenttype); timeSlotListMap.add(map); if (str_timeslot.equals("0")) { if (!str_Availability_Type.equalsIgnoreCase("With Patient")) { final int density = (int) getBaseContext().getResources() .getDisplayMetrics().density; final Button myText = new Button(MDLiveProviderDetails.this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { myText.setElevation(0f); } isDoctorAvailableNow = true; LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.setMargins(4 * density, 4 * density, 4 * density, 4 * density); myText.setLayoutParams(params); myText.setGravity(Gravity.CENTER); myText.setTextColor(Color.WHITE); myText.setTextSize(16); myText.setPadding(8 * density, 4 * density, 8 * density, 4 * density); myText.setBackgroundResource(R.drawable.timeslot_white_rounded_corner); myText.setText("Now"); myText.setBackgroundResource(R.drawable.timeslot_blue_rounded_corner); myText.setClickable(true); previousSelectedTv = myText; if (str_appointmenttype.toLowerCase().contains("video")) { videoList.add(myText); } if (str_appointmenttype.toLowerCase().contains("phone")) { phoneList.add(myText); } LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(4 * density, 4 * density, 4 * density, 4 * density); myText.setLayoutParams(lp); myText.setTag("Now"); defaultNowTextPreferences(myText, str_appointmenttype); selectedTimeslot = true; clickEventForHorizontalText(myText, str_timeslot, str_phys_avail_id); layout.addView(myText); //layout.addView(line, 1); } } else { setHorizontalScrollviewTimeslots(layout, str_timeslot, j, str_phys_avail_id); } } } } else if (str_availabilityStatus.equalsIgnoreCase("With patient")) { isDoctorWithPatient = true; } } } //with patient if (isDoctorWithPatient) { if (layout.getChildCount() >= 1) { // Req Future Appmt enableOrdisableProviderDetails(str_Availability_Type); } else if (layout.getChildCount() < 1) { //Make future appointment onlyWithPatient(); } } /*This is for Status is available and the timeslot is Zero..Remaining all the status were not available.*/ //Available now only else if (isDoctorAvailableNow && layout.getChildCount() < 1) { horizontalscrollview.setVisibility(View.GONE); findViewById(R.id.dateTxtLayout).setVisibility(View.GONE); if (str_Availability_Type.equalsIgnoreCase("video")) { onlyVideo(); } else if (str_Availability_Type.equalsIgnoreCase("video or phone")) { VideoOrPhoneNotAvailable(); } else if (str_Availability_Type.equalsIgnoreCase("phone")) { onlyPhone(); } else if (str_Availability_Type.equalsIgnoreCase("With Patient")) { onlyWithPatient(); } } //Available now and later //Part1 ----> timeslot zero followed by many timeslots else if (isDoctorAvailableNow && layout.getChildCount() >= 1) { enableOrdisableProviderDetails(str_Availability_Type); } //part 2 available ly later //Part2 ----> timeslot not zero followed by many timeslots else if (!isDoctorAvailableNow && layout.getChildCount() >= 1) { availableOnlyLater(str_Availability_Type); } //not available else if (layout.getChildCount() == 0 && str_Availability_Type.equals("not available")) { if (str_appointmenttype.equals("1")) { notAvailable(); } else if (str_appointmenttype.equals("2")) { notAvailable(); } else { notAvailable(); } } //not available else if (layout.getChildCount() == 0) { horizontalscrollview.setVisibility(View.GONE); findViewById(R.id.dateTxtLayout).setVisibility(View.GONE); if (str_Availability_Type.equalsIgnoreCase("video")) { onlyVideo(); } else if (str_Availability_Type.equalsIgnoreCase("video or phone")) { VideoOrPhoneNotAvailable(); } else if (str_Availability_Type.equalsIgnoreCase("phone")) { onlyPhone(); } else if (str_Availability_Type.equalsIgnoreCase("With patient")) { onlyWithPatient(); } else if (str_Availability_Type.equalsIgnoreCase("not available")) { //Make future appointment only notAvailable(); } } setResponseQualificationDetails(providerdetObj, str_Availability_Type); } catch (Exception e) { e.printStackTrace(); } }
From source file:ru.adios.budgeter.widgets.DataTableLayout.java
private Button createButtonForFooter(int pageNum, boolean pressed) { final Button button = new Button(getContext()); button.setText(String.valueOf(pageNum)); if (pressed) { setNewPressedPageButton(button); }//from w w w . j a va 2s. c om button.setOnClickListener(buttonListener); return button; }
From source file:com.google.sample.beaconservice.ManageBeaconFragment.java
private LinearLayout makeAttachmentInsertRow() { LinearLayout insertRow = new LinearLayout(getActivity()); final TextView namespaceTextView = makeTextView(namespace); final EditText typeEditText = makeEditText(); final EditText dataEditText = makeEditText(); insertRow.addView(namespaceTextView); insertRow.addView(typeEditText);//from w w w .j a v a 2s . c o m insertRow.addView(dataEditText); Button insertButton = new Button(getActivity()); insertButton.setText("+"); insertButton.setLayoutParams(BUTTON_COL_LAYOUT); insertButton.setOnClickListener( makeInsertAttachmentOnClickListener(insertButton, namespaceTextView, typeEditText, dataEditText)); insertRow.addView(insertButton); return insertRow; }
From source file:eu.operando.operandoapp.OperandoProxyStatus.java
private void LoadPendingNotificationsTab() { final String addAllowedSuccessful = "Added to Allowed Domains Successfully", addAllowedUnsuccessfull = "This domain already exists in your allowed domain list", addBlockedSuccessfull = "Added to Blocked Domains Successfully", addBlockedUnsuccessfull = "This domain already exists in your blocked domain list"; try {//from ww w . j a v a 2 s .co m for (final PendingNotification pending_notification : new DatabaseHelper(this) .getAllPendingNotifications()) { String info = pending_notification.app_info + " || " + pending_notification.permission + " || " + pending_notification.id; Button b = new Button(this); b.setText(info); b.setLayoutParams(new LinearLayout.LayoutParams(android.app.ActionBar.LayoutParams.MATCH_PARENT, android.app.ActionBar.LayoutParams.WRAP_CONTENT)); ((TableLayout) ((LinearLayout) ((ScrollView) findViewById(R.id.PendingNotificationsScrollView)) .getChildAt(0)).getChildAt(1)).addView(b); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { final int notificationId = Integer .parseInt(((Button) v).getText().toString().split(" \\|\\| ")[2]); new AlertDialog.Builder(MainActivity.this).setIcon(R.drawable.logo_bevel) .setTitle("Manage Application Permission") .setMessage("What do you want to do with this specific application permission?") .setPositiveButton("ALLOW", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { DatabaseHelper db = new DatabaseHelper(MainActivity.this); boolean add = true; for (String permission : pending_notification.permission .split("\\, ")) { add = add && db.addAllowedDomain(pending_notification.app_info, permission); } boolean remove = db.removePendingNotification(notificationId); ((NotificationManager) MainActivity.this .getSystemService(Context.NOTIFICATION_SERVICE)) .cancel(notificationId); Toast.makeText(MainActivity.this, add && remove ? addAllowedSuccessful : addAllowedUnsuccessfull, Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show(); } ((TableLayout) ((LinearLayout) ((ScrollView) findViewById( R.id.PendingNotificationsScrollView)).getChildAt(0)) .getChildAt(1)).removeAllViews(); LoadPendingNotificationsTab(); new DatabaseHelper(MainActivity.this).sendSettingsToServer( new RequestFilterUtil(MainActivity.this).getIMEI()); } }).setNegativeButton("BLOCK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { DatabaseHelper db = new DatabaseHelper(MainActivity.this); boolean add = true; for (String permission : pending_notification.permission .split("\\, ")) { add = add && db.addBlockedDomain(pending_notification.app_info, permission); } boolean remove = db.removePendingNotification(notificationId); ((NotificationManager) MainActivity.this .getSystemService(Context.NOTIFICATION_SERVICE)) .cancel(notificationId); Toast.makeText(MainActivity.this, add && remove ? addBlockedSuccessfull : addBlockedUnsuccessfull, Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show(); } ((TableLayout) ((LinearLayout) ((ScrollView) findViewById( R.id.PendingNotificationsScrollView)).getChildAt(0)) .getChildAt(1)).removeAllViews(); LoadPendingNotificationsTab(); new DatabaseHelper(MainActivity.this).sendSettingsToServer( new RequestFilterUtil(MainActivity.this).getIMEI()); } }).setNeutralButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //nothing } }).show(); } catch (Exception e) { Log.d("ERROR", e.getMessage()); } } }); } } catch (Exception e) { Log.d("ERROR", e.getMessage()); } }
From source file:com.cybrosys.scientific.EventListener.java
@SuppressWarnings("deprecation") public void showHistory() { shPref = ScientificActivity.ctx.getSharedPreferences("myHistpref", 0); int inSize = shPref.getInt("HistIndex", 0); System.out.println("" + inSize); String[] str = new String[inSize]; for (int inI = 0; inI < inSize; inI++) { str[inI] = shPref.getString("hist" + inI, ""); System.out.println(str[inI]); }/*from www.j av a 2 s. c om*/ LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); vwLayout = inflater.inflate(R.layout.pop_history, (ViewGroup) ((Activity) ctx).findViewById(R.id.popup_element)); popmW1 = new PopupWindow(vwLayout, PalmCalcActivity.inDispwidth, PalmCalcActivity.inDispheight, true); popmW1.setBackgroundDrawable(new BitmapDrawable()); popmW1.setOutsideTouchable(true); popmW1.showAtLocation(vwLayout, Gravity.CENTER, 0, 0); tblltTable = (TableLayout) vwLayout.findViewById(R.id.tablelay); ImageButton btnCancel = (ImageButton) vwLayout.findViewById(R.id.butcancelmain); btnCancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { popmW1.dismiss(); } }); txtvHistory = new TextView[inSize]; btnHistory = new Button[inSize]; tblrRowL = new TableRow[inSize]; TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 1f); TableRow.LayoutParams textParams = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT, .1f); int inJ = 0, inL = inSize - 1; for (int inI = 0; inI < inSize; inI++) { if (!str[inI].equalsIgnoreCase("")) { btnHistory[inJ] = new Button(ctx); txtvHistory[inJ] = new TextView(ctx); txtvHistory[inJ].setText("" + (inJ + 1)); txtvHistory[inJ].setGravity(Gravity.CENTER); txtvHistory[inJ].setTextColor(ScientificActivity.ctx.getResources().getColor(R.color.HistColor)); txtvHistory[inJ].setLayoutParams(textParams); btnHistory[inJ].setText(str[inL]); btnHistory[inJ].setTextColor(Color.WHITE); btnHistory[inJ].setGravity(Gravity.LEFT); btnHistory[inJ].setLayoutParams(buttonParams); btnHistory[inJ].setBackgroundDrawable(ctx.getResources().getDrawable(R.drawable.button_effect)); tblrRowL[inJ] = new TableRow(ctx); tblrRowL[inJ].addView(txtvHistory[inJ]); tblrRowL[inJ].addView(btnHistory[inJ]); tblltTable.addView(tblrRowL[inJ]); final int inK = inJ; btnHistory[inK].setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // etxt.setText(btns[inK].getText().toString()); mHandler.insert(btnHistory[inK].getText().toString()); popmW1.dismiss(); } }); inJ++; inL--; } } if (inSize == 0) { TextView txtvHistory = new TextView(ctx); txtvHistory.setLayoutParams(textParams); txtvHistory.setGravity(Gravity.CENTER); txtvHistory.setTextColor(Color.WHITE); txtvHistory.setText("History Empty"); TableRow tblrRowL = new TableRow(ctx); tblrRowL.addView(txtvHistory); tblltTable.addView(tblrRowL); } }
From source file:foam.starwisp.StarwispBuilder.java
public void Build(final StarwispActivity ctx, final String ctxname, JSONArray arr, ViewGroup parent) { if (StarwispLinearLayout.m_DisplayMetrics == null) { StarwispLinearLayout.m_DisplayMetrics = ctx.getResources().getDisplayMetrics(); }/*from ww w .ja va 2s. c o m*/ try { String type = arr.getString(0); //Log.i("starwisp","building started "+type); if (type.equals("build-fragment")) { String name = arr.getString(1); int ID = arr.getInt(2); Fragment fragment = ActivityManager.GetFragment(name); LinearLayout inner = new LinearLayout(ctx); inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3))); inner.setId(ID); FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction(); fragmentTransaction.add(ID, fragment); fragmentTransaction.commit(); parent.addView(inner); return; } if (type.equals("map")) { int ID = arr.getInt(1); LinearLayout inner = new LinearLayout(ctx); inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); inner.setId(ID); Fragment mapfrag = SupportMapFragment.newInstance(); FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction(); fragmentTransaction.add(ID, mapfrag); fragmentTransaction.commit(); parent.addView(inner); return; } if (type.equals("drawmap")) { final LinearLayout inner = new LinearLayout(ctx); inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); DrawableMap dm = new DrawableMap(); dm.init(arr.getInt(1), inner, (StarwispActivity) ctx, this, arr.getString(3)); parent.addView(inner); m_DMaps.put(arr.getInt(1), dm); return; } if (type.equals("linear-layout")) { StarwispLinearLayout.Build(this, ctx, ctxname, arr, parent); return; } if (type.equals("relative-layout")) { StarwispRelativeLayout.Build(this, ctx, ctxname, arr, parent); return; } if (type.equals("draggable")) { final LinearLayout v = new LinearLayout(ctx); final int id = arr.getInt(1); final String behaviour_type = arr.getString(5); v.setPadding(20, 20, 20, 10); v.setId(id); v.setOrientation(StarwispLinearLayout.BuildOrientation(arr.getString(2))); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3))); v.setClickable(true); v.setFocusable(true); JSONArray col = arr.getJSONArray(4); v.setBackgroundResource(R.drawable.draggable); GradientDrawable drawable = (GradientDrawable) v.getBackground(); final int colour = Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)); drawable.setColor(colour); /*LayerDrawable bgDrawable = (LayerDrawable)v.getBackground(); GradientDrawable bgShape = (GradientDrawable)bgDrawable.findDrawableByLayerId(R.id.draggableshape); bgShape.setColor(colour);*/ /*v.getBackground().setColorFilter(colour, PorterDuff.Mode.MULTIPLY);*/ parent.addView(v); JSONArray children = arr.getJSONArray(6); for (int i = 0; i < children.length(); i++) { Build(ctx, ctxname, new JSONArray(children.getString(i)), v); } // Sets a long click listener for the ImageView using an anonymous listener object that // implements the OnLongClickListener interface if (!behaviour_type.equals("drop-only") && !behaviour_type.equals("drop-only-consume")) { v.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View vv) { if (id != 99) { ClipData dragData = new ClipData( new ClipDescription("" + id, new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN }), new ClipData.Item("" + id)); View.DragShadowBuilder myShadow = new MyDragShadowBuilder(v); Log.i("starwisp", "start drag id " + vv.getId() + " " + v); v.startDrag(dragData, myShadow, v, 0); v.setVisibility(View.GONE); return true; } return false; } }); } if (!behaviour_type.equals("drag-only")) { // ye gads - needed as drag/drop doesn't deal with nested targets final StarwispBuilder that = this; v.setOnDragListener(new View.OnDragListener() { public boolean onDrag(View vv, DragEvent event) { //Log.i("starwisp","on drag event happened"); final int action = event.getAction(); switch (action) { case DragEvent.ACTION_DRAG_STARTED: //Log.i("starwisp","Drag started"+v ); if (event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) { // returns true to indicate that the View can accept the dragged data. return true; } else { // Returns false. During the current drag and drop operation, this View will // not receive events again until ACTION_DRAG_ENDED is sent. return false; } case DragEvent.ACTION_DRAG_ENTERED: { if (that.m_LastDragHighlighted != null) { that.m_LastDragHighlighted.getBackground().setColorFilter(null); } v.getBackground().setColorFilter(0x77777777, PorterDuff.Mode.MULTIPLY); that.m_LastDragHighlighted = v; //Log.i("starwisp","Drag entered"+v ); return true; } case DragEvent.ACTION_DRAG_LOCATION: { //View dragee = (View)event.getLocalState(); //dragee.setVisibility(View.VISIBLE); //Log.i("starwisp","Drag location"+v ); return true; } case DragEvent.ACTION_DRAG_EXITED: { //Log.i("starwisp","Drag exited "+v ); v.getBackground().setColorFilter(null); return true; } case DragEvent.ACTION_DROP: { v.getBackground().setColorFilter(null); //Log.i("starwisp","Drag dropped "+v ); View otherw = (View) event.getLocalState(); //Log.i("starwisp","removing from parent "+((View)otherw.getParent()).getId()); // check we are not adding to ourself if (id != otherw.getId()) { ((ViewManager) otherw.getParent()).removeView(otherw); //Log.i("starwisp","adding to " + id); if (!behaviour_type.equals("drop-only-consume")) { v.addView(otherw); } } otherw.setVisibility(View.VISIBLE); return true; } case DragEvent.ACTION_DRAG_ENDED: { //Log.i("starwisp","Drag ended "+v ); v.getBackground().setColorFilter(null); View dragee = (View) event.getLocalState(); dragee.setVisibility(View.VISIBLE); if (event.getResult()) { //Log.i("starwisp","sucess " ); } else { //Log.i("starwisp","fail " ); } ; return true; } // An unknown action type was received. default: //Log.e("starwisp","Unknown action type received by OnDragListener."); break; } ; return true; } }); return; } } if (type.equals("frame-layout")) { FrameLayout v = new FrameLayout(ctx); v.setId(arr.getInt(1)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); parent.addView(v); JSONArray children = arr.getJSONArray(3); for (int i = 0; i < children.length(); i++) { Build(ctx, ctxname, new JSONArray(children.getString(i)), v); } return; } /* if (type.equals("grid-layout")) { GridLayout v = new GridLayout(ctx); v.setId(arr.getInt(1)); v.setRowCount(arr.getInt(2)); //v.setColumnCount(arr.getInt(2)); v.setOrientation(BuildOrientation(arr.getString(3))); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4))); parent.addView(v); JSONArray children = arr.getJSONArray(5); for (int i=0; i<children.length(); i++) { Build(ctx,ctxname,new JSONArray(children.getString(i)), v); } return; } */ if (type.equals("scroll-view")) { HorizontalScrollView v = new HorizontalScrollView(ctx); v.setId(arr.getInt(1)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); parent.addView(v); JSONArray children = arr.getJSONArray(3); for (int i = 0; i < children.length(); i++) { Build(ctx, ctxname, new JSONArray(children.getString(i)), v); } return; } if (type.equals("scroll-view-vert")) { ScrollView v = new ScrollView(ctx); v.setId(arr.getInt(1)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); parent.addView(v); JSONArray children = arr.getJSONArray(3); for (int i = 0; i < children.length(); i++) { Build(ctx, ctxname, new JSONArray(children.getString(i)), v); } return; } if (type.equals("view-pager")) { ViewPager v = new ViewPager(ctx); v.setId(arr.getInt(1)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); v.setOffscreenPageLimit(3); final JSONArray items = arr.getJSONArray(3); v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) { @Override public int getCount() { return items.length(); } @Override public Fragment getItem(int position) { try { String fragname = items.getString(position); return ActivityManager.GetFragment(fragname); } catch (JSONException e) { Log.e("starwisp", "Error parsing fragment data " + e.toString()); } return null; } }); parent.addView(v); return; } if (type.equals("space")) { // Space v = new Space(ctx); (class not found runtime error??) TextView v = new TextView(ctx); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); parent.addView(v); } if (type.equals("image-view")) { ImageView v = new ImageView(ctx); v.setId(arr.getInt(1)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3))); v.setAdjustViewBounds(true); String image = arr.getString(2); if (image.startsWith("/")) { Bitmap b = BitmapCache.Load(image); if (b != null) { v.setImageBitmap(b); } } else { int id = ctx.getResources().getIdentifier(image, "drawable", ctx.getPackageName()); v.setImageResource(id); } parent.addView(v); } if (type.equals("image-button")) { ImageButton v = new ImageButton(ctx); v.setId(arr.getInt(1)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3))); String image = arr.getString(2); if (image.startsWith("/")) { v.setImageBitmap(BitmapCache.Load(image)); } else { int id = ctx.getResources().getIdentifier(image, "drawable", ctx.getPackageName()); v.setImageResource(id); } final String fn = arr.getString(4); v.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Callback(ctx, ctxname, v.getId()); } }); v.setAdjustViewBounds(true); v.setScaleType(ImageView.ScaleType.CENTER_INSIDE); parent.addView(v); } if (type.equals("text-view")) { TextView v = new TextView(ctx); v.setId(arr.getInt(1)); v.setText(Html.fromHtml(arr.getString(2)), BufferType.SPANNABLE); v.setTextSize(arr.getInt(3)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4))); v.setLinkTextColor(0xff00aa00); // uncomment all this to get hyperlinks to work in text... // should make this an option of course //v.setClickable(true); // make links //v.setMovementMethod(LinkMovementMethod.getInstance()); //v.setEnabled(true); // go to browser /*v.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View vv, MotionEvent event) { return false; } };*/ if (arr.length() > 5) { if (arr.getString(5).equals("left")) { v.setGravity(Gravity.LEFT); } else { if (arr.getString(5).equals("fill")) { v.setGravity(Gravity.FILL); } else { v.setGravity(Gravity.CENTER); } } } else { v.setGravity(Gravity.CENTER); } v.setTypeface(((StarwispActivity) ctx).m_Typeface); parent.addView(v); } if (type.equals("debug-text-view")) { TextView v = (TextView) ctx.getLayoutInflater().inflate(R.layout.debug_text, null); // v.setBackgroundResource(R.color.black); v.setId(arr.getInt(1)); // v.setText(Html.fromHtml(arr.getString(2))); // v.setTextColor(R.color.white); // v.setTextSize(arr.getInt(3)); // v.setMovementMethod(LinkMovementMethod.getInstance()); // v.setMaxLines(10); // v.setVerticalScrollBarEnabled(true); // v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4))); //v.setMovementMethod(new ScrollingMovementMethod()); /* if (arr.length()>5) { if (arr.getString(5).equals("left")) { v.setGravity(Gravity.LEFT); } else { if (arr.getString(5).equals("fill")) { v.setGravity(Gravity.FILL); } else { v.setGravity(Gravity.CENTER); } } } else { v.setGravity(Gravity.LEFT); } v.setTypeface(((StarwispActivity)ctx).m_Typeface);*/ parent.addView(v); } if (type.equals("web-view")) { WebView v = new WebView(ctx); v.setId(arr.getInt(1)); v.setVerticalScrollBarEnabled(false); v.loadData(arr.getString(2), "text/html", "utf-8"); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3))); parent.addView(v); } if (type.equals("edit-text")) { final EditText v = new EditText(ctx); v.setId(arr.getInt(1)); v.setText(arr.getString(2)); v.setTextSize(arr.getInt(3)); v.setGravity(Gravity.LEFT | Gravity.TOP); String inputtype = arr.getString(4); if (inputtype.equals("text")) { //v.setInputType(InputType.TYPE_CLASS_TEXT); } else if (inputtype.equals("numeric")) { v.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); } else if (inputtype.equals("email")) { v.setInputType(InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS); } v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(5))); v.setTypeface(((StarwispActivity) ctx).m_Typeface); final String fn = arr.getString(5); //v.setSingleLine(true); v.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { CallbackArgs(ctx, ctxname, v.getId(), "\"" + s.toString() + "\""); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); parent.addView(v); } if (type.equals("button")) { Button v = new Button(ctx); v.setId(arr.getInt(1)); v.setText(arr.getString(2)); v.setTextSize(arr.getInt(3)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4))); v.setTypeface(((StarwispActivity) ctx).m_Typeface); final String fn = arr.getString(5); v.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Callback(ctx, ctxname, v.getId()); } }); parent.addView(v); } if (type.equals("colour-button")) { Button v = new Button(ctx); v.setId(arr.getInt(1)); v.setText(arr.getString(2)); v.setTextSize(arr.getInt(3)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4))); v.setTypeface(((StarwispActivity) ctx).m_Typeface); JSONArray col = arr.getJSONArray(6); v.getBackground().setColorFilter( Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)), PorterDuff.Mode.MULTIPLY); final String fn = arr.getString(5); v.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Callback(ctx, ctxname, v.getId()); } }); parent.addView(v); } if (type.equals("toggle-button")) { ToggleButton v = new ToggleButton(ctx); if (arr.getString(5).equals("fancy")) { v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_fancy, null); } if (arr.getString(5).equals("yes")) { v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_yes, null); } if (arr.getString(5).equals("maybe")) { v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_maybe, null); } if (arr.getString(5).equals("no")) { v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_no, null); } v.setId(arr.getInt(1)); v.setText(arr.getString(2)); v.setTextSize(arr.getInt(3)); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4))); v.setTypeface(((StarwispActivity) ctx).m_Typeface); final String fn = arr.getString(6); v.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String arg = "#f"; if (((ToggleButton) v).isChecked()) arg = "#t"; CallbackArgs(ctx, ctxname, v.getId(), arg); } }); parent.addView(v); } if (type.equals("seek-bar")) { SeekBar v = new SeekBar(ctx); v.setId(arr.getInt(1)); v.setMax(arr.getInt(2)); v.setProgress(arr.getInt(2) / 2); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3))); final String fn = arr.getString(4); v.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onProgressChanged(SeekBar v, int a, boolean s) { CallbackArgs(ctx, ctxname, v.getId(), Integer.toString(a)); } public void onStartTrackingTouch(SeekBar v) { } public void onStopTrackingTouch(SeekBar v) { } }); parent.addView(v); } if (type.equals("spinner")) { Spinner v = new Spinner(ctx); final int wid = arr.getInt(1); v.setId(wid); final JSONArray items = arr.getJSONArray(2); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3))); v.setMinimumWidth(100); // stops tiny buttons ArrayList<String> spinnerArray = new ArrayList<String>(); for (int i = 0; i < items.length(); i++) { spinnerArray.add(items.getString(i)); } ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx, R.layout.spinner_item, spinnerArray) { public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface); return v; } }; spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_layout); v.setAdapter(spinnerArrayAdapter); v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> a, View v, int pos, long id) { CallbackArgs(ctx, ctxname, wid, "" + pos); } public void onNothingSelected(AdapterView<?> v) { } }); parent.addView(v); } if (type.equals("nomadic")) { final int wid = arr.getInt(1); NomadicSurfaceView v = new NomadicSurfaceView(ctx, wid); v.setId(wid); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); Log.e("starwisp", "built the thing"); parent.addView(v); Log.e("starwisp", "addit to the view"); } if (type.equals("canvas")) { StarwispCanvas v = new StarwispCanvas(ctx); final int wid = arr.getInt(1); v.setId(wid); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); v.SetDrawList(arr.getJSONArray(3)); parent.addView(v); } if (type.equals("camera-preview")) { PictureTaker pt = new PictureTaker(); CameraPreview v = new CameraPreview(ctx, pt); final int wid = arr.getInt(1); v.setId(wid); v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2))); parent.addView(v); Log.i("starwisp", "in camera-preview..."); List<List<String>> info = v.mPictureTaker.GetInfo(); // can't find a way to do this via a callback yet String arg = "'("; for (List<String> e : info) { arg += "(" + e.get(0) + " " + e.get(1) + ")"; //Log.i("starwisp","converting prop "+arg); } arg += ")"; m_Scheme.eval("(set! camera-properties " + arg + ")"); } if (type.equals("button-grid")) { LinearLayout horiz = new LinearLayout(ctx); final int id = arr.getInt(1); final String buttontype = arr.getString(2); horiz.setId(id); horiz.setOrientation(LinearLayout.HORIZONTAL); parent.addView(horiz); int height = arr.getInt(3); int textsize = arr.getInt(4); LayoutParams lp = BuildLayoutParams(arr.getJSONArray(5)); JSONArray buttons = arr.getJSONArray(6); int count = buttons.length(); int vertcount = 0; LinearLayout vert = null; for (int i = 0; i < count; i++) { JSONArray button = buttons.getJSONArray(i); if (vertcount == 0) { vert = new LinearLayout(ctx); vert.setId(0); vert.setOrientation(LinearLayout.VERTICAL); horiz.addView(vert); } vertcount = (vertcount + 1) % height; if (buttontype.equals("button")) { Button b = new Button(ctx); b.setId(button.getInt(0)); b.setText(button.getString(1)); b.setTextSize(textsize); b.setLayoutParams(lp); b.setTypeface(((StarwispActivity) ctx).m_Typeface); final String fn = arr.getString(6); b.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t"); } }); vert.addView(b); } else if (buttontype.equals("toggle")) { ToggleButton b = new ToggleButton(ctx); b.setId(button.getInt(0)); b.setText(button.getString(1)); b.setTextSize(textsize); b.setLayoutParams(lp); b.setTypeface(((StarwispActivity) ctx).m_Typeface); final String fn = arr.getString(6); b.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String arg = "#f"; if (((ToggleButton) v).isChecked()) arg = "#t"; CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg); } }); vert.addView(b); } } } } catch (JSONException e) { Log.e("starwisp", "Error parsing [" + arr.toString() + "] " + e.toString()); } //Log.i("starwisp","building ended"); }
From source file:terse.a1.TerseActivity.java
void SetContentViewWithHomeButtonAndScroll(View v) { Button btn = new Button(this); btn.setText("[HOME]"); // btn.setTextSize(15); // btn.setHeight(25); // btn.setMaxHeight(25); btn.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on clicks startTerseActivity("/Top", ""); };/*from w w w .j av a 2s . co m*/ }); LinearLayout linear = new LinearLayout(this); linear.setOrientation(LinearLayout.VERTICAL); linear.addView(btn); linear.addView(v); ScrollView scrollv = new ScrollView(this); scrollv.addView(linear); setContentView(scrollv); }
From source file:com.cybrosys.scientific.EventListener.java
@SuppressWarnings("deprecation") @SuppressLint("NewApi") @Override/* www . j a v a2 s.c o m*/ public void onClick(View vwView) { vibrate(); ctx = PalmCalcActivity.ctx; int id = vwView.getId(); ScientificActivity.txtvShift.setText(""); switch (id) { case R.id.buttonDel: mHandler.onDelete(); break; case R.id.button3: if (inShift == 0) mHandler.insert("3"); else { mHandler.insert(","); inShift = 0; } break; case R.id.buttonDot: if (inShift == 0) mHandler.insert("."); else { showD(); inShift = 0; } break; case R.id.buttonAC: mHandler.onClear(); break; case R.id.ButtonEqual: String strDisplayEq = mHandler.getDisplayText(); if (!strDisplayEq.equalsIgnoreCase("")) mHandler.onEnter(); break; case R.id.ButtonAns: if (inShift == 0) mHandler.onShow(); else { showHistory(); inShift = 0; } break; case R.id.buttonDeg: mHandler.onDegChange(); break; case R.id.buttonAlt: if (inShift == 0) { String[] strMode = new String[] { "Floatpt", "FIX", "SCI" }; int inSizeM = 3; LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); vwLayout = inflater.inflate(R.layout.pop_history, (ViewGroup) ((Activity) ctx).findViewById(R.id.popup_element)); TextView txtvHeaderPop = (TextView) vwLayout.findViewById(R.id.txtvHeaderPop); txtvHeaderPop.setText("MODE"); popmW1 = new PopupWindow(vwLayout, PalmCalcActivity.inDispwidth, PalmCalcActivity.inDispheight, true); popmW1.setBackgroundDrawable(new BitmapDrawable()); popmW1.setOutsideTouchable(true); popmW1.showAtLocation(vwLayout, Gravity.CENTER, 0, 0); tblltTable = (TableLayout) vwLayout.findViewById(R.id.tablelay); ImageButton btnCancel = (ImageButton) vwLayout.findViewById(R.id.butcancelmain); btnCancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { popmW1.dismiss(); } }); txtvHistory = new TextView[inSizeM]; btnHistory = new Button[inSizeM]; tblrRowL = new TableRow[inSizeM]; TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 1f); TableRow.LayoutParams textParams = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT, .1f); int inJ = 0; for (int inI = 0; inI < inSizeM; inI++) { btnHistory[inJ] = new Button(ctx); txtvHistory[inJ] = new TextView(ctx); txtvHistory[inJ].setText("" + (inJ + 1)); txtvHistory[inJ].setLayoutParams(textParams); btnHistory[inJ].setText(strMode[inI]); txtvHistory[inJ].setGravity(Gravity.CENTER); txtvHistory[inJ] .setTextColor(ScientificActivity.ctx.getResources().getColor(R.color.HistColor)); btnHistory[inJ].setTextColor(Color.WHITE); btnHistory[inJ].setGravity(Gravity.LEFT); btnHistory[inJ].setLayoutParams(buttonParams); btnHistory[inJ].setBackgroundDrawable(ctx.getResources().getDrawable(R.drawable.button_effect)); tblrRowL[inJ] = new TableRow(ctx); tblrRowL[inJ].addView(txtvHistory[inJ]); tblrRowL[inJ].addView(btnHistory[inJ]); tblltTable.addView(tblrRowL[inJ]); final int inK = inJ; btnHistory[inK].setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // etxt.setText(btns[inK].getText().toString()); ScientificActivity.txtvFSE.setText(btnHistory[inK].getText().toString()); popmW1.dismiss(); } }); inJ++; } } else { setFSE(); inShift = 0; } mHandler.onFSEChange(); break; case R.id.buttonShift: if (inShift == 0) { inShift = 1; mHandler.onShiftPress(); } else inShift = 0; break; case R.id.buttonHyp: if (inHyp == 0) { inHyp = 1; mHandler.onHypPress(); } else { inHyp = 0; ScientificActivity.txtvHyp.setText(""); } break; case R.id.buttonMS: mHandler.onEnter(); String strDisplay = mHandler.getDisplayText(); if (inShift == 0) { if (isValidNumber(strDisplay)) { PreferenceClass.setMyStringPref(ctx, strDisplay); Toast.makeText(ctx, "Memory Saved!", Toast.LENGTH_SHORT).show(); mHandler.onClear(); } else Toast.makeText(ctx, "Save Failed!", Toast.LENGTH_SHORT).show(); } else { Memstore(); } break; case R.id.buttonMR: if (inShift == 0) { String strPref = PreferenceClass.getMyStringPref(ctx); if (!strPref.equalsIgnoreCase("")) { mHandler.insert(strPref); } else Toast.makeText(ctx, "Empty", Toast.LENGTH_SHORT).show(); } else { Memread(); inShift = 0; } break; case R.id.buttonMp: mHandler.onEnter(); String strDisplay2 = mHandler.getDisplayText(); if (isValidNumber(strDisplay2)) { String strPref2 = PreferenceClass.getMyStringPref(ctx); if (!strPref2.equalsIgnoreCase("")) { if (inShift == 0) { try { PreferenceClass.setMyStringPref(ctx, "" + mSymbols.eval(strPref2 + "+" + strDisplay2)); mHandler.onClear(); } catch (SyntaxException e) { e.printStackTrace(); } Toast.makeText(ctx, "Value added", Toast.LENGTH_SHORT).show(); } else { Memplus(); inShift = 0; } } } break; default: if (vwView instanceof Button) { String strText = ((Button) vwView).getTag().toString(); if (strText.contains(",")) { int inInComa = strText.lastIndexOf(","); if (inShift == 1) { strText = strText.substring(inInComa + 1, strText.length()); inShift = 0; } else { strText = strText.substring(0, inInComa); } } if (inHyp == 1) { if (strText.contains("sin(")) { strText = strText.replace("sin(", "sinh("); } if (strText.contains("cos(")) { strText = strText.replace("cos(", "cosh("); } if (strText.contains("tan(")) { strText = strText.replace("tan(", "tanh("); } ScientificActivity.txtvHyp.setText(""); inHyp = 0; } mHandler.insert(strText); } } }
From source file:com.citrus.sample.WalletPaymentFragment.java
void showTokenizedPrompt() { final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); final String message = "Auto Load Money with Saved Card"; String positiveButtonText = "Auto Load"; LinearLayout linearLayout = new LinearLayout(getActivity()); linearLayout.setOrientation(LinearLayout.VERTICAL); final TextView labelamt = new TextView(getActivity()); final EditText editAmount = new EditText(getActivity()); final TextView labelAmount = new TextView(getActivity()); final EditText editLoadAmount = new EditText(getActivity()); final TextView labelMobileNo = new TextView(getActivity()); final EditText editThresholdAmount = new EditText(getActivity()); final Button btnSelectSavedCards = new Button(getActivity()); btnSelectSavedCards.setText("Select Saved Card"); editLoadAmount.setSingleLine(true);//from w w w . ja v a 2s . c o m editThresholdAmount.setSingleLine(true); editAmount.setSingleLine(true); labelamt.setText("Load Amount"); labelAmount.setText("Auto Load Amount"); labelMobileNo.setText("Threshold Amount"); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); labelamt.setLayoutParams(layoutParams); editAmount.setLayoutParams(layoutParams); labelAmount.setLayoutParams(layoutParams); labelMobileNo.setLayoutParams(layoutParams); editLoadAmount.setLayoutParams(layoutParams); editThresholdAmount.setLayoutParams(layoutParams); btnSelectSavedCards.setLayoutParams(layoutParams); btnSelectSavedCards.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCitrusClient.getWallet(new Callback<List<PaymentOption>>() { @Override public void success(List<PaymentOption> paymentOptions) { walletList.clear(); for (PaymentOption paymentOption : paymentOptions) { if (paymentOption instanceof CreditCardOption) { if (Arrays.asList(AUTO_LOAD_CARD_SCHEMS) .contains(((CardOption) paymentOption).getCardScheme().toString())) walletList.add(paymentOption); //only available for Master and Visa Credit Card.... } } savedOptionsAdapter = new SavedOptionsAdapter(getActivity(), walletList); showSavedAccountsDialog(); } @Override public void error(CitrusError error) { Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); } }); linearLayout.addView(labelamt); linearLayout.addView(editAmount); linearLayout.addView(labelAmount); linearLayout.addView(editLoadAmount); linearLayout.addView(labelMobileNo); linearLayout.addView(editThresholdAmount); linearLayout.addView(btnSelectSavedCards); int paddingPx = Utils.getSizeInPx(getActivity(), 32); linearLayout.setPadding(paddingPx, paddingPx, paddingPx, paddingPx); editLoadAmount.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); editThresholdAmount.setInputType(InputType.TYPE_CLASS_NUMBER); alert.setTitle("Auto Load Money with Saved Card"); alert.setMessage(message); alert.setView(linearLayout); alert.setPositiveButton(positiveButtonText, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final String amount = editAmount.getText().toString(); final String loadAmount = editLoadAmount.getText().toString(); final String thresHoldAmount = editThresholdAmount.getText().toString(); // Hide the keyboard. InputMethodManager imm = (InputMethodManager) getActivity() .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editAmount.getWindowToken(), 0); if (TextUtils.isEmpty(amount)) { Toast.makeText(getActivity(), "Amount cant be blank", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(loadAmount)) { Toast.makeText(getActivity(), "Load Amount cant be blank", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(thresHoldAmount)) { Toast.makeText(getActivity(), "thresHoldAmount cant be blank", Toast.LENGTH_SHORT).show(); return; } if (Double.valueOf(thresHoldAmount) < new Double("500")) { Toast.makeText(getActivity(), "thresHoldAmount should not be less than 500", Toast.LENGTH_SHORT).show(); return; } if (Double.valueOf(loadAmount) < new Double(thresHoldAmount)) { Toast.makeText(getActivity(), "Load Amount should not be less than thresHoldAmount", Toast.LENGTH_SHORT).show(); return; } if (otherPaymentOption == null) { Toast.makeText(getActivity(), "Saved Card Option is null.", Toast.LENGTH_SHORT).show(); } try { PaymentType paymentType = new PaymentType.LoadMoney(new Amount(amount), otherPaymentOption); mCitrusClient.autoLoadMoney((PaymentType.LoadMoney) paymentType, new Amount(thresHoldAmount), new Amount(loadAmount), new Callback<SubscriptionResponse>() { @Override public void success(SubscriptionResponse subscriptionResponse) { Logger.d("AUTO LOAD RESPONSE ***" + subscriptionResponse.getSubscriptionResponseMessage()); Toast.makeText(getActivity(), subscriptionResponse.getSubscriptionResponseMessage(), Toast.LENGTH_SHORT).show(); } @Override public void error(CitrusError error) { Logger.d("AUTO LOAD ERROR ***" + error.getMessage()); Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); } catch (CitrusException e) { e.printStackTrace(); } } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); editLoadAmount.requestFocus(); alert.show(); }