List of usage examples for android.app AlertDialog setCanceledOnTouchOutside
public void setCanceledOnTouchOutside(boolean cancel)
From source file:com.mobiletin.inputmethod.indic.LatinIME.java
private void showSubtypeSelectorAndSettings() { final CharSequence title = getString(R.string.english_ime_input_options); // TODO: Should use new string "Select active input modes". final CharSequence languageSelectionTitle = getString(R.string.language_selection_title); final CharSequence[] items = new CharSequence[] { languageSelectionTitle, getString(ApplicationUtils.getActivityTitleResId(this, SettingsActivity.class)) }; final OnClickListener listener = new OnClickListener() { @Override/*from w w w . j a v a 2 s . co m*/ public void onClick(DialogInterface di, int position) { di.dismiss(); switch (position) { case 0: final Intent intent = IntentUtils.getInputLanguageSelectionIntent( mRichImm.getInputMethodIdOfThisIme(), Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(Intent.EXTRA_TITLE, languageSelectionTitle); startActivity(intent); break; case 1: launchSettings(); break; } } }; final AlertDialog.Builder builder = new AlertDialog.Builder( DialogUtils.getPlatformDialogThemeContext(this)); builder.setItems(items, listener).setTitle(title); final AlertDialog dialog = builder.create(); dialog.setCancelable(true /* cancelable */); dialog.setCanceledOnTouchOutside(true /* cancelable */); showOptionDialog(dialog); }
From source file:no.barentswatch.fiskinfo.BaseActivity.java
public void createConfirmLogoutDialog(Context activityContext, int rPathToTitleOfPopup, int rPathToTextInTheBodyOfThePopup) { AlertDialog.Builder builder = new AlertDialog.Builder(activityContext); AlertDialog dialog; builder.setTitle(rPathToTitleOfPopup); builder.setMessage(rPathToTextInTheBodyOfThePopup); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override// w ww . ja va 2 s .c o m public void onClick(DialogInterface dialog, int which) { invalidateAuthenticationData(); dialog.dismiss(); loadView(MainActivity.class); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = builder.create(); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { actionBar.setSelectedNavigationItem(adapter.getCount()); } }); dialog.show(); dialog.setCanceledOnTouchOutside(false); TextView messageView = (TextView) dialog.findViewById(android.R.id.message); messageView.setGravity(Gravity.CENTER); }
From source file:com.cypress.cysmart.CommonFragments.ProfileScanningFragment.java
public void showWarningMessage() { AlertDialog alert; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(getActivity().getResources().getString(R.string.alert_message_clear_cache)) .setTitle(getActivity().getResources().getString(R.string.alert_title_clear_cache)) .setCancelable(false)/*from w ww .jav a2 s.c om*/ .setPositiveButton(getActivity().getResources().getString(R.string.alert_message_exit_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); if (BluetoothLeService.mBluetoothGatt != null) BluetoothLeService.refreshDeviceCache(BluetoothLeService.mBluetoothGatt); BluetoothLeService.disconnect(); Toast.makeText(getActivity(), getResources().getString(R.string.alert_message_bluetooth_disconnect), Toast.LENGTH_SHORT).show(); Intent homePage = getActivity().getIntent(); getActivity().finish(); getActivity().overridePendingTransition(R.anim.slide_right, R.anim.push_right); startActivity(homePage); getActivity().overridePendingTransition(R.anim.slide_left, R.anim.push_left); } }) .setNegativeButton(getActivity().getResources().getString(R.string.alert_message_exit_cancel), null); alert = builder.create(); alert.setCanceledOnTouchOutside(false); alert.show(); }
From source file:it.unipr.ce.dsg.gamidroid.activities.NAM4JAndroidActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = this; isTablet = Utils.isTablet(this); // Setting the default network sharedPreferences = getSharedPreferences(Constants.PREFERENCES, Context.MODE_PRIVATE); Editor editor = sharedPreferences.edit(); editor.putString(Constants.NETWORK, Constants.DEFAULT_NETWORK); editor.commit();// ww w . jav a2 s . c om // Starting the resources monitoring service startService(new Intent(this, DeviceMonitorService.class)); wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); // Settings menu elements ArrayList<MenuListElement> listElements = new ArrayList<MenuListElement>(); listElements.add(new MenuListElement(getResources().getString(R.string.connectMenuTitle), getResources().getString(R.string.connectMenuSubTitle))); listElements.add(new MenuListElement(getResources().getString(R.string.settingsMenuTitle), getResources().getString(R.string.settingsMenuSubTitle))); listElements.add(new MenuListElement(getResources().getString(R.string.exitMenuTitle), getResources().getString(R.string.exitMenuSubTitle))); listView = (ListView) findViewById(R.id.ListViewContent); MenuListAdapter adapter = new MenuListAdapter(this, R.layout.menu_list_view_row, listElements); listView.setAdapter(adapter); listView.setOnItemClickListener(new ListItemClickListener()); mainRL = (RelativeLayout) findViewById(R.id.rlContainer); listRL = (RelativeLayout) findViewById(R.id.listContainer); cpuBar = (LinearLayout) findViewById(R.id.CpuBar); memoryBar = (LinearLayout) findViewById(R.id.MemoryBar); titleBarRL = (RelativeLayout) findViewById(R.id.titleLl); // Adding swipe gesture listener to the top bar titleBarRL.setOnTouchListener(new SwipeAndClickListener()); menuButton = (Button) findViewById(R.id.menuButton); menuButton.setOnTouchListener(new SwipeAndClickListener()); infoButton = (Button) findViewById(R.id.infoButton); infoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog dialog = new AlertDialog(NAM4JAndroidActivity.this) { @Override public boolean dispatchTouchEvent(MotionEvent event) { dismiss(); return false; } }; String text = getResources().getString(R.string.aboutApp); String title = getResources().getString(R.string.nam4j); dialog.setMessage(text); dialog.setTitle(title); dialog.setCanceledOnTouchOutside(true); dialog.show(); } }); centerButton = (Button) findViewById(R.id.centerButton); centerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { centerMap(); } }); isTablet = Utils.isTablet(context); int[] screenSize = Utils.getScreenSize(context, getWindow()); screenWidth = screenSize[0]; screenHeight = screenSize[1]; // Updates the display orientation each time the device is rotated if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { screenOrientation = Orientation.LANDSCAPE; } else { screenOrientation = Orientation.PORTRAIT; } // If the device is portrait, the menu button is displayed, the menu is // hidden and the swipe listener is added to the menu bar if (screenOrientation == Orientation.PORTRAIT) { menuButton.setVisibility(View.VISIBLE); // Adding swipe gesture listener to the top bar titleBarRL.setOnTouchListener(new SwipeAndClickListener()); if (isTablet) { menuWidth = 0.35; } else { menuWidth = 0.6; } } else { // If the device is a tablet in landscape, the menu button is // hidden, the menu is displayed, the swipe listener is not added to // the menu bar and the mainRL width is set to the window's width // minus the menu's width if (isTablet) { menuWidth = 0.2; menuButton.setVisibility(View.INVISIBLE); RelativeLayout.LayoutParams menuListLP = (LayoutParams) mainRL.getLayoutParams(); // Setting the main view width as the container width without // the menu menuListLP.width = (int) (screenWidth * (1 - menuWidth)); mainRL.setLayoutParams(menuListLP); displaySideMenu(); } else { menuWidth = 0.4; menuButton.setVisibility(View.VISIBLE); // Adding swipe gesture listener to the top bar titleBarRL.setOnTouchListener(new SwipeAndClickListener()); } } // Check if the device has the Google Play Services installed and // updated. They are necessary to use Google Maps int code = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context); if (code != ConnectionResult.SUCCESS) { showErrorDialog(code); System.out.println("Google Play Services error"); FrameLayout fl = (FrameLayout) findViewById(R.id.frameId); fl.removeAllViews(); } else { // Create a new global location parameters object mLocationRequest = new LocationRequest(); // Set the update interval mLocationRequest.setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS); // Use high accuracy mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // Set the interval ceiling to one minute mLocationRequest.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS); bitmapDescriptorBlue = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE); blueCircle = BitmapDescriptorFactory .fromBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.blue_circle)); bitmapDescriptorRed = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED); // Create a new location client, using the enclosing class to handle // callbacks mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this) .addOnConnectionFailedListener(this).addApi(LocationServices.API).build(); map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapview)).getMap(); if (map != null) { // Set default map center and zoom on Parma double lat = 44.7950156; double lgt = 10.32547; map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lgt), 12.0f)); // Adding listeners to the map respectively for zoom level // change and onTap event map.setOnCameraChangeListener(getCameraChangeListener()); map.setOnMapClickListener(getOnMapClickListener()); // Set map type as normal (i.e. not the satellite view) map.setMapType(com.google.android.gms.maps.GoogleMap.MAP_TYPE_NORMAL); // Hide traffic layer map.setTrafficEnabled(false); // Enable the 'my-location' layer, which continuously draws an // indication of a user's current location and bearing, and // displays UI controls that allow the interaction with the // location itself // map.setMyLocationEnabled(true); ml = new HashMap<String, Marker>(); // Get file manager for config files fileManager = FileManager.getFileManager(); fileManager.createFiles(); map.setOnMarkerClickListener(this); } else { AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setMessage("The map cannot be initialized."); dialog.setCancelable(true); dialog.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); dialog.show(); } } }
From source file:com.cypress.cysmart.HomePageActivity.java
/** * Handling the back pressed actions/* www . ja v a2 s . c o m*/ */ @Override public void onBackPressed() { // Getting the current active fragment Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.container); // Profile scanning fragment active if (currentFragment instanceof ProfileScanningFragment) { if (parentView.isDrawerOpen(Gravity.START)) { parentView.closeDrawer(Gravity.START); } else { alertbox(); } } else if (currentFragment instanceof AboutFragment) { if (parentView.isDrawerOpen(Gravity.START)) { parentView.closeDrawer(Gravity.START); } else { if (BluetoothLeService.getConnectionState() == 2 || BluetoothLeService.getConnectionState() == 1 || BluetoothLeService.getConnectionState() == 4) { BluetoothLeService.disconnect(); Toast.makeText(this, getResources().getString(R.string.alert_message_bluetooth_disconnect), Toast.LENGTH_SHORT).show(); } // Guiding the user back to profile scanning fragment Intent intent = getIntent(); finish(); overridePendingTransition(R.anim.slide_left, R.anim.push_left); startActivity(intent); overridePendingTransition(R.anim.slide_right, R.anim.push_right); } } else if (currentFragment instanceof ProfileControlFragment) { if (parentView.isDrawerOpen(Gravity.START)) { parentView.closeDrawer(Gravity.START); } else { // Guiding the user back to profile scanning fragment // Logger.i("BLE DISCONNECT---->"+BluetoothLeService.getConnectionState()); if (BluetoothLeService.getConnectionState() == 2 || BluetoothLeService.getConnectionState() == 1 || BluetoothLeService.getConnectionState() == 4) { BluetoothLeService.disconnect(); Toast.makeText(this, getResources().getString(R.string.alert_message_bluetooth_disconnect), Toast.LENGTH_SHORT).show(); } Intent intent = getIntent(); finish(); overridePendingTransition(R.anim.slide_right, R.anim.push_right); startActivity(intent); overridePendingTransition(R.anim.slide_left, R.anim.push_left); super.onBackPressed(); } } else if (currentFragment instanceof GattDescriptorFragment) { CySmartApplication mApplication = (CySmartApplication) getApplication(); BluetoothGattDescriptor descriptor = mApplication.getBluetoothgattDescriptor(); if (descriptor != null) { BluetoothLeService.readDescriptor(descriptor); } super.onBackPressed(); } else if (currentFragment instanceof HeartRateService || currentFragment instanceof HealthTemperatureService || currentFragment instanceof DeviceInformationService || currentFragment instanceof BatteryInformationService || currentFragment instanceof BloodPressureService || currentFragment instanceof CapsenseService || currentFragment instanceof CSCService || currentFragment instanceof FindMeService || currentFragment instanceof GlucoseService || currentFragment instanceof RGBFragment || currentFragment instanceof RSCService || currentFragment instanceof SensorHubService || currentFragment instanceof RemoteControlEmulatorFragment || currentFragment instanceof GattServicesFragment) { if (parentView.isDrawerOpen(Gravity.START)) { parentView.closeDrawer(Gravity.START); } else { Utils.setUpActionBar(this, getResources().getString(R.string.profile_control_fragment)); super.onBackPressed(); } } else if (currentFragment instanceof OTAFirmwareUpgradeFragment) { if (parentView.isDrawerOpen(Gravity.START)) { parentView.closeDrawer(Gravity.START); } else if (OTAFirmwareUpgradeFragment.mFileupgradeStarted) { AlertDialog alert; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(this.getResources().getString(R.string.alert_message_ota_pending)) .setTitle(this.getResources().getString(R.string.app_name)).setCancelable(false) .setPositiveButton(this.getResources().getString(R.string.alert_message_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if (BluetoothLeService.getConnectionState() == 2 || BluetoothLeService.getConnectionState() == 1 || BluetoothLeService.getConnectionState() == 4) { final BluetoothDevice device = BluetoothLeService.mBluetoothAdapter .getRemoteDevice( BluetoothLeService.getmBluetoothDeviceAddress()); OTAFirmwareUpgradeFragment.mFileupgradeStarted = false; unpairDevice(device); BluetoothLeService.disconnect(); Toast.makeText(HomePageActivity.this, getResources() .getString(R.string.alert_message_bluetooth_disconnect), Toast.LENGTH_SHORT).show(); Intent intent = getIntent(); finish(); overridePendingTransition(R.anim.slide_right, R.anim.push_right); startActivity(intent); overridePendingTransition(R.anim.slide_left, R.anim.push_left); } } }) .setNegativeButton(this.getResources().getString(R.string.alert_message_no), null); alert = builder.create(); alert.setCanceledOnTouchOutside(true); if (!this.isDestroyed()) alert.show(); } else { Utils.setUpActionBar(this, getResources().getString(R.string.profile_control_fragment)); super.onBackPressed(); } } else { if (parentView.isDrawerOpen(Gravity.START)) { parentView.closeDrawer(Gravity.START); } else { super.onBackPressed(); } } }
From source file:no.barentswatch.fiskinfo.MapActivity.java
/** * /* w ww.j a v a 2 s .co m*/ * @param activityContext * The context of the current activity */ @SuppressLint("InflateParams") public void setProximityAlertDialog(Context activityContext) { LayoutInflater layoutInflater = getLayoutInflater(); View view = layoutInflater.inflate(R.layout.dialog_scheduled_task_executor, null); final AlertDialog builder = new AlertDialog.Builder(activityContext).create(); builder.setTitle(R.string.map_set_proximity_alert_title); builder.setView(view); final EditText distanceEditText = (EditText) view.findViewById(R.id.scheduledProximityRangeEditText); final SeekBar seekbar = (SeekBar) view.findViewById(R.id.scheduledSetProximityRangeSeekBar); distanceEditText.setText(String.valueOf(minLenghtMeters)); final Spinner measuringUnitSpinner = (Spinner) view.findViewById(R.id.scheduledMeasuringUnitsSpinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.measurement_units, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); measuringUnitSpinner.setAdapter(adapter); seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser == true) { if (currentlySelected == meterIndex) { distanceEditText .setText(String.valueOf((int) (minLenghtMeters + (stepSizeMeters * progress)))); } else if (currentlySelected == nauticalMileIndex) { distanceEditText.setText( String.valueOf(minLenghtNauticalMiles + (stepSizeNauticalMiles * progress))); } } } }); measuringUnitSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { double distance = (distanceEditText.length() != 0 ? Double.parseDouble(distanceEditText.getText().toString()) : 0); System.out.println("posistion: " + position); System.out.println("currentlySelected: " + position); if (position == meterIndex) { if (position != currentlySelected) { distance = convertDistance(distance, position); distanceEditText.setText(String.valueOf(distance)); currentlySelected = position; } } else if (position == nauticalMileIndex) { if (position != currentlySelected) { distance = convertDistance(distance, position); distanceEditText.setText(String.valueOf(distance)); currentlySelected = position; } } else { return; } System.out.println("distance: " + distance); int newProgress = findProgress(distance, position); seekbar.setProgress(newProgress); System.out.println("progress: " + newProgress); distanceEditText.setText(String.valueOf(distance)); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); Button setProximityAlertButton = (Button) view.findViewById(R.id.scheduledSetProximityCheckerDialogButton); Button cancelButton = (Button) view.findViewById(R.id.cancel_button); builder.setView(view); builder.setCanceledOnTouchOutside(false); setProximityAlertButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (!alarmSet) { mGpsLocationTracker = new GpsLocationTracker(getContext()); double latitude, longitude = 0; if (mGpsLocationTracker.canGetLocation()) { latitude = mGpsLocationTracker.getLatitude(); cachedLat = latitude; longitude = mGpsLocationTracker.getLongitude(); cachedLon = longitude; } else { mGpsLocationTracker.showSettingsAlert(); return; } String distance = distanceEditText.getText().toString(); cachedDistance = distance; cacheWriter = new DownloadMapLayerFromBarentswatchApiInBackground().execute("fishingfacility", "OLEX", "cachedResults", String.valueOf(longitude), String.valueOf(latitude), distance, "true"); alarmSet = true; runScheduledAlarm(); } builder.dismiss(); } }); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { builder.cancel(); } }); builder.show(); }
From source file:com.nttec.everychan.ui.presentation.BoardFragment.java
@SuppressLint("InflateParams") private void saveThisPage() { if (!CompatibilityUtils.hasAccessStorage(activity)) return;//from ww w. j a v a 2s. c o m DownloadingService.DownloadingQueueItem check = new DownloadingService.DownloadingQueueItem( tabModel.pageModel, presentationModel.source.boardModel, DownloadingService.MODE_DOWNLOAD_ALL); String itemName = resources.getString(R.string.downloading_thread_format, tabModel.pageModel.boardName, tabModel.pageModel.threadNumber); if (DownloadingService.isInQueue(check)) { Toast.makeText(activity, resources.getString(R.string.notification_download_already_in_queue, itemName), Toast.LENGTH_LONG).show(); } else { Context dialogContext = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ? new ContextThemeWrapper(activity, R.style.Theme_Neutron) : activity; View saveThreadDialogView = LayoutInflater.from(dialogContext).inflate(R.layout.dialog_save_thread, null); final CheckBox saveThumbsChkbox = (CheckBox) saveThreadDialogView .findViewById(R.id.dialog_save_thread_thumbs); final CheckBox saveAllChkbox = (CheckBox) saveThreadDialogView .findViewById(R.id.dialog_save_thread_all); switch (settings.getDownloadThreadMode()) { case DownloadingService.MODE_DOWNLOAD_ALL: saveThumbsChkbox.setChecked(true); saveAllChkbox.setChecked(true); break; case DownloadingService.MODE_DOWNLOAD_THUMBS: saveThumbsChkbox.setChecked(true); saveAllChkbox.setChecked(false); break; default: saveThumbsChkbox.setChecked(false); saveAllChkbox.setChecked(false); saveAllChkbox.setEnabled(false); break; } saveThumbsChkbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (saveThumbsChkbox.isChecked()) { saveAllChkbox.setEnabled(true); } else { saveAllChkbox.setEnabled(false); saveAllChkbox.setChecked(false); } } }); DialogInterface.OnClickListener save = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { int mode = DownloadingService.MODE_ONLY_CACHE; if (saveThumbsChkbox.isChecked()) { mode = DownloadingService.MODE_DOWNLOAD_THUMBS; } if (saveAllChkbox.isChecked()) { mode = DownloadingService.MODE_DOWNLOAD_ALL; } settings.saveDownloadThreadMode(mode); Intent savePageIntent = new Intent(activity, DownloadingService.class); savePageIntent.putExtra(DownloadingService.EXTRA_DOWNLOADING_ITEM, new DownloadingService.DownloadingQueueItem(tabModel.pageModel, presentationModel.source.boardModel, mode)); activity.startService(savePageIntent); } }; AlertDialog saveThreadDialog = new AlertDialog.Builder(dialogContext).setView(saveThreadDialogView) .setTitle(R.string.dialog_save_thread_title) .setPositiveButton(R.string.dialog_save_thread_save, save) .setNegativeButton(android.R.string.cancel, null).create(); saveThreadDialog.setCanceledOnTouchOutside(false); saveThreadDialog.show(); } }
From source file:no.barentswatch.fiskinfo.BaseActivity.java
/** * This functions creates a dialog which allows the user to export different * map layers./*w w w . ja v a 2s . c om*/ * * @param ActivityContext * The context of the current activity. * @return True if the export succeeded, false otherwise. */ public boolean exportMapLayerToUser(Context activityContext) { LayoutInflater layoutInflater = getLayoutInflater(); View view = layoutInflater.inflate(R.layout.dialog_export_metadata, (null)); Button downloadButton = (Button) view.findViewById(R.id.metadataDownloadButton); Button cancelButton = (Button) view.findViewById(R.id.cancel_button); final AlertDialog builder = new AlertDialog.Builder(activityContext).create(); builder.setTitle(R.string.map_export_metadata_title); builder.setView(view); final AtomicReference<String> selectedHeader = new AtomicReference<String>(); final AtomicReference<String> selectedFormat = new AtomicReference<String>(); final ExpandableListView expListView = (ExpandableListView) view .findViewById(R.id.exportMetadataMapServices); final List<String> listDataHeader = new ArrayList<String>(); final HashMap<String, List<String>> listDataChild = new HashMap<String, List<String>>(); final Map<String, String> nameToApiNameResolver = new HashMap<String, String>(); JSONArray availableSubscriptions = getSharedCacheOfAvailableSubscriptions(); if (availableSubscriptions == null) { availableSubscriptions = authenticatedGetRequestToBarentswatchAPIService( getString(R.string.my_page_geo_data_service)); setSharedCacheOfAvailableSubscriptions(availableSubscriptions); } for (int i = 0; i < availableSubscriptions.length(); i++) { try { JSONObject currentSub = availableSubscriptions.getJSONObject(i); nameToApiNameResolver.put(currentSub.getString("Name"), currentSub.getString("ApiName")); listDataHeader.add(currentSub.getString("Name")); List<String> availableDownloadFormatsOfCurrentLayer = new ArrayList<String>(); JSONArray availableFormats = currentSub.getJSONArray("Formats"); for (int j = 0; j < availableFormats.length(); j++) { availableDownloadFormatsOfCurrentLayer.add(availableFormats.getString(j)); } listDataChild.put(listDataHeader.get(i), availableDownloadFormatsOfCurrentLayer); System.out .println("item: " + currentSub.getString("Name") + ", " + currentSub.getString("ApiName")); } catch (JSONException e) { e.printStackTrace(); Log.d("ExportMapLAyerToUser", "Invalid JSON returned from API CALL"); return false; } } final ExpandableListAdapter listAdapter = new ExpandableListAdapter(activityContext, listDataHeader, listDataChild); expListView.setAdapter(listAdapter); // Listview on child click listener expListView.setOnChildClickListener(new OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { selectedHeader.set(nameToApiNameResolver.get(listDataHeader.get(groupPosition))); selectedHeader.set(listDataHeader.get(groupPosition)); selectedFormat.set(listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition)); LinearLayout currentlySelected = (LinearLayout) parent.findViewWithTag("currentlySelectedRow"); if (currentlySelected != null) { currentlySelected.getChildAt(0).setBackgroundColor(Color.WHITE); currentlySelected.setTag(null); } ((LinearLayout) v).getChildAt(0).setBackgroundColor(Color.rgb(214, 214, 214)); v.setTag("currentlySelectedRow"); return true; } }); downloadButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { new DownloadMapLayerFromBarentswatchApiInBackground() .execute(nameToApiNameResolver.get(selectedHeader.get()), selectedFormat.get()); builder.dismiss(); } }); cancelButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { builder.dismiss(); } }); builder.setCanceledOnTouchOutside(false); builder.show(); return true; }
From source file:cl.smartcities.isci.transportinspector.dialogs.BusSelectionDialog.java
@NonNull @Override/* w w w . ja va 2 s . c o m*/ public Dialog onCreateDialog(Bundle savedInstanceState) { final AlertDialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); LayoutInflater inflater = this.getActivity().getLayoutInflater(); final View dialog_view = inflater.inflate(R.layout.bus_selection_dialog, null); final Typeface iconTypeface = Typeface.createFromAsset(this.getContext().getAssets(), getActivity().getString(R.string.icon_font)); ((TextView) dialog_view.findViewById(R.id.suggestion_icon)).setTypeface(iconTypeface); builder.setView(dialog_view); builder.setCancelable(false); dialog = builder.create(); final Bundle bundle = getArguments(); ArrayList<Bus> buses = null; if (bundle != null) { buses = bundle.getParcelableArrayList(NotificationState.BUSES); } if (buses != null && !buses.isEmpty()) { dialog_view.findViewById(R.id.list_view).setVisibility(View.VISIBLE); setBusMap(buses); ArrayList<String> serviceList = new ArrayList<>(); serviceList.addAll(this.busMap.keySet()); BusSelectionAdapter adapter = new BusSelectionAdapter(this.getContext(), serviceList, busMap, new BusSelectionAdapter.ListViewAdapterListener() { @Override public void onPositiveClick(Bus bus) { dialog.cancel(); listener.onPositiveClick(bus); } @Override public void onNegativeClick() { dialog.cancel(); listener.onNegativeClick(); } }); ListView listView = (ListView) dialog_view.findViewById(R.id.list_view); listView.setAdapter(adapter); if (adapter.getCount() > VISIBLE_BUSES) { View item = adapter.getView(0, null, listView); item.measure(0, 0); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, (int) ((VISIBLE_BUSES + 0.5) * item.getMeasuredHeight())); listView.setLayoutParams(params); } } Button otherAcceptButton = (Button) dialog_view.findViewById(R.id.accept); otherAcceptButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText serviceEditText = (EditText) dialog_view.findViewById(R.id.service_edit_text); EditText licensePlateEditText = (EditText) dialog_view.findViewById(R.id.license_plate_edit_text); String service = serviceEditText.getText().toString(); String licensePlate = licensePlateEditText.getText().toString(); ServiceHelper helper = new ServiceHelper(getContext()); if (ServiceValidator.validate(service) && helper.getColorId(Util.formatServiceName(service)) != 0) { service = Util.formatServiceName(service); if (licensePlate.equals("")) { licensePlate = Constants.DUMMY_LICENSE_PLATE; } else if (!LicensePlateValidator.validate(licensePlate)) { Toast.makeText(getContext(), R.string.bus_selection_warning_plate, Toast.LENGTH_SHORT) .show(); return; } } else { Toast.makeText(getContext(), R.string.bus_selection_warning_service, Toast.LENGTH_SHORT).show(); return; } final Bus bus = new Bus(Util.formatServiceName(service), licensePlate); InputMethodManager imm = (InputMethodManager) getContext() .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); Log.d("BusSelectionDialog", "hiding soft input"); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { BusSelectionDialog.this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { dialog.cancel(); listener.onPositiveClick(bus); } }); } }, 500); //dialog.cancel(); // TODO(aantoine): This call is to quick, some times the keyboard is not // out of the window when de sliding panel shows up. //listener.onPositiveClick(bus); } }); /* set cancel button to close dialog */ dialog_view.findViewById(R.id.close_dialog).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.cancel(); listener.onNegativeClick(); } }); ((Button) dialog_view.findViewById(R.id.close_dialog)).setTypeface(iconTypeface); dialog.setCanceledOnTouchOutside(false); return dialog; }