List of usage examples for android.webkit WebView loadUrl
public void loadUrl(String url)
From source file:com.dtworkshop.inappcrossbrowser.WebViewBrowser.java
/** * Closes the dialog/*from w ww.j a va 2s .c o m*/ */ public void closeDialog() { final WebView childView = this.inAppWebView; // The JS protects against multiple calls, so this should happen only when // closeDialog() is called by other native code. if (childView == null) { return; } this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { childView.setWebViewClient(new WebViewClient() { // NB: wait for about:blank before dismissing public void onPageFinished(WebView view, String url) { if (dialog != null) { dialog.dismiss(); } } }); // NB: From SDK 19: "If you call methods on WebView from any thread // other than your app's UI thread, it can cause unexpected results." // http://developer.android.com/guide/webapps/migrating.html#Threads childView.loadUrl("about:blank"); } }); try { JSONObject obj = new JSONObject(); obj.put("type", EXIT_EVENT); sendUpdate(obj, false); } catch (JSONException ex) { Log.d(LOG_TAG, "Should never happen"); } }
From source file:jp.mixi.android.sdk.MixiContainerImpl.java
@Override public void setupAd(Activity activity, AdParameter param) { WebView view = (WebView) activity.findViewById(R.id.webview); // view ?????????? if (view == null) { Log.w(TAG, "webview not found."); return;//from w w w. j av a 2s . c om } view.setWebViewClient(new MapWebViewClient(activity)); if (param == null || param.headerPath == null) { Log.w(TAG, "path is null."); return; } view.loadUrl(param.headerPath); // ????? if (mSelector == Config.APPLICATION) { setupAppCounter(); } }
From source file:com.anjalimacwan.fragment.NoteViewFragment.java
@SuppressLint("SetJavaScriptEnabled") @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override/*from ww w.j a va 2s . c om*/ public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Set values setRetainInstance(true); setHasOptionsMenu(true); // Get filename of saved note filename = getArguments().getString("filename"); // Change window title String title; try { title = listener.loadNoteTitle(filename); } catch (IOException e) { title = getResources().getString(R.string.view_note); } getActivity().setTitle(title); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(title, null, ContextCompat.getColor(getActivity(), R.color.primary)); getActivity().setTaskDescription(taskDescription); } // Show the Up button in the action bar. ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Animate elevation change if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-large") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { LinearLayout noteViewEdit = (LinearLayout) getActivity().findViewById(R.id.noteViewEdit); LinearLayout noteList = (LinearLayout) getActivity().findViewById(R.id.noteList); noteList.animate().z(0f); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) noteViewEdit.animate() .z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation_land)); else noteViewEdit.animate().z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation)); } // Set up content view TextView noteContents = (TextView) getActivity().findViewById(R.id.textView); markdownView = (MarkdownView) getActivity().findViewById(R.id.markdownView); // Apply theme SharedPreferences pref = getActivity().getSharedPreferences(getActivity().getPackageName() + "_preferences", Context.MODE_PRIVATE); ScrollView scrollView = (ScrollView) getActivity().findViewById(R.id.scrollView); String theme = pref.getString("theme", "light-sans"); int textSize = -1; int textColor = -1; String fontFamily = null; if (theme.contains("light")) { if (noteContents != null) { noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary)); noteContents.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background)); } if (markdownView != null) { markdownView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background)); textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary); } scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background)); } if (theme.contains("dark")) { if (noteContents != null) { noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark)); noteContents .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark)); } if (markdownView != null) { markdownView .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark)); textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark); } scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark)); } if (theme.contains("sans")) { if (noteContents != null) noteContents.setTypeface(Typeface.SANS_SERIF); if (markdownView != null) fontFamily = "sans-serif"; } if (theme.contains("serif")) { if (noteContents != null) noteContents.setTypeface(Typeface.SERIF); if (markdownView != null) fontFamily = "serif"; } if (theme.contains("monospace")) { if (noteContents != null) noteContents.setTypeface(Typeface.MONOSPACE); if (markdownView != null) fontFamily = "monospace"; } switch (pref.getString("font_size", "normal")) { case "smallest": textSize = 12; break; case "small": textSize = 14; break; case "normal": textSize = 16; break; case "large": textSize = 18; break; case "largest": textSize = 20; break; } if (noteContents != null) noteContents.setTextSize(textSize); if (markdownView != null) { String topBottom = " " + Float.toString(getResources().getDimension(R.dimen.padding_top_bottom) / getResources().getDisplayMetrics().density) + "px"; String leftRight = " " + Float.toString(getResources().getDimension(R.dimen.padding_left_right) / getResources().getDisplayMetrics().density) + "px"; String fontSize = " " + Integer.toString(textSize) + "px"; String fontColor = " #" + StringUtils.remove(Integer.toHexString(textColor), "ff"); final String css = "body { " + "margin:" + topBottom + topBottom + leftRight + leftRight + "; " + "font-family:" + fontFamily + "; " + "font-size:" + fontSize + "; " + "color:" + fontColor + "; " + "}"; final String js = "var styleNode = document.createElement('style');\n" + "styleNode.type = \"text/css\";\n" + "var styleText = document.createTextNode('" + css + "');\n" + "styleNode.appendChild(styleText);\n" + "document.getElementsByTagName('head')[0].appendChild(styleNode);\n"; markdownView.getSettings().setJavaScriptEnabled(true); markdownView.getSettings().setLoadsImagesAutomatically(false); markdownView.setWebViewClient(new WebViewClient() { @TargetApi(Build.VERSION_CODES.N) @Override public void onLoadResource(WebView view, String url) { view.stopLoading(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) try { startActivity(intent); } catch (ActivityNotFoundException | FileUriExposedException e) { /* Gracefully fail */ } else try { startActivity(intent); } catch (ActivityNotFoundException e) { /* Gracefully fail */ } } @Override public void onPageFinished(WebView view, String url) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) view.evaluateJavascript(js, null); else view.loadUrl("javascript:" + js); } }); } // Load note contents try { contentsOnLoad = listener.loadNote(filename); } catch (IOException e) { showToast(R.string.error_loading_note); // Add NoteListFragment or WelcomeFragment Fragment fragment; if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-normal")) fragment = new NoteListFragment(); else fragment = new WelcomeFragment(); getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteListFragment") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit(); } // Set TextView contents if (noteContents != null) noteContents.setText(contentsOnLoad); if (markdownView != null) markdownView.loadMarkdown(contentsOnLoad); // Show a toast message if this is the user's first time viewing a note final SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); firstLoad = sharedPref.getInt("first-load", 0); if (firstLoad == 0) { // Show dialog with info DialogFragment firstLoad = new FirstViewDialogFragment(); firstLoad.show(getFragmentManager(), "firstloadfragment"); // Set first-load preference to 1; we don't need to show the dialog anymore SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt("first-load", 1); editor.apply(); } // Detect single and double-taps using GestureDetector final GestureDetector detector = new GestureDetector(getActivity(), new GestureDetector.OnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } @Override public boolean onDown(MotionEvent e) { return false; } }); detector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() { @Override public boolean onDoubleTap(MotionEvent e) { if (sharedPref.getBoolean("show_double_tap_message", true)) { SharedPreferences.Editor editor = sharedPref.edit(); editor.putBoolean("show_double_tap_message", false); editor.apply(); } Bundle bundle = new Bundle(); bundle.putString("filename", filename); Fragment fragment = new NoteEditFragment(); fragment.setArguments(bundle); getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteEditFragment") .commit(); return false; } @Override public boolean onDoubleTapEvent(MotionEvent e) { return false; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { if (sharedPref.getBoolean("show_double_tap_message", true) && showMessage) { showToastLong(R.string.double_tap); showMessage = false; } return false; } }); if (noteContents != null) noteContents.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { detector.onTouchEvent(event); return false; } }); if (markdownView != null) markdownView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { detector.onTouchEvent(event); return false; } }); }
From source file:com.openatk.field_work.MainActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.main_menu_add) { // Check if have an operation if (operationsList.isEmpty()) { // Show dialog to create operation createOperation(new Callable<Void>() { public Void call() { //Do this after we create an operation return addFieldMapView(); }// w w w . j a va2 s. c o m }); } else { addFieldMapView(); } } else if (item.getItemId() == R.id.main_menu_current_location) { Location myLoc = map.getMyLocation(); if (myLoc == null) { Toast.makeText(this, "Still searching for your location", Toast.LENGTH_SHORT).show(); } else { CameraPosition oldPos = map.getCameraPosition(); CameraPosition newPos = new CameraPosition(new LatLng(myLoc.getLatitude(), myLoc.getLongitude()), map.getMaxZoomLevel() - 5.0f, oldPos.tilt, oldPos.bearing); map.animateCamera(CameraUpdateFactory.newCameraPosition(newPos)); } } else if (item.getItemId() == R.id.main_menu_layers) { MenuItem layers = menu.findItem(R.id.main_menu_layers); //TODO hazards /*if(showingHazards == false){ showingHazards = true; layers.setTitle("Hide Hazards"); } else { showingHazards = false; layers.setTitle("Show Hazards"); } SharedPreferences prefs = getApplicationContext().getSharedPreferences("com.openatk.field_work", Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("showingHazards",showingHazards); editor.commit(); drawHazards();*/ } else if (item.getItemId() == R.id.main_menu_sync) { this.syncHelper.sync(this); } else if (item.getItemId() == R.id.main_menu_list_view) { // Show list view Log.d("MainActivity", "Showing list view"); setState(STATE_LIST_VIEW); } else if (item.getItemId() == R.id.main_menu_map_view) { // Show map view Log.d("MainActivity", "Showing map view"); setState(STATE_DEFAULT); closeKeyboard(); } else if (item.getItemId() == R.id.main_menu_help) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Help"); WebView wv = new WebView(this); wv.loadUrl("file:///android_asset/Help.html"); wv.getSettings().setSupportZoom(true); wv.getSettings().setBuiltInZoomControls(true); /*wv.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } });*/ alert.setView(wv); alert.setNegativeButton("Close", null); alert.show(); } else if (item.getItemId() == R.id.main_menu_legal) { CharSequence licence = "The MIT License (MIT)\n" + "\n" + "Copyright (c) 2013 Purdue University\n" + "\n" + "Permission is hereby granted, free of charge, to any person obtaining a copy " + "of this software and associated documentation files (the \"Software\"), to deal " + "in the Software without restriction, including without limitation the rights " + "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell " + "copies of the Software, and to permit persons to whom the Software is " + "furnished to do so, subject to the following conditions:" + "\n" + "The above copyright notice and this permission notice shall be included in " + "all copies or substantial portions of the Software.\n" + "\n" + "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR " + "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, " + "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE " + "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER " + "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, " + "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN " + "THE SOFTWARE.\n"; new AlertDialog.Builder(this).setTitle("Legal").setMessage(licence) .setIcon(android.R.drawable.ic_dialog_alert).setPositiveButton("Close", null).show(); } else if (item.getItemId() == R.id.main_menu_autosync) { TrelloSyncInfo syncInfo = syncHelper.getSyncInfo(getApplicationContext()); int selected = -1; if (syncInfo != null) { if (syncInfo.getAutoSync() != null && syncInfo.getAutoSync() == false) { selected = 0; } else if (syncInfo.getInterval() != null) { Log.d("MainActivity", "syncInfo interval:" + syncInfo.getInterval()); if (syncInfo.getInterval() == 60) selected = 1; if (syncInfo.getInterval() == 60 * 5) selected = 2; if (syncInfo.getInterval() == 60 * 10) selected = 3; if (syncInfo.getInterval() == 60 * 30) selected = 4; } } String[] options = { "Never", "1 min", "5 min", "10 min", "30 min" }; new AlertDialog.Builder(this).setTitle("Autosync Interval") .setSingleChoiceItems(options, selected, new DialogInterface.OnClickListener() { Integer devAutoSyncOnTrigger = 0; public void onClick(DialogInterface dialog, int which) { if (which == 0) { syncHelper.autoSyncOff(getApplicationContext()); } else if (which == 1) { syncHelper.autoSyncOn(getApplicationContext(), 60); } else if (which == 2) { syncHelper.autoSyncOn(getApplicationContext(), 60 * 5); } else if (which == 3) { syncHelper.autoSyncOn(getApplicationContext(), 60 * 10); } else if (which == 4) { syncHelper.autoSyncOn(getApplicationContext(), 60 * 30); devAutoSyncOnTrigger++; if (devAutoSyncOnTrigger > 9) { if (devAutoSyncOnTrigger % 2 == 0) { syncHelper.devAutoSyncOn(getApplicationContext(), 3); Toast.makeText(getApplicationContext(), "Presentation auto sync on, every 3 seconds.", Toast.LENGTH_SHORT) .show(); } else { syncHelper.devAutoSyncOff(getApplicationContext()); Toast.makeText(getApplicationContext(), "Presentation auto sync off.", Toast.LENGTH_SHORT).show(); } } } } }).setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }).show(); } return true; }
From source file:org.esupportail.nfctagdroid.NfcTacDroidActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ESUP_NFC_TAG_SERVER_URL = getEsupNfcTagServerUrl(getApplicationContext()); //To keep session for desfire async requests CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); LocalStorage.getInstance(getApplicationContext()); Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getApplicationContext())); setContentView(R.layout.activity_main); mAdapter = NfcAdapter.getDefaultAdapter(this); checkHardware(mAdapter);//from w w w. j a v a 2s .co m localStorageDBHelper = LocalStorage.getInstance(this.getApplicationContext()); String numeroId = localStorageDBHelper.getValue("numeroId"); TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String imei = telephonyManager.getDeviceId(); url = ESUP_NFC_TAG_SERVER_URL + "/nfc-index?numeroId=" + numeroId + "&imei=" + imei + "&macAddress=" + getMacAddr() + "&apkVersion=" + getApkVersion(); view = (WebView) this.findViewById(R.id.webView); view.clearCache(true); view.addJavascriptInterface(new LocalStorageJavaScriptInterface(this.getApplicationContext()), "AndroidLocalStorage"); view.addJavascriptInterface(new AndroidJavaScriptInterface(this.getApplicationContext()), "Android"); view.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int progress) { if (progress == 100) { AUTH_TYPE = localStorageDBHelper.getValue("authType"); } } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { log.info("Webview console message : " + consoleMessage.message()); return false; } }); view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { view.reload(); return true; } }); view.getSettings().setAllowContentAccess(true); WebSettings webSettings = view.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setDomStorageEnabled(true); webSettings.setDatabaseEnabled(true); webSettings.setDatabasePath(this.getFilesDir().getParentFile().getPath() + "/databases/"); view.setDownloadListener(new DownloadListener() { public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }); view.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { } }); view.loadUrl(url); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); }
From source file:com.likemag.cordova.inappbrowsercustom.InAppBrowser.java
/** * Closes the dialog/*w w w . j a va 2 s .co m*/ */ public void closeDialog() { final WebView childView = this.inAppWebView; // The JS protects against multiple calls, so this should happen only when // closeDialog() is called by other native code. if (childView == null) { return; } this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { childView.setWebViewClient(new WebViewClient() { // NB: wait for about:blank before dismissing public void onPageFinished(WebView view, String url) { if (dialog != null) { dialog.dismiss(); } } }); // NB: From SDK 19: "If you call methods on WebView from any thread // other than your app's UI thread, it can cause unexpected results." // http://developer.android.com/guide/webapps/migrating.html#Threads childView.loadUrl("about:blank"); } }); try { JSONObject obj = new JSONObject(); obj.put("type", EXIT_EVENT); sendUpdate(obj, false); } catch (JSONException ex) { Log.d(LOG_TAG, "Should never happen"); } }
From source file:com.sonymobile.dronecontrol.activity.MainActivity.java
private void loadLicense() { View view = getLayoutInflater().inflate(R.layout.licenses, null); Dialog dialog = new AlertDialog.Builder(this).setPositiveButton(R.string.settings_button_ok, null) .setView(view).setTitle(getString(R.string.settings_item_licenses)).create(); final WebView webView = (WebView) view.findViewById(R.id.license_view); final ProgressBar webProgress = (ProgressBar) view.findViewById(R.id.license_progress); webProgress.setVisibility(View.VISIBLE); dialog.setOnDismissListener(new OnDismissListener() { @Override/* w w w.j a va2 s. c om*/ public void onDismiss(DialogInterface dialog) { webView.stopLoading(); } }); webView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onScaleChanged(WebView view, float oldScale, float newScale) { super.onScaleChanged(view, oldScale, newScale); webProgress.setVisibility(View.GONE); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); webProgress.setVisibility(View.GONE); } }); webView.loadUrl("file:///android_asset/licenses.html"); dialog.show(); }
From source file:com.openatk.planting.MainActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.main_menu_add) { // Check if have an operation if (operationsList.isEmpty()) { // Show dialog to create operation createOperation(new Callable<Void>() { public Void call() { return addFieldMapView(); }/* ww w .ja va 2 s .c o m*/ }); } else { addFieldMapView(); } } else if (item.getItemId() == R.id.main_menu_current_location) { Location myLoc = map.getMyLocation(); if (myLoc == null) { Toast.makeText(this, "Still searching for your location", Toast.LENGTH_SHORT).show(); } else { CameraPosition oldPos = map.getCameraPosition(); CameraPosition newPos = new CameraPosition(new LatLng(myLoc.getLatitude(), myLoc.getLongitude()), map.getMaxZoomLevel(), oldPos.tilt, oldPos.bearing); map.animateCamera(CameraUpdateFactory.newCameraPosition(newPos)); } } else if (item.getItemId() == R.id.main_menu_layers) { MenuItem layers = menu.findItem(R.id.main_menu_layers); if (showingHazards == false) { showingHazards = true; layers.setTitle("Hide Hazards"); } else { showingHazards = false; layers.setTitle("Show Hazards"); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("showingHazards", showingHazards); editor.commit(); drawHazards(); } else if (item.getItemId() == R.id.main_menu_list_view) { if (mCurrentState == STATE_LIST_VIEW) { // Show map view Log.d("MainActivity", "Showing map view"); setState(STATE_DEFAULT); //item.setIcon(R.drawable.list_view); this.invalidateOptionsMenu(); } else { // Show list view Log.d("MainActivity", "Showing list view"); setState(STATE_LIST_VIEW); //item.setIcon(R.drawable.map_view); this.invalidateOptionsMenu(); } } else if (item.getItemId() == R.id.main_menu_help) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Help"); WebView wv = new WebView(this); wv.loadUrl("file:///android_asset/Help.html"); wv.getSettings().setSupportZoom(true); wv.getSettings().setBuiltInZoomControls(true); wv.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); alert.setView(wv); alert.setNegativeButton("Close", null); alert.show(); } else if (item.getItemId() == R.id.main_menu_legal) { CharSequence licence = "The MIT License (MIT)\n" + "\n" + "Copyright (c) 2013 Purdue University\n" + "\n" + "Permission is hereby granted, free of charge, to any person obtaining a copy " + "of this software and associated documentation files (the \"Software\"), to deal " + "in the Software without restriction, including without limitation the rights " + "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell " + "copies of the Software, and to permit persons to whom the Software is " + "furnished to do so, subject to the following conditions:" + "\n" + "The above copyright notice and this permission notice shall be included in " + "all copies or substantial portions of the Software.\n" + "\n" + "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR " + "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, " + "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE " + "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER " + "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, " + "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN " + "THE SOFTWARE.\n"; new AlertDialog.Builder(this).setTitle("Legal").setMessage(licence) .setIcon(android.R.drawable.ic_dialog_alert).setPositiveButton("Close", null).show(); } return true; }
From source file:org.openhab.habdroid.ui.OpenHABWidgetAdapter.java
@SuppressWarnings("deprecation") @Override/* ww w.j ava 2 s . c o m*/ public View getView(int position, View convertView, ViewGroup parent) { /* TODO: This definitely needs some huge refactoring */ final RelativeLayout widgetView; TextView labelTextView; TextView valueTextView; int widgetLayout; String[] splitString; OpenHABWidget openHABWidget = getItem(position); int screenWidth = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay().getWidth(); switch (this.getItemViewType(position)) { case TYPE_FRAME: widgetLayout = R.layout.openhabwidgetlist_frameitem; break; case TYPE_GROUP: widgetLayout = R.layout.openhabwidgetlist_groupitem; break; case TYPE_SECTIONSWITCH: widgetLayout = R.layout.openhabwidgetlist_sectionswitchitem; break; case TYPE_SWITCH: widgetLayout = R.layout.openhabwidgetlist_switchitem; break; case TYPE_ROLLERSHUTTER: widgetLayout = R.layout.openhabwidgetlist_rollershutteritem; break; case TYPE_TEXT: widgetLayout = R.layout.openhabwidgetlist_textitem; break; case TYPE_SLIDER: widgetLayout = R.layout.openhabwidgetlist_slideritem; break; case TYPE_IMAGE: widgetLayout = R.layout.openhabwidgetlist_imageitem; break; case TYPE_SELECTION: widgetLayout = R.layout.openhabwidgetlist_selectionitem; break; case TYPE_SETPOINT: widgetLayout = R.layout.openhabwidgetlist_setpointitem; break; case TYPE_CHART: widgetLayout = R.layout.openhabwidgetlist_chartitem; break; case TYPE_VIDEO: widgetLayout = R.layout.openhabwidgetlist_videoitem; break; case TYPE_VIDEO_MJPEG: widgetLayout = R.layout.openhabwidgetlist_videomjpegitem; break; case TYPE_WEB: widgetLayout = R.layout.openhabwidgetlist_webitem; break; case TYPE_COLOR: widgetLayout = R.layout.openhabwidgetlist_coloritem; break; default: widgetLayout = R.layout.openhabwidgetlist_genericitem; break; } if (convertView == null) { widgetView = new RelativeLayout(getContext()); String inflater = Context.LAYOUT_INFLATER_SERVICE; LayoutInflater vi; vi = (LayoutInflater) getContext().getSystemService(inflater); vi.inflate(widgetLayout, widgetView, true); } else { widgetView = (RelativeLayout) convertView; } // Process the colour attributes Integer iconColor = openHABWidget.getIconColor(); Integer labelColor = openHABWidget.getLabelColor(); Integer valueColor = openHABWidget.getValueColor(); // Process widgets icon image MySmartImageView widgetImage = (MySmartImageView) widgetView.findViewById(R.id.widgetimage); // Some of widgets, for example Frame doesnt' have an icon, so... if (widgetImage != null) { if (openHABWidget.getIcon() != null) { // This is needed to escape possible spaces and everything according to rfc2396 String iconUrl = openHABBaseUrl + "images/" + Uri.encode(openHABWidget.getIcon() + ".png"); // Log.d(TAG, "Will try to load icon from " + iconUrl); // Now set image URL widgetImage.setImageUrl(iconUrl, R.drawable.blank_icon, openHABUsername, openHABPassword); if (iconColor != null) widgetImage.setColorFilter(iconColor); else widgetImage.clearColorFilter(); } } TextView defaultTextView = new TextView(widgetView.getContext()); // Get TextView for widget label and set it's color labelTextView = (TextView) widgetView.findViewById(R.id.widgetlabel); // Change label color only for non-frame widgets if (labelColor != null && labelTextView != null && this.getItemViewType(position) != TYPE_FRAME) { Log.d(TAG, String.format("Setting label color to %d", labelColor)); labelTextView.setTextColor(labelColor); } else if (labelTextView != null && this.getItemViewType(position) != TYPE_FRAME) labelTextView.setTextColor(defaultTextView.getTextColors().getDefaultColor()); // Get TextView for widget value and set it's color valueTextView = (TextView) widgetView.findViewById(R.id.widgetvalue); if (valueColor != null && valueTextView != null) { Log.d(TAG, String.format("Setting value color to %d", valueColor)); valueTextView.setTextColor(valueColor); } else if (valueTextView != null) valueTextView.setTextColor(defaultTextView.getTextColors().getDefaultColor()); defaultTextView = null; switch (getItemViewType(position)) { case TYPE_FRAME: if (labelTextView != null) { labelTextView.setText(openHABWidget.getLabel()); if (valueColor != null) labelTextView.setTextColor(valueColor); } widgetView.setClickable(false); if (openHABWidget.getLabel().length() > 0) { // hide empty frames widgetView.setVisibility(View.VISIBLE); labelTextView.setVisibility(View.VISIBLE); } else { widgetView.setVisibility(View.GONE); labelTextView.setVisibility(View.GONE); } break; case TYPE_GROUP: if (labelTextView != null && valueTextView != null) { splitString = openHABWidget.getLabel().split("\\[|\\]"); labelTextView.setText(splitString[0]); if (splitString.length > 1) { // We have some value valueTextView.setText(splitString[1]); } else { // This is needed to clean up cached TextViews valueTextView.setText(""); } } break; case TYPE_SECTIONSWITCH: splitString = openHABWidget.getLabel().split("\\[|\\]"); if (labelTextView != null) labelTextView.setText(splitString[0]); if (splitString.length > 1 && valueTextView != null) { // We have some value valueTextView.setText(splitString[1]); } else { // This is needed to clean up cached TextViews valueTextView.setText(""); } RadioGroup sectionSwitchRadioGroup = (RadioGroup) widgetView.findViewById(R.id.sectionswitchradiogroup); // As we create buttons in this radio in runtime, we need to remove all // exiting buttons first sectionSwitchRadioGroup.removeAllViews(); sectionSwitchRadioGroup.setTag(openHABWidget); Iterator<OpenHABWidgetMapping> sectionMappingIterator = openHABWidget.getMappings().iterator(); while (sectionMappingIterator.hasNext()) { OpenHABWidgetMapping widgetMapping = sectionMappingIterator.next(); SegmentedControlButton segmentedControlButton = (SegmentedControlButton) LayoutInflater .from(sectionSwitchRadioGroup.getContext()) .inflate(R.layout.openhabwidgetlist_sectionswitchitem_button, sectionSwitchRadioGroup, false); segmentedControlButton.setText(widgetMapping.getLabel()); segmentedControlButton.setTag(widgetMapping.getCommand()); if (openHABWidget.getItem() != null && widgetMapping.getCommand() != null) { if (widgetMapping.getCommand().equals(openHABWidget.getItem().getState())) { segmentedControlButton.setChecked(true); } else { segmentedControlButton.setChecked(false); } } else { segmentedControlButton.setChecked(false); } segmentedControlButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Log.i(TAG, "Button clicked"); RadioGroup group = (RadioGroup) view.getParent(); if (group.getTag() != null) { OpenHABWidget radioWidget = (OpenHABWidget) group.getTag(); SegmentedControlButton selectedButton = (SegmentedControlButton) view; if (selectedButton.getTag() != null) { sendItemCommand(radioWidget.getItem(), (String) selectedButton.getTag()); } } } }); sectionSwitchRadioGroup.addView(segmentedControlButton); } sectionSwitchRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup group, int checkedId) { OpenHABWidget radioWidget = (OpenHABWidget) group.getTag(); SegmentedControlButton selectedButton = (SegmentedControlButton) group.findViewById(checkedId); if (selectedButton != null) { Log.d(TAG, "Selected " + selectedButton.getText()); Log.d(TAG, "Command = " + (String) selectedButton.getTag()); // radioWidget.getItem().sendCommand((String)selectedButton.getTag()); sendItemCommand(radioWidget.getItem(), (String) selectedButton.getTag()); } } }); break; case TYPE_SWITCH: if (labelTextView != null) labelTextView.setText(openHABWidget.getLabel()); SwitchCompat switchSwitch = (SwitchCompat) widgetView.findViewById(R.id.switchswitch); if (openHABWidget.hasItem()) { if (openHABWidget.getItem().getStateAsBoolean()) { switchSwitch.setChecked(true); } else { switchSwitch.setChecked(false); } } switchSwitch.setTag(openHABWidget.getItem()); switchSwitch.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent motionEvent) { SwitchCompat switchSwitch = (SwitchCompat) v; OpenHABItem linkedItem = (OpenHABItem) switchSwitch.getTag(); if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) if (!switchSwitch.isChecked()) { sendItemCommand(linkedItem, "ON"); } else { sendItemCommand(linkedItem, "OFF"); } return false; } }); break; case TYPE_COLOR: if (labelTextView != null) labelTextView.setText(openHABWidget.getLabel()); ImageButton colorUpButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_up); ImageButton colorDownButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_down); ImageButton colorColorButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_color); colorUpButton.setTag(openHABWidget.getItem()); colorDownButton.setTag(openHABWidget.getItem()); colorColorButton.setTag(openHABWidget.getItem()); colorUpButton.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent motionEvent) { ImageButton colorButton = (ImageButton) v; OpenHABItem colorItem = (OpenHABItem) colorButton.getTag(); if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) sendItemCommand(colorItem, "ON"); return false; } }); colorDownButton.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent motionEvent) { ImageButton colorButton = (ImageButton) v; OpenHABItem colorItem = (OpenHABItem) colorButton.getTag(); if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) sendItemCommand(colorItem, "OFF"); return false; } }); colorColorButton.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent motionEvent) { ImageButton colorButton = (ImageButton) v; OpenHABItem colorItem = (OpenHABItem) colorButton.getTag(); if (colorItem != null) { if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) { Log.d(TAG, "Time to launch color picker!"); ColorPickerDialog colorDialog = new ColorPickerDialog(widgetView.getContext(), new OnColorChangedListener() { public void colorChanged(float[] hsv, View v) { Log.d(TAG, "New color HSV = " + hsv[0] + ", " + hsv[1] + ", " + hsv[2]); String newColor = String.valueOf(hsv[0]) + "," + String.valueOf(hsv[1] * 100) + "," + String.valueOf(hsv[2] * 100); OpenHABItem colorItem = (OpenHABItem) v.getTag(); sendItemCommand(colorItem, newColor); } }, colorItem.getStateAsHSV()); colorDialog.setTag(colorItem); colorDialog.show(); } } return false; } }); break; case TYPE_ROLLERSHUTTER: if (labelTextView != null) labelTextView.setText(openHABWidget.getLabel()); ImageButton rollershutterUpButton = (ImageButton) widgetView.findViewById(R.id.rollershutterbutton_up); ImageButton rollershutterStopButton = (ImageButton) widgetView .findViewById(R.id.rollershutterbutton_stop); ImageButton rollershutterDownButton = (ImageButton) widgetView .findViewById(R.id.rollershutterbutton_down); rollershutterUpButton.setTag(openHABWidget.getItem()); rollershutterStopButton.setTag(openHABWidget.getItem()); rollershutterDownButton.setTag(openHABWidget.getItem()); rollershutterUpButton.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent motionEvent) { ImageButton rollershutterButton = (ImageButton) v; OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag(); if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) sendItemCommand(rollershutterItem, "UP"); return false; } }); rollershutterStopButton.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent motionEvent) { ImageButton rollershutterButton = (ImageButton) v; OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag(); if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) sendItemCommand(rollershutterItem, "STOP"); return false; } }); rollershutterDownButton.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent motionEvent) { ImageButton rollershutterButton = (ImageButton) v; OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag(); if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) sendItemCommand(rollershutterItem, "DOWN"); return false; } }); break; case TYPE_TEXT: splitString = openHABWidget.getLabel().split("\\[|\\]"); if (labelTextView != null) if (splitString.length > 0) { labelTextView.setText(splitString[0]); } else { labelTextView.setText(openHABWidget.getLabel()); } if (valueTextView != null) if (splitString.length > 1) { // If value is not empty, show TextView valueTextView.setVisibility(View.VISIBLE); valueTextView.setText(splitString[1]); } else { // If value is empty, hide TextView to fix vertical alignment of label valueTextView.setVisibility(View.GONE); valueTextView.setText(""); } break; case TYPE_SLIDER: splitString = openHABWidget.getLabel().split("\\[|\\]"); if (labelTextView != null) labelTextView.setText(splitString[0]); SeekBar sliderSeekBar = (SeekBar) widgetView.findViewById(R.id.sliderseekbar); if (openHABWidget.hasItem()) { sliderSeekBar.setTag(openHABWidget.getItem()); sliderSeekBar.setProgress(openHABWidget.getItem().getStateAsFloat().intValue()); sliderSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } public void onStartTrackingTouch(SeekBar seekBar) { Log.d(TAG, "onStartTrackingTouch position = " + seekBar.getProgress()); } public void onStopTrackingTouch(SeekBar seekBar) { Log.d(TAG, "onStopTrackingTouch position = " + seekBar.getProgress()); OpenHABItem sliderItem = (OpenHABItem) seekBar.getTag(); // sliderItem.sendCommand(String.valueOf(seekBar.getProgress())); if (sliderItem != null && seekBar != null) sendItemCommand(sliderItem, String.valueOf(seekBar.getProgress())); } }); if (volumeUpWidget == null) { volumeUpWidget = sliderSeekBar; volumeDownWidget = sliderSeekBar; } } break; case TYPE_IMAGE: MySmartImageView imageImage = (MySmartImageView) widgetView.findViewById(R.id.imageimage); imageImage.setImageUrl(ensureAbsoluteURL(openHABBaseUrl, openHABWidget.getUrl()), false, openHABUsername, openHABPassword); // ViewGroup.LayoutParams imageLayoutParams = imageImage.getLayoutParams(); // float imageRatio = imageImage.getDrawable().getIntrinsicWidth()/imageImage.getDrawable().getIntrinsicHeight(); // imageLayoutParams.height = (int) (screenWidth/imageRatio); // imageImage.setLayoutParams(imageLayoutParams); if (openHABWidget.getRefresh() > 0) { imageImage.setRefreshRate(openHABWidget.getRefresh()); refreshImageList.add(imageImage); } break; case TYPE_CHART: MySmartImageView chartImage = (MySmartImageView) widgetView.findViewById(R.id.chartimage); //Always clear the drawable so no images from recycled views appear chartImage.setImageDrawable(null); OpenHABItem chartItem = openHABWidget.getItem(); Random random = new Random(); String chartUrl = ""; if (chartItem != null) { if (chartItem.getType().equals("GroupItem")) { chartUrl = openHABBaseUrl + "chart?groups=" + chartItem.getName() + "&period=" + openHABWidget.getPeriod() + "&random=" + String.valueOf(random.nextInt()); } else { chartUrl = openHABBaseUrl + "chart?items=" + chartItem.getName() + "&period=" + openHABWidget.getPeriod() + "&random=" + String.valueOf(random.nextInt()); } if (openHABWidget.getService() != null && openHABWidget.getService().length() > 0) { chartUrl += "&service=" + openHABWidget.getService(); } } Log.d(TAG, "Chart url = " + chartUrl); if (chartImage == null) Log.e(TAG, "chartImage == null !!!"); ViewGroup.LayoutParams chartLayoutParams = chartImage.getLayoutParams(); chartLayoutParams.height = (int) (screenWidth / 2); chartImage.setLayoutParams(chartLayoutParams); chartUrl += "&w=" + String.valueOf(screenWidth); chartUrl += "&h=" + String.valueOf(screenWidth / 2); chartImage.setImageUrl(chartUrl, false, openHABUsername, openHABPassword); // TODO: This is quite dirty fix to make charts look full screen width on all displays if (openHABWidget.getRefresh() > 0) { chartImage.setRefreshRate(openHABWidget.getRefresh()); refreshImageList.add(chartImage); } Log.d(TAG, "chart size = " + chartLayoutParams.width + " " + chartLayoutParams.height); break; case TYPE_VIDEO: VideoView videoVideo = (VideoView) widgetView.findViewById(R.id.videovideo); Log.d(TAG, "Opening video at " + openHABWidget.getUrl()); // TODO: This is quite dirty fix to make video look maximum available size on all screens WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); ViewGroup.LayoutParams videoLayoutParams = videoVideo.getLayoutParams(); videoLayoutParams.height = (int) (wm.getDefaultDisplay().getWidth() / 1.77); videoVideo.setLayoutParams(videoLayoutParams); // We don't have any event handler to know if the VideoView is on the screen // so we manage an array of all videos to stop them when user leaves the page if (!videoWidgetList.contains(videoVideo)) videoWidgetList.add(videoVideo); // Start video if (!videoVideo.isPlaying()) { videoVideo.setVideoURI(Uri.parse(openHABWidget.getUrl())); videoVideo.start(); } Log.d(TAG, "Video height is " + videoVideo.getHeight()); break; case TYPE_VIDEO_MJPEG: Log.d(TAG, "Video is mjpeg"); ImageView mjpegImage = (ImageView) widgetView.findViewById(R.id.mjpegimage); MjpegStreamer mjpegStreamer = new MjpegStreamer(openHABWidget.getUrl(), this.openHABUsername, this.openHABPassword, this.getContext()); mjpegStreamer.setTargetImageView(mjpegImage); mjpegStreamer.start(); if (!mjpegWidgetList.contains(mjpegStreamer)) mjpegWidgetList.add(mjpegStreamer); break; case TYPE_WEB: WebView webWeb = (WebView) widgetView.findViewById(R.id.webweb); if (openHABWidget.getHeight() > 0) { ViewGroup.LayoutParams webLayoutParams = webWeb.getLayoutParams(); webLayoutParams.height = openHABWidget.getHeight() * 80; webWeb.setLayoutParams(webLayoutParams); } webWeb.setWebViewClient( new AnchorWebViewClient(openHABWidget.getUrl(), this.openHABUsername, this.openHABPassword)); webWeb.getSettings().setJavaScriptEnabled(true); webWeb.loadUrl(openHABWidget.getUrl()); break; case TYPE_SELECTION: int spinnerSelectedIndex = -1; if (labelTextView != null) labelTextView.setText(openHABWidget.getLabel()); final Spinner selectionSpinner = (Spinner) widgetView.findViewById(R.id.selectionspinner); selectionSpinner.setOnItemSelectedListener(null); ArrayList<String> spinnerArray = new ArrayList<String>(); Iterator<OpenHABWidgetMapping> mappingIterator = openHABWidget.getMappings().iterator(); while (mappingIterator.hasNext()) { OpenHABWidgetMapping openHABWidgetMapping = mappingIterator.next(); spinnerArray.add(openHABWidgetMapping.getLabel()); if (openHABWidgetMapping.getCommand() != null && openHABWidget.getItem() != null) if (openHABWidgetMapping.getCommand().equals(openHABWidget.getItem().getState())) { spinnerSelectedIndex = spinnerArray.size() - 1; } } ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this.getContext(), android.R.layout.simple_spinner_item, spinnerArray); spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); selectionSpinner.setAdapter(spinnerAdapter); selectionSpinner.setTag(openHABWidget); if (spinnerSelectedIndex >= 0) { Log.d(TAG, "Setting spinner selected index to " + String.valueOf(spinnerSelectedIndex)); selectionSpinner.setSelection(spinnerSelectedIndex); } else { Log.d(TAG, "Not setting spinner selected index"); } selectionSpinner.post(new Runnable() { @Override public void run() { selectionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int index, long id) { Log.d(TAG, "Spinner item click on index " + index); Spinner spinner = (Spinner) parent; String selectedLabel = (String) spinner.getAdapter().getItem(index); Log.d(TAG, "Spinner onItemSelected selected label = " + selectedLabel); OpenHABWidget openHABWidget = (OpenHABWidget) parent.getTag(); if (openHABWidget != null) { Log.d(TAG, "Label selected = " + openHABWidget.getMapping(index).getLabel()); Iterator<OpenHABWidgetMapping> mappingIterator = openHABWidget.getMappings() .iterator(); while (mappingIterator.hasNext()) { OpenHABWidgetMapping openHABWidgetMapping = mappingIterator.next(); if (openHABWidgetMapping.getLabel().equals(selectedLabel)) { Log.d(TAG, "Spinner onItemSelected found match with " + openHABWidgetMapping.getCommand()); if (openHABWidget.getItem() != null && openHABWidget.getItem().getState() != null) { // Only send the command for selection of selected command will change the state if (!openHABWidget.getItem().getState() .equals(openHABWidgetMapping.getCommand())) { Log.d(TAG, "Spinner onItemSelected selected label command != current item state"); sendItemCommand(openHABWidget.getItem(), openHABWidgetMapping.getCommand()); } } else if (openHABWidget.getItem() != null && openHABWidget.getItem().getState() == null) { Log.d(TAG, "Spinner onItemSelected selected label command and state == null"); sendItemCommand(openHABWidget.getItem(), openHABWidgetMapping.getCommand()); } } } } // if (!openHABWidget.getItem().getState().equals(openHABWidget.getMapping(index).getCommand())) // sendItemCommand(openHABWidget.getItem(), // openHABWidget.getMapping(index).getCommand()); } public void onNothingSelected(AdapterView<?> arg0) { } }); } }); break; case TYPE_SETPOINT: splitString = openHABWidget.getLabel().split("\\[|\\]"); if (labelTextView != null) labelTextView.setText(splitString[0]); if (valueTextView != null) if (splitString.length > 1) { // If value is not empty, show TextView valueTextView.setVisibility(View.VISIBLE); valueTextView.setText(splitString[1]); } Button setPointMinusButton = (Button) widgetView.findViewById(R.id.setpointbutton_minus); Button setPointPlusButton = (Button) widgetView.findViewById(R.id.setpointbutton_plus); setPointMinusButton.setTag(openHABWidget); setPointPlusButton.setTag(openHABWidget); setPointMinusButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Log.d(TAG, "Minus"); OpenHABWidget setPointWidget = (OpenHABWidget) v.getTag(); float currentValue = setPointWidget.getItem().getStateAsFloat(); currentValue = currentValue - setPointWidget.getStep(); if (currentValue < setPointWidget.getMinValue()) currentValue = setPointWidget.getMinValue(); if (currentValue > setPointWidget.getMaxValue()) currentValue = setPointWidget.getMaxValue(); sendItemCommand(setPointWidget.getItem(), String.valueOf(currentValue)); } }); setPointPlusButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Log.d(TAG, "Plus"); OpenHABWidget setPointWidget = (OpenHABWidget) v.getTag(); float currentValue = setPointWidget.getItem().getStateAsFloat(); currentValue = currentValue + setPointWidget.getStep(); if (currentValue < setPointWidget.getMinValue()) currentValue = setPointWidget.getMinValue(); if (currentValue > setPointWidget.getMaxValue()) currentValue = setPointWidget.getMaxValue(); sendItemCommand(setPointWidget.getItem(), String.valueOf(currentValue)); } }); if (volumeUpWidget == null) { volumeUpWidget = setPointPlusButton; volumeDownWidget = setPointMinusButton; } break; default: if (labelTextView != null) labelTextView.setText(openHABWidget.getLabel()); break; } LinearLayout dividerLayout = (LinearLayout) widgetView.findViewById(R.id.listdivider); if (dividerLayout != null) { if (position < this.getCount() - 1) { if (this.getItemViewType(position + 1) == TYPE_FRAME) { dividerLayout.setVisibility(View.GONE); // hide dividers before frame widgets } else { dividerLayout.setVisibility(View.VISIBLE); // show dividers for all others } } else { // last widget in the list, hide divider dividerLayout.setVisibility(View.GONE); } } return widgetView; }
From source file:com.gmail.tylerfilla.axon.ui.activity.HelpFOSSViewerActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Inflate and set content view setContentView(R.layout.activity_help_foss_viewer); // Find stuff Toolbar appBar = (Toolbar) findViewById(R.id.activity_help_foss_viewer_app_bar); WebView browser = (WebView) findViewById(R.id.activity_help_foss_viewer_browser); // Configure app bar setSupportActionBar(appBar);// w w w . j av a 2s .com // Display up button in app bar getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Apply dark tint to navigation icon // noinspection ConstantConditions Drawable navigationIcon = DrawableCompat.wrap(appBar.getNavigationIcon()); DrawableCompat.setTint(navigationIcon, 0x8b000000); appBar.setNavigationIcon(navigationIcon); // Get component index which was passed in int componentIndex = getIntent().getIntExtra("componentIndex", -1); if (componentIndex != -1) { // Component information String componentName = ""; String licenseName = ""; String licenseTextURL = ""; try { // Read components file into a buffer StringWriter componentFileBuffer = new StringWriter(); IOUtils.copy(getAssets().open("foss/components.json"), componentFileBuffer, Charset.defaultCharset()); // Parse component object from file JSONObject component = ((JSONArray) new JSONTokener(componentFileBuffer.toString()).nextValue()) .getJSONObject(componentIndex); // Extract component information from its JSON object componentName = component.getString("name"); licenseName = component.getString("licenseName"); licenseTextURL = component.getString("licenseTextURL"); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } // Set title and subtitle setTitle(componentName); appBar.setSubtitle(licenseName); // Load license URL browser.loadUrl(licenseTextURL); } }