List of usage examples for android.widget ImageView setImageResource
@android.view.RemotableViewMethod(asyncImpl = "setImageResourceAsync") public void setImageResource(@DrawableRes int resId)
From source file:cm.confide.ex.chips.BaseRecipientAdapter.java
@Override public View getView(int position, View convertView, ViewGroup parent) { final RecipientEntry entry = getEntries().get(position); String displayName = entry.getDisplayName(); String destination = entry.getDestination(); if (TextUtils.isEmpty(displayName) || TextUtils.equals(displayName, destination)) { displayName = destination;/*from w ww. j a va2 s. c o m*/ // We only show the destination for secondary entries, so clear it // only for the first level. if (entry.isFirstLevel()) { destination = null; } } final View itemView = convertView != null ? convertView : mInflater.inflate(getItemLayout(), parent, false); final TextView displayNameView = (TextView) itemView.findViewById(getDisplayNameId()); final TextView destinationView = (TextView) itemView.findViewById(getDestinationId()); final TextView destinationTypeView = (TextView) itemView.findViewById(getDestinationTypeId()); final ImageView imageView = (ImageView) itemView.findViewById(getPhotoId()); displayNameView.setText(displayName); if (!TextUtils.isEmpty(destination)) { destinationView.setText(destination); } else { destinationView.setText(null); } if (destinationTypeView != null) { final CharSequence destinationType = mQuery .getTypeLabel(mContext.getResources(), entry.getDestinationType(), entry.getDestinationLabel()) .toString().toUpperCase(); destinationTypeView.setText(destinationType); } if (entry.isFirstLevel()) { displayNameView.setVisibility(View.VISIBLE); if (imageView != null) { imageView.setVisibility(View.VISIBLE); final byte[] photoBytes = entry.getPhotoBytes(); if (photoBytes != null) { final Bitmap photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length); imageView.setImageBitmap(photo); } else { imageView.setImageResource(getDefaultPhotoResource()); } } } else { displayNameView.setVisibility(View.GONE); if (imageView != null) { imageView.setVisibility(View.INVISIBLE); } } return itemView; }
From source file:de.dfki.iui.opentok.cordova.plugin.OpenTokPlugin.java
private ImageView createAudioIcon(int initialResourceId, int initialVisibility) { ImageView imgView = new ImageView(this.cordova.getActivity()); imgView.setImageResource(initialResourceId); imgView.setVisibility(initialVisibility); return imgView; }
From source file:com.gcssloop.diycode.activity.MainActivity.java
private void loadMenuData() { NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); View headerView = navigationView.getHeaderView(0); ImageView avatar = (ImageView) headerView.findViewById(R.id.nav_header_image); TextView username = (TextView) headerView.findViewById(R.id.nav_header_name); TextView tagline = (TextView) headerView.findViewById(R.id.nav_header_tagline); if (mDiycode.isLogin()) { UserDetail me = mCache.getMe();//from w w w .j a v a2 s . co m if (me == null) { Logger.e("?"); mDiycode.getMe(); // ? return; } username.setText(me.getLogin()); tagline.setText(me.getTagline()); Glide.with(this).load(me.getAvatar_url()).into(avatar); avatar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UserDetail me = mCache.getMe(); if (me == null) { try { me = mDiycode.getMeNow(); } catch (Exception e) { e.printStackTrace(); } } if (me != null) { User user = new User(); user.setId(me.getId()); user.setName(me.getName()); user.setLogin(me.getLogin()); user.setAvatar_url(me.getAvatar_url()); UserActivity.newInstance(MainActivity.this, user); } } }); } else { mCache.removeMe(); username.setText("()"); tagline.setText("?"); avatar.setImageResource(R.mipmap.ic_launcher); avatar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openActivity(LoginActivity.class); } }); } }
From source file:com.t2.compassionMeditation.Graphs1Activity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, this.getClass().getSimpleName() + ".onCreate()"); // We don't want the screen to timeout in this activity getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); this.requestWindowFeature(Window.FEATURE_NO_TITLE); // This needs to happen BEFORE setContentView setContentView(R.layout.graphs_activity_layout); mInstance = this; sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); mLoggingEnabled = SharedPref.getBoolean(this, "enable_logging", true); mDatabaseEnabled = SharedPref.getBoolean(this, "database_enabled", false); mAntHrmEnabled = SharedPref.getBoolean(this, "enable_ant_hrm", false); mInternalSensorMonitoring = SharedPref.getBoolean(this, "inernal_sensor_monitoring_enabled", false); if (mAntHrmEnabled) { mHeartRateSource = HEARTRATE_ANT; } else {/* w w w .j a v a2 s . com*/ mHeartRateSource = HEARTRATE_ZEPHYR; } // The session start time will be used as session id // Note this also sets session start time // **** This session ID will be prepended to all JSON data stored // in the external database until it's changed (by the start // of a new session. Calendar cal = Calendar.getInstance(); SharedPref.setBioSessionId(sharedPref, cal.getTimeInMillis()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US); String sessionDate = sdf.format(new Date()); String userId = SharedPref.getString(this, "SelectedUser", ""); long sessionId = SharedPref.getLong(this, "bio_session_start_time", 0); mDataOutHandler = new DataOutHandler(this, userId, sessionDate, mAppId, DataOutHandler.DATA_TYPE_EXTERNAL_SENSOR, sessionId); if (mDatabaseEnabled) { TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); String myNumber = telephonyManager.getLine1Number(); String remoteDatabaseUri = SharedPref.getString(this, "database_sync_name", getString(R.string.database_uri)); // remoteDatabaseUri += myNumber; Log.d(TAG, "Initializing database at " + remoteDatabaseUri); // TODO: remove try { mDataOutHandler.initializeDatabase(dDatabaseName, dDesignDocName, dDesignDocId, byDateViewName, remoteDatabaseUri); } catch (DataOutHandlerException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } mDataOutHandler.setRequiresAuthentication(false); } mBioDataProcessor.initialize(mDataOutHandler); if (mLoggingEnabled) { mDataOutHandler.enableLogging(this); } if (mLogCatEnabled) { mDataOutHandler.enableLogCat(); } // Log the version try { PackageManager packageManager = getPackageManager(); PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0); mApplicationVersion = info.versionName; String versionString = mAppId + " application version: " + mApplicationVersion; DataOutPacket packet = new DataOutPacket(); packet.add(DataOutHandlerTags.version, versionString); try { mDataOutHandler.handleDataOut(packet); } catch (DataOutHandlerException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } } catch (NameNotFoundException e) { Log.e(TAG, e.toString()); } // Set up UI elements Resources resources = this.getResources(); AssetManager assetManager = resources.getAssets(); mPauseButton = (Button) findViewById(R.id.buttonPause); mAddMeasureButton = (Button) findViewById(R.id.buttonAddMeasure); mTextInfoView = (TextView) findViewById(R.id.textViewInfo); mMeasuresDisplayText = (TextView) findViewById(R.id.measuresDisplayText); // Don't actually show skin conductance meter unless we get samples ImageView image = (ImageView) findViewById(R.id.imageView1); image.setImageResource(R.drawable.signal_bars0); // Check to see of there a device configured for EEG, if so then show the skin conductance meter String tmp = SharedPref.getString(this, "EEG", null); if (tmp != null) { image.setVisibility(View.VISIBLE); } else { image.setVisibility(View.INVISIBLE); } // Initialize SPINE by passing the fileName with the configuration properties try { mManager = SPINEFactory.createSPINEManager("SPINETestApp.properties", resources); } catch (InstantiationException e) { Log.e(TAG, "Exception creating SPINE manager: " + e.toString()); e.printStackTrace(); } try { currentMindsetData = new MindsetData(this); } catch (Exception e1) { Log.e(TAG, "Exception creating MindsetData: " + e1.toString()); e1.printStackTrace(); } // Establish nodes for BSPAN // Create a broadcast receiver. Note that this is used ONLY for command messages from the service // All data from the service goes through the mail SPINE mechanism (received(Data data)). // See public void received(Data data) this.mCommandReceiver = new SpineReceiver(this); int itemId = 0; eegPos = itemId; // eeg always comes first mBioParameters.clear(); // First create GraphBioParameters for each of the EEG static params (ie mindset) for (itemId = 0; itemId < MindsetData.NUM_BANDS + 2; itemId++) { // 2 extra, for attention and meditation GraphBioParameter param = new GraphBioParameter(itemId, MindsetData.spectralNames[itemId], "", true); param.isShimmer = false; mBioParameters.add(param); } // Now create all of the potential dynamic GBraphBioParameters (GSR, EMG, ECG, EEG, HR, Skin Temp, Resp Rate // String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names); String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names_less_eeg); for (String paramName : paramNamesStringArray) { if (paramName.equalsIgnoreCase("not assigned")) continue; GraphBioParameter param = new GraphBioParameter(itemId, paramName, "", true); if (paramName.equalsIgnoreCase("gsr")) { gsrPos = itemId; param.isShimmer = true; param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_GSR_SENSOR; param.shimmerNode = getShimmerNode(); } if (paramName.equalsIgnoreCase("emg")) { emgPos = itemId; param.isShimmer = true; param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_EMG_SENSOR; param.shimmerNode = getShimmerNode(); } if (paramName.equalsIgnoreCase("ecg")) { ecgPos = itemId; param.isShimmer = true; param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_ECG_SENSOR; param.shimmerNode = getShimmerNode(); } if (paramName.equalsIgnoreCase("heart rate")) { heartRatePos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("resp rate")) { respRatePos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("skin temp")) { skinTempPos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth Airflow")) { eHealthAirFlowPos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth Temp")) { eHealthTempPos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth SpO2")) { eHealthSpO2Pos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth Heartrate")) { eHealthHeartRatePos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth GSR")) { eHealthGSRPos = itemId; param.isShimmer = false; } itemId++; mBioParameters.add(param); } // Since These are static nodes (Non-spine) we have to manually put them in the active node list Node mindsetNode = null; mindsetNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_MINDSET)); // Note that the sensor id 0xfff1 (-15) is a reserved id for this particular sensor mManager.getActiveNodes().add(mindsetNode); Node zepherNode = null; zepherNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_ZEPHYR)); mManager.getActiveNodes().add(zepherNode); // The arduino node is programmed to look like a static Spine node // Note that currently we don't have to turn it on or off - it's always streaming // Since Spine (in this case) is a static node we have to manually put it in the active node list // Since the final int RESERVED_ADDRESS_ARDUINO_SPINE = 1; // 0x0001 mSpineNode = new Node(new Address("" + RESERVED_ADDRESS_ARDUINO_SPINE)); mManager.getActiveNodes().add(mSpineNode); final String sessionName; // Check to see if we were requested to play back a previous session try { Bundle bundle = getIntent().getExtras(); if (bundle != null) { sessionName = bundle.getString(BioZenConstants.EXTRA_SESSION_NAME); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Replay Session " + sessionName + "?"); alert.setMessage("Make sure to turn off all Bluetooth Sensors!"); alert.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { mDataOutHandler.logNote("Replaying data from session " + sessionName); } catch (DataOutHandlerException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } replaySessionData(sessionName); AlertDialog.Builder alert1 = new AlertDialog.Builder(mInstance); alert1.setTitle("INFO"); alert1.setMessage("Replay of session complete!"); alert1.show(); } }); alert.show(); } } catch (Exception e) { Log.e(TAG, e.toString()); e.printStackTrace(); } if (mInternalSensorMonitoring) { // IntentSender Launches our service scheduled with with the alarm manager mBigBrotherService = PendingIntent.getService(Graphs1Activity.this, 0, new Intent(Graphs1Activity.this, BigBrotherService.class), 0); long firstTime = SystemClock.elapsedRealtime(); // Schedule the alarm! AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, mPollingPeriod * 1000, mBigBrotherService); // Tell the user about what we did. Toast.makeText(Graphs1Activity.this, R.string.service_scheduled, Toast.LENGTH_LONG).show(); } //testFIRFilter(); // testHR(); }
From source file:com.t2.compassionMeditation.Graphs1Activity.java
/** * This is where we receive sensor data that comes through the actual * Spine channel. /*from w ww. j ava 2 s.c o m*/ * @param data Generic Spine data packet. Should be cast to specifid data type indicated by data.getFunctionCode() * * @see spine.SPINEListener#received(spine.datamodel.Data) */ @Override public void received(Data data) { //Log.d(TAG, this.getClass().getSimpleName() + ".received()"); if (data != null) { switch (data.getFunctionCode()) { // E-Health board case SPINEFunctionConstants.FEATURE: { FeatureData featureData = (FeatureData) data; Feature[] feats = featureData.getFeatures(); if (feats.length < 2) { break; } Feature firsFeat = feats[0]; Feature Feat2 = feats[1]; int airFlow = firsFeat.getCh1Value(); int scaledTemp = firsFeat.getCh2Value(); float temp = (float) scaledTemp / (65535F / 9F) + 29F; int BPM = firsFeat.getCh3Value(); int SPO2 = firsFeat.getCh4Value(); int scaledConductance = Feat2.getCh1Value(); float conductance = (float) scaledConductance / (65535F / 4F); Log.d(TAG, "E-health Values = " + airFlow + ", " + temp + ", " + BPM + ", " + SPO2 + ", " + conductance + ", "); synchronized (mKeysLock) { mBioParameters.get(eHealthAirFlowPos).rawValue = airFlow; mBioParameters.get(eHealthAirFlowPos).scaledValue = (int) map(airFlow, 0, 360, 0, 100); mBioParameters.get(eHealthTempPos).rawValue = (int) temp; mBioParameters.get(eHealthTempPos).scaledValue = (int) map(temp, 29, 40, 0, 100); mBioParameters.get(eHealthHeartRatePos).rawValue = BPM; mBioParameters.get(eHealthHeartRatePos).scaledValue = (int) map(BPM, 30, 220, 0, 100); mBioParameters.get(eHealthSpO2Pos).rawValue = SPO2; mBioParameters.get(eHealthSpO2Pos).scaledValue = SPO2; mBioParameters.get(eHealthGSRPos).rawValue = (int) map(scaledConductance, 0, 65535, 0, 100); mBioParameters.get(eHealthGSRPos).scaledValue = (int) map(scaledConductance, 0, 65535, 0, 100); ; DataOutPacket packet = new DataOutPacket(); packet.add(DataOutHandlerTags.RAW_HEARTRATE, BPM); packet.add(DataOutHandlerTags.RAW_GSR, conductance); packet.add(DataOutHandlerTags.RAW_SKINTEMP, temp); packet.add(DataOutHandlerTags.SPO2, SPO2); packet.add(DataOutHandlerTags.AIRFLOW, airFlow); try { mDataOutHandler.handleDataOut(packet); } catch (DataOutHandlerException e) { Log.e(TAG, e.toString()); // e.printStackTrace(); } } break; } case SPINEFunctionConstants.HEARTBEAT: { synchronized (mKeysLock) { HeartBeatData thisData = (HeartBeatData) data; int scaled = (thisData.getBPM()) / 2; if (mHeartRateSource == HEARTRATE_ANT) { mBioParameters.get(heartRatePos).rawValue = thisData.getBPM(); mBioParameters.get(heartRatePos).scaledValue = scaled; } // Send data to output DataOutPacket packet = new DataOutPacket(); packet.add(DataOutHandlerTags.RAW_HEARTRATE, thisData.getBPM()); try { mDataOutHandler.handleDataOut(packet); } catch (DataOutHandlerException e) { Log.e(TAG, e.toString()); // e.printStackTrace(); } // See if we are configured to update display every time we get sensor data if (mDisplaySampleRate == 9999 && mIsActive) { this.runOnUiThread(Timer_Tick); } } break; } case SPINEFunctionConstants.SHIMMER: { Node node = data.getNode(); numTicsWithoutData = 0; Node source = data.getNode(); ShimmerData shimmerData = (ShimmerData) data; synchronized (mKeysLock) { switch (shimmerData.sensorCode) { case SPINESensorConstants.SHIMMER_GSR_SENSOR: mBioDataProcessor.processShimmerGSRData(shimmerData, mConfiguredGSRRange); mBioParameters.get(gsrPos).rawValue = (int) (mBioDataProcessor.mGsrConductance * 1000); // scale by 1000 to fit a float into an int double scaled = mBioDataProcessor.mGsrConductance * 10; mBioParameters.get(gsrPos).scaledValue = (int) scaled; // See if we are configured to update display every time we get sensor data if (mDisplaySampleRate == 9999 && mIsActive) { this.runOnUiThread(Timer_Tick); } break; case SPINESensorConstants.SHIMMER_EMG_SENSOR: mBioDataProcessor.processShimmerEMGData(shimmerData); scaled = MathExtra.scaleData((float) shimmerData.emg, 4000F, 0F, 100); mBioParameters.get(emgPos).rawValue = (int) scaled; mBioParameters.get(emgPos).scaledValue = (int) scaled; // See if we are configured to update display every time we get sensor data if (mDisplaySampleRate == 9999) { this.runOnUiThread(Timer_Tick); } break; case SPINESensorConstants.SHIMMER_ECG_SENSOR: // If we're receiving packets from shimmer egg then swith the heartrate to shimmer // Otherwise we'll leave it at the default which is zephyr mHeartRateSource = HEARTRATE_SHIMMER; mBioDataProcessor.processShimmerECGData(shimmerData); scaled = (mBioDataProcessor.mRawEcg + 50) / 2; mBioParameters.get(ecgPos).rawValue = (int) scaled; mBioParameters.get(ecgPos).scaledValue = (int) scaled; if (mHeartRateSource == HEARTRATE_SHIMMER) { mBioParameters.get(heartRatePos).rawValue = mBioDataProcessor.mShimmerHeartRate; mBioParameters.get(heartRatePos).scaledValue = mBioDataProcessor.mShimmerHeartRate; } // See if we are configured to update display every time we get sensor data if (mDisplaySampleRate == 9999) { this.runOnUiThread(Timer_Tick); } break; } } break; } case SPINEFunctionConstants.ZEPHYR: { numTicsWithoutData = 0; mBioDataProcessor.processZephyrData(data); synchronized (mKeysLock) { if (mHeartRateSource == HEARTRATE_ZEPHYR) { mBioParameters.get(heartRatePos).scaledValue = mBioDataProcessor.mZephyrHeartRate / 3; mBioParameters.get(heartRatePos).rawValue = mBioDataProcessor.mZephyrHeartRate; } mBioParameters.get(respRatePos).scaledValue = (int) mBioDataProcessor.mRespRate * 5; mBioParameters.get(respRatePos).rawValue = (int) mBioDataProcessor.mRespRate; mBioParameters.get(skinTempPos).scaledValue = (int) mBioDataProcessor.mSkinTempF; mBioParameters.get(skinTempPos).rawValue = (int) mBioDataProcessor.mSkinTempF; } synchronized (mRespRateAverageLock) { mRespRateTotal += mBioDataProcessor.mRespRate; mRespRateIndex++; } // See if we are configured to update display every time we get sensor data if (mDisplaySampleRate == 9999) { this.runOnUiThread(Timer_Tick); } break; } // End case SPINEFunctionConstants.ZEPHYR: case SPINEFunctionConstants.MINDSET: { Node source = data.getNode(); MindsetData mindsetData = (MindsetData) data; mBioDataProcessor.processMindsetData(data, currentMindsetData); if (mindsetData.exeCode == Constants.EXECODE_SPECTRAL || mindsetData.exeCode == Constants.EXECODE_RAW_ACCUM) { numTicsWithoutData = 0; synchronized (mKeysLock) { for (int i = 0; i < MindsetData.NUM_BANDS + 2; i++) { // 2 extra, for attention and meditation mBioParameters.get(i).scaledValue = currentMindsetData.getFeatureValue(i); mBioParameters.get(i).rawValue = currentMindsetData.getFeatureValue(i); } } // See if we are configured to update display every time we get sensor data if (mDisplaySampleRate == 9999) { this.runOnUiThread(Timer_Tick); } } if (mindsetData.exeCode == Constants.EXECODE_POOR_SIG_QUALITY) { // Now show signal strength as bars int sigQuality = mindsetData.poorSignalStrength & 0xff; ImageView image = (ImageView) findViewById(R.id.imageView1); if (sigQuality == 200) image.setImageResource(R.drawable.signal_bars0); else if (sigQuality > 150) image.setImageResource(R.drawable.signal_bars1); else if (sigQuality > 100) image.setImageResource(R.drawable.signal_bars2); else if (sigQuality > 50) image.setImageResource(R.drawable.signal_bars3); else if (sigQuality > 25) image.setImageResource(R.drawable.signal_bars4); else image.setImageResource(R.drawable.signal_bars5); if (sigQuality == 200 && mPrevSigQuality != 200) { Toast.makeText(getApplicationContext(), "Headset not makeing good skin contact. Please Adjust", Toast.LENGTH_LONG).show(); } mPrevSigQuality = sigQuality; } break; } // End case SPINEFunctionConstants.MINDSET: } // End switch (data.getFunctionCode()) } // End if (data != null) }
From source file:com.DGSD.Teexter.UI.Recipient.BaseRecipientAdapter.java
@Override public View getView(int position, View convertView, ViewGroup parent) { final RecipientEntry entry = mEntries.get(position); switch (entry.getEntryType()) { case RecipientEntry.ENTRY_TYPE_WAITING_FOR_DIRECTORY_SEARCH: { return convertView != null ? convertView : mInflater.inflate(getWaitingForDirectorySearchLayout(), parent, false); }/*from w w w .ja v a2 s.c o m*/ default: { String displayName = entry.getDisplayName(); String destination = entry.getDestination(); if (TextUtils.isEmpty(displayName) || TextUtils.equals(displayName, destination)) { displayName = destination; destination = null; } final View itemView = convertView != null ? convertView : mInflater.inflate(getItemLayout(), parent, false); final TextView displayNameView = (TextView) itemView.findViewById(getDisplayNameId()); final TextView destinationView = (TextView) itemView.findViewById(getDestinationId()); final TextView destinationTypeView = (TextView) itemView.findViewById(getDestinationTypeId()); final ImageView imageView = (ImageView) itemView.findViewById(getPhotoId()); displayNameView.setText(displayName); if (!TextUtils.isEmpty(destination)) { destinationView.setText(destination); } else { destinationView.setText(null); } if (destinationTypeView != null) { final CharSequence destinationType = Email.getTypeLabel(mContext.getResources(), entry.getDestinationType(), entry.getDestinationLabel()).toString().toUpperCase(); destinationTypeView.setText(destinationType); } if (entry.isFirstLevel()) { displayNameView.setVisibility(View.VISIBLE); if (imageView != null) { imageView.setVisibility(View.VISIBLE); final byte[] photoBytes = entry.getPhotoBytes(); if (photoBytes != null && imageView != null) { final Bitmap photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length); imageView.setImageBitmap(photo); } else { imageView.setImageResource(getDefaultPhotoResource()); } } } else { displayNameView.setVisibility(View.GONE); if (imageView != null) { imageView.setVisibility(View.INVISIBLE); } } return itemView; } } }
From source file:com.tingbacke.wearmaps.MobileActivity.java
/** * Updates my location to currentLocation, moves the camera. * * @param location// w w w . j ava 2s .co m */ private void handleNewLocation(Location location) { Log.d(TAG, location.toString()); double latitude = location.getLatitude(); double longitude = location.getLongitude(); LatLng latLng = new LatLng(latitude, longitude); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(18).bearing(0).tilt(25) .build(); mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); TextView myLatitude = (TextView) findViewById(R.id.textView); TextView myLongitude = (TextView) findViewById(R.id.textView2); TextView myAddress = (TextView) findViewById(R.id.textView3); ImageView myImage = (ImageView) findViewById(R.id.imageView); myLatitude.setText("Latitude: " + String.valueOf(latitude)); myLongitude.setText("Longitude: " + String.valueOf(longitude)); // Instantiating currDistance to get distance to destination from my location currDistance = getDistance(latitude, longitude, destLat, destLong); Geocoder geocoder = new Geocoder(this, Locale.ENGLISH); try { List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1); if (addresses != null) { Address returnedAddress = addresses.get(0); StringBuilder strReturnedAddress = new StringBuilder(""); for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n"); } // Hardcoded string which searches through strReturnedAddress for specifics // if statements decide which information will be displayed String fake = strReturnedAddress.toString(); if (fake.contains("stra Varvsgatan")) { myAddress.setText("K3, Malm Hgskola" + "\n" + "Cykelparkering: 50m" + "\n" + "Dest: " + Math.round(currDistance) + "m away"); myImage.setImageResource(R.mipmap.kranen); } else if (fake.contains("Lilla Varvsgatan")) { myAddress.setText("Turning Torso" + "\n" + "Caf: 90m " + "\n" + "Dest: " + Math.round(currDistance) + "m away"); myImage.setImageResource(R.mipmap.turning); } else if (fake.contains("Vstra Varvsgatan")) { myAddress.setText("Kockum Fritid" + "\n" + "Bankomat: 47m" + "\n" + "Dest: " + Math.round(currDistance) + "m away"); myImage.setImageResource(R.mipmap.kockum); } else if (fake.contains("Stapelbddsgatan")) { myAddress.setText("Stapelbddsparken" + "\n" + "Toalett: 63m" + "\n" + "Dest: " + Math.round(currDistance) + "m away"); myImage.setImageResource(R.mipmap.stapel); } else if (fake.contains("Stora Varvsgatan")) { myAddress.setText("Media Evolution City" + "\n" + "Busshllplats: 94m" + "\n" + "Dest: " + Math.round(currDistance) + "m away"); myImage.setImageResource(R.mipmap.media); } else if (fake.contains("Masttorget")) { myAddress.setText("Ica Maxi" + "\n" + "Systembolaget: 87m" + "\n" + "Dest: " + Math.round(currDistance) + "m away"); myImage.setImageResource(R.mipmap.ica); } else if (fake.contains("Riggaregatan")) { myAddress.setText("Scaniabadet" + "\n" + "\n" + "Dest: " + Math.round(currDistance) + "m away"); myImage.setImageResource(R.mipmap.scaniabadet); } else if (fake.contains("Dammfrivgen")) { //fakear Turning Torso p min adress fr tillfllet myAddress.setText("Turning Torso" + "\n" + "453m away"); myImage.setImageResource(R.mipmap.turning); } //myAddress.setText(strReturnedAddress.toString()+ "Dest: " + Math.round(currDistance) + "m away"); /* // Added this Toast to display address ---> In order to find out where to call notification builder for wearable Toast.makeText(MobileActivity.this, myAddress.getText().toString(), Toast.LENGTH_LONG).show(); */ //Here is where I call the notification builder for the wearable showNotification(1, "basic", getBasicNotification("myStack")); } else { myAddress.setText("No Address returned!"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); myAddress.setText("Cannot get Address!"); } }
From source file:com.keylesspalace.tusky.ComposeActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String theme = preferences.getString("appTheme", ThemeUtils.APP_THEME_DEFAULT); if (theme.equals("black")) { setTheme(R.style.TuskyDialogActivityBlackTheme); }/*from www . j a v a2s. co m*/ setContentView(R.layout.activity_compose); replyTextView = findViewById(R.id.composeReplyView); replyContentTextView = findViewById(R.id.composeReplyContentView); textEditor = findViewById(R.id.composeEditField); mediaPreviewBar = findViewById(R.id.compose_media_preview_bar); contentWarningBar = findViewById(R.id.composeContentWarningBar); contentWarningEditor = findViewById(R.id.composeContentWarningField); charactersLeft = findViewById(R.id.composeCharactersLeftView); tootButton = findViewById(R.id.composeTootButton); pickButton = findViewById(R.id.composeAddMediaButton); visibilityButton = findViewById(R.id.composeToggleVisibilityButton); contentWarningButton = findViewById(R.id.composeContentWarningButton); emojiButton = findViewById(R.id.composeEmojiButton); hideMediaToggle = findViewById(R.id.composeHideMediaButton); emojiView = findViewById(R.id.emojiView); emojiList = Collections.emptyList(); saveTootHelper = new SaveTootHelper(database.tootDao(), this); // Setup the toolbar. Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(null); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); Drawable closeIcon = AppCompatResources.getDrawable(this, R.drawable.ic_close_24dp); ThemeUtils.setDrawableTint(this, closeIcon, R.attr.compose_close_button_tint); actionBar.setHomeAsUpIndicator(closeIcon); } // setup the account image final AccountEntity activeAccount = accountManager.getActiveAccount(); if (activeAccount != null) { ImageView composeAvatar = findViewById(R.id.composeAvatar); if (TextUtils.isEmpty(activeAccount.getProfilePictureUrl())) { composeAvatar.setImageResource(R.drawable.avatar_default); } else { Picasso.with(this).load(activeAccount.getProfilePictureUrl()).error(R.drawable.avatar_default) .placeholder(R.drawable.avatar_default).into(composeAvatar); } composeAvatar.setContentDescription( getString(R.string.compose_active_account_description, activeAccount.getFullName())); mastodonApi.getInstance().enqueue(new Callback<Instance>() { @Override public void onResponse(@NonNull Call<Instance> call, @NonNull Response<Instance> response) { if (response.isSuccessful() && response.body().getMaxTootChars() != null) { maximumTootCharacters = response.body().getMaxTootChars(); updateVisibleCharactersLeft(); cacheInstanceMetadata(activeAccount); } } @Override public void onFailure(@NonNull Call<Instance> call, @NonNull Throwable t) { Log.w(TAG, "error loading instance data", t); loadCachedInstanceMetadata(activeAccount); } }); mastodonApi.getCustomEmojis().enqueue(new Callback<List<Emoji>>() { @Override public void onResponse(@NonNull Call<List<Emoji>> call, @NonNull Response<List<Emoji>> response) { emojiList = response.body(); setEmojiList(emojiList); cacheInstanceMetadata(activeAccount); } @Override public void onFailure(@NonNull Call<List<Emoji>> call, @NonNull Throwable t) { Log.w(TAG, "error loading custom emojis", t); loadCachedInstanceMetadata(activeAccount); } }); } else { // do not do anything when not logged in, activity will be finished in super.onCreate() anyway return; } composeOptionsView = findViewById(R.id.composeOptionsBottomSheet); composeOptionsView.setListener(this); composeOptionsBehavior = BottomSheetBehavior.from(composeOptionsView); composeOptionsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); addMediaBehavior = BottomSheetBehavior.from(findViewById(R.id.addMediaBottomSheet)); emojiBehavior = BottomSheetBehavior.from(emojiView); emojiView.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.HORIZONTAL, false)); enableButton(emojiButton, false, false); // Setup the interface buttons. tootButton.setOnClickListener(v -> onSendClicked()); pickButton.setOnClickListener(v -> openPickDialog()); visibilityButton.setOnClickListener(v -> showComposeOptions()); contentWarningButton.setOnClickListener(v -> onContentWarningChanged()); emojiButton.setOnClickListener(v -> showEmojis()); hideMediaToggle.setOnClickListener(v -> toggleHideMedia()); TextView actionPhotoTake = findViewById(R.id.action_photo_take); TextView actionPhotoPick = findViewById(R.id.action_photo_pick); int textColor = ThemeUtils.getColor(this, android.R.attr.textColorTertiary); Drawable cameraIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_camera_alt).color(textColor) .sizeDp(18); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoTake, cameraIcon, null, null, null); Drawable imageIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_image).color(textColor).sizeDp(18); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoPick, imageIcon, null, null, null); actionPhotoTake.setOnClickListener(v -> initiateCameraApp()); actionPhotoPick.setOnClickListener(v -> onMediaPick()); thumbnailViewSize = getResources().getDimensionPixelSize(R.dimen.compose_media_preview_size); /* Initialise all the state, or restore it from a previous run, to determine a "starting" * state. */ Status.Visibility startingVisibility = Status.Visibility.UNKNOWN; boolean startingHideText; ArrayList<SavedQueuedMedia> savedMediaQueued = null; if (savedInstanceState != null) { startingVisibility = Status.Visibility .byNum(savedInstanceState.getInt("statusVisibility", Status.Visibility.PUBLIC.getNum())); statusMarkSensitive = savedInstanceState.getBoolean("statusMarkSensitive"); startingHideText = savedInstanceState.getBoolean("statusHideText"); // Keep these until everything needed to put them in the queue is finished initializing. savedMediaQueued = savedInstanceState.getParcelableArrayList("savedMediaQueued"); // These are for restoring an in-progress commit content operation. InputContentInfoCompat previousInputContentInfo = InputContentInfoCompat .wrap(savedInstanceState.getParcelable("commitContentInputContentInfo")); int previousFlags = savedInstanceState.getInt("commitContentFlags"); if (previousInputContentInfo != null) { onCommitContentInternal(previousInputContentInfo, previousFlags); } photoUploadUri = savedInstanceState.getParcelable("photoUploadUri"); } else { statusMarkSensitive = false; startingHideText = false; photoUploadUri = null; } /* If the composer is started up as a reply to another post, override the "starting" state * based on what the intent from the reply request passes. */ Intent intent = getIntent(); String[] mentionedUsernames = null; ArrayList<String> loadedDraftMediaUris = null; inReplyToId = null; if (intent != null) { if (startingVisibility == Status.Visibility.UNKNOWN) { Status.Visibility preferredVisibility = Status.Visibility.byString( preferences.getString("defaultPostPrivacy", Status.Visibility.PUBLIC.serverString())); Status.Visibility replyVisibility = Status.Visibility .byNum(intent.getIntExtra(REPLY_VISIBILITY_EXTRA, Status.Visibility.UNKNOWN.getNum())); startingVisibility = Status.Visibility .byNum(Math.max(preferredVisibility.getNum(), replyVisibility.getNum())); } inReplyToId = intent.getStringExtra(IN_REPLY_TO_ID_EXTRA); mentionedUsernames = intent.getStringArrayExtra(MENTIONED_USERNAMES_EXTRA); String contentWarning = intent.getStringExtra(CONTENT_WARNING_EXTRA); if (contentWarning != null) { startingHideText = !contentWarning.isEmpty(); if (startingHideText) { startingContentWarning = contentWarning; } } // If come from SavedTootActivity String savedTootText = intent.getStringExtra(SAVED_TOOT_TEXT_EXTRA); if (!TextUtils.isEmpty(savedTootText)) { startingText = savedTootText; textEditor.setText(savedTootText); } String savedJsonUrls = intent.getStringExtra(SAVED_JSON_URLS_EXTRA); if (!TextUtils.isEmpty(savedJsonUrls)) { // try to redo a list of media loadedDraftMediaUris = new Gson().fromJson(savedJsonUrls, new TypeToken<ArrayList<String>>() { }.getType()); } int savedTootUid = intent.getIntExtra(SAVED_TOOT_UID_EXTRA, 0); if (savedTootUid != 0) { this.savedTootUid = savedTootUid; } if (intent.hasExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA)) { replyTextView.setVisibility(View.VISIBLE); String username = intent.getStringExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA); replyTextView.setText(getString(R.string.replying_to, username)); Drawable arrowDownIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_down) .sizeDp(12); ThemeUtils.setDrawableTint(this, arrowDownIcon, android.R.attr.textColorTertiary); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null, arrowDownIcon, null); replyTextView.setOnClickListener(v -> { TransitionManager.beginDelayedTransition((ViewGroup) replyContentTextView.getParent()); if (replyContentTextView.getVisibility() != View.VISIBLE) { replyContentTextView.setVisibility(View.VISIBLE); Drawable arrowUpIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_up) .sizeDp(12); ThemeUtils.setDrawableTint(this, arrowUpIcon, android.R.attr.textColorTertiary); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null, arrowUpIcon, null); } else { replyContentTextView.setVisibility(View.GONE); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null, arrowDownIcon, null); } }); } if (intent.hasExtra(REPLYING_STATUS_CONTENT_EXTRA)) { replyContentTextView.setText(intent.getStringExtra(REPLYING_STATUS_CONTENT_EXTRA)); } } // After the starting state is finalised, the interface can be set to reflect this state. setStatusVisibility(startingVisibility); updateHideMediaToggle(); updateVisibleCharactersLeft(); // Setup the main text field. textEditor.setOnCommitContentListener(this); final int mentionColour = textEditor.getLinkTextColors().getDefaultColor(); SpanUtilsKt.highlightSpans(textEditor.getText(), mentionColour); textEditor.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable editable) { SpanUtilsKt.highlightSpans(editable, mentionColour); updateVisibleCharactersLeft(); } }); textEditor.setAdapter(new MentionAutoCompleteAdapter(this, R.layout.item_autocomplete, this)); textEditor.setTokenizer(new MentionTokenizer()); // Add any mentions to the text field when a reply is first composed. if (mentionedUsernames != null) { StringBuilder builder = new StringBuilder(); for (String name : mentionedUsernames) { builder.append('@'); builder.append(name); builder.append(' '); } startingText = builder.toString(); textEditor.setText(startingText); textEditor.setSelection(textEditor.length()); } // work around Android platform bug -> https://issuetracker.google.com/issues/67102093 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O || Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) { textEditor.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } // Initialise the content warning editor. contentWarningEditor.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { updateVisibleCharactersLeft(); } @Override public void afterTextChanged(Editable s) { } }); showContentWarning(startingHideText); if (startingContentWarning != null) { contentWarningEditor.setText(startingContentWarning); } // Initialise the empty media queue state. waitForMediaLatch = new CountUpDownLatch(); // These can only be added after everything affected by the media queue is initialized. if (!ListUtils.isEmpty(loadedDraftMediaUris)) { for (String uriString : loadedDraftMediaUris) { Uri uri = Uri.parse(uriString); long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri); pickMedia(uri, mediaSize); } } else if (savedMediaQueued != null) { for (SavedQueuedMedia item : savedMediaQueued) { Bitmap preview = MediaUtils.getImageThumbnail(getContentResolver(), item.uri, thumbnailViewSize); addMediaToQueue(item.id, item.type, preview, item.uri, item.mediaSize, item.readyStage, item.description); } } else if (intent != null && savedInstanceState == null) { /* Get incoming images being sent through a share action from another app. Only do this * when savedInstanceState is null, otherwise both the images from the intent and the * instance state will be re-queued. */ String type = intent.getType(); if (type != null) { if (type.startsWith("image/")) { List<Uri> uriList = new ArrayList<>(); if (intent.getAction() != null) { switch (intent.getAction()) { case Intent.ACTION_SEND: { Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (uri != null) { uriList.add(uri); } break; } case Intent.ACTION_SEND_MULTIPLE: { ArrayList<Uri> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (list != null) { for (Uri uri : list) { if (uri != null) { uriList.add(uri); } } } break; } } } for (Uri uri : uriList) { long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri); pickMedia(uri, mediaSize); } } else if (type.equals("text/plain")) { String action = intent.getAction(); if (action != null && action.equals(Intent.ACTION_SEND)) { String text = intent.getStringExtra(Intent.EXTRA_TEXT); if (text != null) { int start = Math.max(textEditor.getSelectionStart(), 0); int end = Math.max(textEditor.getSelectionEnd(), 0); int left = Math.min(start, end); int right = Math.max(start, end); textEditor.getText().replace(left, right, text, 0, text.length()); } } } } } textEditor.requestFocus(); }
From source file:de.dfki.iui.opentok.cordova.plugin.OpenTokPlugin.java
private void doUpdateViewIconStatus(final ImageView icon, final int ressourceId, final int visibility) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override//ww w. j a v a2 s . c om public void run() { icon.setImageResource(ressourceId); icon.setVisibility(visibility); } }); }