List of usage examples for android.view View getContext
@ViewDebug.CapturedViewProperty public final Context getContext()
From source file:com.scrachx.foodfacts.checker.ui.history.HistoryFragment.java
@Override protected void setUp(View view) { String grade = ""; if (this.getArguments() != null) { String descGrade = this.getArguments().getString("grade"); grade = convertDescriptionToGrade(descGrade); if (StringUtils.isNotEmpty(descGrade)) { mNavHeader.setText(getString(R.string.history) + ": " + descGrade); }// w w w. j a va2 s.c om } mProductsHistoryRecyclerView = view.findViewById(R.id.products_recycler_view); mProductsHistory = new ArrayList<>(); // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView mProductsHistoryRecyclerView.setHasFixedSize(true); // use a linear layout manager LinearLayoutManager mLayoutManager = new LinearLayoutManager(getBaseActivity()); mProductsHistoryRecyclerView.setLayoutManager(mLayoutManager); // use VERTICAL divider DividerItemDecoration dividerItemDecoration = new DividerItemDecoration( mProductsHistoryRecyclerView.getContext(), DividerItemDecoration.VERTICAL); mProductsHistoryRecyclerView.addItemDecoration(dividerItemDecoration); // Retain an instance so that you can call `resetState()` for fresh searches String finalGrade = grade; mScrollListener = new EndlessRecyclerViewScrollListener(mLayoutManager) { @Override public void onLoadMore(int page, int totalItemsCount, RecyclerView view) { if (mProductsHistory.size() < mCountProducts) { mPresenter.onLoadProducts(page, finalGrade); } } }; // Adds the scroll listener to RecyclerView mProductsHistoryRecyclerView.addOnScrollListener(mScrollListener); // Click listener on a product mProductsHistoryRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(view.getContext(), new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { History hp = ((HistoryRecyclerViewAdapter) mProductsHistoryRecyclerView.getAdapter()) .getHistory(position); if (hp != null) { mPresenter.loadProduct(hp.getBarcode()); } } })); mPresenter.onLoadProducts(0, grade); }
From source file:carsharing.starter.automotive.iot.ibm.com.mobilestarterapp.Home.CarBrowse.java
public void getCars(final Location location) { final String url = API.carsNearby + "/" + location.getLatitude() + "/" + location.getLongitude(); try {//from w ww .ja va 2s .c o m final API.doRequest task = new API.doRequest(new API.doRequest.TaskListener() { @Override public void postExecute(JSONArray result) throws JSONException { JSONObject serverResponse = result.getJSONObject(result.length() - 1); int statusCode = serverResponse.getInt("statusCode"); result.remove(result.length() - 1); final FragmentActivity activity = getActivity(); if (activity == null) { return; } final ActionBar supportActionBar = ((AppCompatActivity) activity).getSupportActionBar(); if (statusCode == 200) { final View view = getView(); if (view == null) { return; } final ListView listView = (ListView) view.findViewById(R.id.listView); final ArrayList<CarData> carsArray = new ArrayList<CarData>(); for (int i = 0; i < result.length(); i++) { final CarData tempCarData = new CarData(result.getJSONObject(i)); carsArray.add(tempCarData); final LatLng carLocation = new LatLng(tempCarData.lat, tempCarData.lng); mMap.addMarker(new MarkerOptions().position(carLocation).title(tempCarData.title) .icon(BitmapDescriptorFactory.fromResource(R.drawable.models))); } Collections.sort(carsArray, new Comparator<CarData>() { @Override public int compare(CarData lhs, CarData rhs) { return lhs.distance - rhs.distance; } }); final CarDataAdapter adapter = new CarDataAdapter(activity.getApplicationContext(), carsArray); listView.setAdapter(adapter); final ArrayList<CarData> finalCarsArray = carsArray; listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) { final Intent carDetails = new Intent(view.getContext(), CarDetails.class); final Bundle bundle = new Bundle(); bundle.putSerializable("carData", finalCarsArray.get(position)); carDetails.putExtras(bundle); startActivity(carDetails); } }); if (carsArray.size() == 0) { final Toast toast = Toast.makeText(activity.getApplicationContext(), "No car available in this area. Location information may be incorrect. Make sure GPS or Wifi is effective and try again. Or, Free Plan limitation, ask administrator to delete registered cars.", Toast.LENGTH_LONG); toast.show(); supportActionBar.setTitle("No car available."); } else { final String title = (carsArray.size() == 1) ? "1 car found." : carsArray.size() + " cars found."; supportActionBar.setTitle(title); } Log.i("Car Data", result.toString()); } else if (statusCode == 500) { final Toast toast = Toast.makeText(activity.getApplicationContext(), "A server internal error received. Ask your administrator.", Toast.LENGTH_LONG); toast.show(); supportActionBar.setTitle("Error: Server internal error."); } else { final Toast toast = Toast.makeText(activity.getApplicationContext(), "Error: Unable to connect to server.", Toast.LENGTH_LONG); toast.show(); supportActionBar.setTitle("Error: Not connected to server."); } } }); task.execute(url, "GET").get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }
From source file:com.layer.atlas.messenger.AtlasMessagesScreen.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.uiHandler = new Handler(); this.app = (MessengerApp) getApplication(); setContentView(R.layout.atlas_screen_messages); boolean convIsNew = getIntent().getBooleanExtra(EXTRA_CONVERSATION_IS_NEW, false); String convUri = getIntent().getStringExtra(EXTRA_CONVERSATION_URI); if (convUri != null) { Uri uri = Uri.parse(convUri);// w w w . j av a2s . c o m conv = app.getLayerClient().getConversation(uri); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(convUri.hashCode()); // Clear notifications for this Conversation } participantsPicker = (AtlasParticipantPicker) findViewById(R.id.atlas_screen_messages_participants_picker); participantsPicker.init(new String[] { app.getLayerClient().getAuthenticatedUserId() }, app.getParticipantProvider()); if (convIsNew) { participantsPicker.setVisibility(View.VISIBLE); } messageComposer = (AtlasMessageComposer) findViewById(R.id.atlas_screen_messages_message_composer); messageComposer.init(app.getLayerClient(), conv); messageComposer.setListener(new AtlasMessageComposer.Listener() { public boolean beforeSend(Message message) { boolean conversationReady = ensureConversationReady(); if (!conversationReady) return false; // push preparePushMetadata(message); return true; } }); messageComposer.registerMenuItem("Photo", new OnClickListener() { public void onClick(View v) { if (!ensureConversationReady()) return; Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); String fileName = "cameraOutput" + System.currentTimeMillis() + ".jpg"; photoFile = new File(getExternalFilesDir(android.os.Environment.DIRECTORY_PICTURES), fileName); final Uri outputUri = Uri.fromFile(photoFile); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri); if (debug) Log.w(TAG, "onClick() requesting photo to file: " + fileName + ", uri: " + outputUri); startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA); } }); messageComposer.registerMenuItem("Image", new OnClickListener() { public void onClick(View v) { if (!ensureConversationReady()) return; // in onCreate or any event where your want the user to select a file Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_CODE_GALLERY); } }); messageComposer.registerMenuItem("Location", new OnClickListener() { public void onClick(View v) { if (!ensureConversationReady()) return; if (lastKnownLocation == null) { Toast.makeText(v.getContext(), "Inserting Location: Location is unknown yet", Toast.LENGTH_SHORT).show(); return; } String locationString = "{\"lat\":" + lastKnownLocation.getLatitude() + ", \"lon\":" + lastKnownLocation.getLongitude() + "}"; MessagePart part = app.getLayerClient().newMessagePart(Atlas.MIME_TYPE_ATLAS_LOCATION, locationString.getBytes()); Message message = app.getLayerClient().newMessage(Arrays.asList(part)); preparePushMetadata(message); conv.send(message); if (debug) Log.w(TAG, "onSendLocation() loc: " + locationString); } }); messagesList = (AtlasMessagesList) findViewById(R.id.atlas_screen_messages_messages_list); messagesList.init(app.getLayerClient(), app.getParticipantProvider()); if (USE_QUERY) { Query<Message> query = Query.builder(Message.class) .predicate(new Predicate(Message.Property.CONVERSATION, Predicate.Operator.EQUAL_TO, conv)) .sortDescriptor(new SortDescriptor(Message.Property.POSITION, SortDescriptor.Order.ASCENDING)) .build(); messagesList.setQuery(query); } else { messagesList.setConversation(conv); } messagesList.setItemClickListener(new ItemClickListener() { public void onItemClick(Cell cell) { if (Atlas.MIME_TYPE_ATLAS_LOCATION.equals(cell.messagePart.getMimeType())) { String jsonLonLat = new String(cell.messagePart.getData()); JSONObject json; try { json = new JSONObject(jsonLonLat); double lon = json.getDouble("lon"); double lat = json.getDouble("lat"); Intent openMapIntent = new Intent(Intent.ACTION_VIEW); String uriString = String.format(Locale.ENGLISH, "geo:%f,%f?z=%d&q=%f,%f", lat, lon, 18, lat, lon); final Uri geoUri = Uri.parse(uriString); openMapIntent.setData(geoUri); if (openMapIntent.resolveActivity(getPackageManager()) != null) { startActivity(openMapIntent); if (debug) Log.w(TAG, "onItemClick() starting Map: " + uriString); } else { if (debug) Log.w(TAG, "onItemClick() No Activity to start Map: " + geoUri); } } catch (JSONException ignored) { } } else if (cell instanceof ImageCell) { Intent intent = new Intent(AtlasMessagesScreen.this.getApplicationContext(), AtlasImageViewScreen.class); app.setParam(intent, cell); startActivity(intent); } } }); typingIndicator = (AtlasTypingIndicator) findViewById(R.id.atlas_screen_messages_typing_indicator); typingIndicator.init(conv, new AtlasTypingIndicator.DefaultTypingIndicatorCallback(app.getParticipantProvider())); // location manager for inserting locations: this.locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); prepareActionBar(); }
From source file:com.nextgis.maplibui.activity.ModifyAttributesActivity.java
protected void createLocationPanelView(final IGISApplication app) { if (null == mGeometry && mFeatureId == NOT_FOUND) { mLatView = (TextView) findViewById(R.id.latitude_view); mLongView = (TextView) findViewById(R.id.longitude_view); mAltView = (TextView) findViewById(R.id.altitude_view); mAccView = (TextView) findViewById(R.id.accuracy_view); final ImageButton refreshLocation = (ImageButton) findViewById(R.id.refresh); mAccurateLocation = (SwitchCompat) findViewById(R.id.accurate_location); mAccurateLocation.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override/*from ww w . java 2 s . c om*/ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (mAccurateLocation.getTag() == null) { refreshLocation.performClick(); mAccurateLocation.setTag(new Object()); } } }); mAccuracyCE = (AppCompatSpinner) findViewById(R.id.accurate_ce); refreshLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { RotateAnimation rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); rotateAnimation.setDuration(500); rotateAnimation.setRepeatCount(1); refreshLocation.startAnimation(rotateAnimation); if (mAccurateLocation.isChecked()) { AlertDialog.Builder builder = new AlertDialog.Builder(ModifyAttributesActivity.this); View layout = View.inflate(ModifyAttributesActivity.this, R.layout.dialog_progress_accurate_location, null); TextView message = (TextView) layout.findViewById(R.id.message); final ProgressBar progress = (ProgressBar) layout.findViewById(R.id.progress); final TextView progressPercent = (TextView) layout.findViewById(R.id.progress_percent); final TextView progressNumber = (TextView) layout.findViewById(R.id.progress_number); final CheckBox finishBeep = (CheckBox) layout.findViewById(R.id.finish_beep); builder.setView(layout); builder.setTitle(R.string.accurate_location); final AccurateLocationTaker accurateLocation = new AccurateLocationTaker(view.getContext(), 100f, mMaxTakeCount, MAX_TAKE_TIME, PROGRESS_DELAY, (String) mAccuracyCE.getSelectedItem()); progress.setIndeterminate(true); message.setText(R.string.accurate_taking); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { accurateLocation.cancelTaking(); } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { accurateLocation.cancelTaking(); } }); builder.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { ControlHelper.unlockScreenOrientation(ModifyAttributesActivity.this); } }); final AlertDialog dialog = builder.create(); accurateLocation .setOnProgressUpdateListener(new AccurateLocationTaker.OnProgressUpdateListener() { @SuppressLint("SetTextI18n") @Override public void onProgressUpdate(Long... values) { int value = values[0].intValue(); if (value == 1) { progress.setIndeterminate(false); progress.setMax(mMaxTakeCount); } if (value > 0) progress.setProgress(value); progressPercent.setText(value * 100 / mMaxTakeCount + " %"); progressNumber.setText(value + " / " + mMaxTakeCount); } }); accurateLocation.setOnGetAccurateLocationListener( new AccurateLocationTaker.OnGetAccurateLocationListener() { @Override public void onGetAccurateLocation(Location accurateLocation, Long... values) { dialog.dismiss(); if (finishBeep.isChecked()) playBeep(); setLocationText(accurateLocation); } }); ControlHelper.lockScreenOrientation(ModifyAttributesActivity.this); dialog.setCanceledOnTouchOutside(false); dialog.show(); accurateLocation.startTaking(); } else if (null != app) { GpsEventSource gpsEventSource = app.getGpsEventSource(); Location location = gpsEventSource.getLastKnownLocation(); setLocationText(location); } } }); } else { //hide location panel ViewGroup rootView = (ViewGroup) findViewById(R.id.controls_list); rootView.removeView(findViewById(R.id.location_panel)); } }
From source file:samples.piggate.com.piggateCompleteExample.buyOfferActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_credit_card); //Set action bar fields getSupportActionBar().setTitle(PiggateUser.getEmail()); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); //Views/*from w ww . ja v a 2 s.c om*/ EditCardNumber = (EditText) findViewById(R.id.cardNumber); EditCVC = (EditText) findViewById(R.id.CVC); SpinnerYear = (Spinner) findViewById(R.id.spinerYear); SpinnerMonth = (Spinner) findViewById(R.id.spinerMonth); validate = (Button) findViewById(R.id.buttonValidate); buttonBuy = (Button) findViewById(R.id.buttonBuy); buttonCancel = (Button) findViewById(R.id.buttonCancel); headerLayout = (LinearLayout) findViewById(R.id.headerLayout); cardlayout = (LinearLayout) findViewById(R.id.cardlayout); buylayout = (LinearLayout) findViewById(R.id.buyLayout); image = (SmartImageView) findViewById(R.id.offerImage2); //Animations slidetoLeft = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slidetoleft); slidetoRight = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slidetoright); slidefromRight = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slidefromright); slidefromLeft = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slidefromleft); //Validation Error AlertDialog errorDialog = new AlertDialog.Builder(buyOfferActivity.this).create(); errorDialog.setTitle("Validation error"); errorDialog.setMessage("The credit card is not valid"); errorDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); //Network Error AlertDialog networkDialog = new AlertDialog.Builder(this).create(); networkDialog.setTitle("Network error"); networkDialog.setMessage("Network is not working"); networkDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); image.setImageUrl(getIntent().getExtras().getString("offerImgURL")); //Set the offer image from URL //(Provisional) set the default fields of the credit card EditCardNumber.setText("4242424242424242"); EditCVC.setText("123"); piggate = new Piggate(this); //Initialize Piggate Object //OnClick listener for the validate button validate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Validate the credit card with Stripe if (checkInternetConnection() == true) { // Credit card for testing: ("4242-4242-4242-4242", 12, 2016, "123") if (piggate.validateCard(EditCardNumber.getText().toString(), Integer.parseInt(SpinnerMonth.getSelectedItem().toString()), Integer.parseInt(SpinnerYear.getSelectedItem().toString()), EditCVC.getText().toString(), "pk_test_BN86VnxiMBHkZtzPmpykc56g", //Stripe test. Will be returned by requests in next release buyOfferActivity.this, "Validating", "Wait while the credit card is validated")) { openBuyLayout(); } else errorDialog.show(); } else { networkDialog.show(); } } }); //OnClick listener for the buy button buttonBuy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Do the buy request to the server RequestParams params = new RequestParams(); //Get the latest credit card Stripe token, amount to pay, type of coin and ID params.put("stripeToken", piggate.get_creditCards().get(piggate.get_creditCards().size() - 1) .getTokenID().toString()); params.put("amount", getIntent().getExtras().getString("offerPrice")); params.put("offerID", getIntent().getExtras().getString("offerID")); params.put("currency", getIntent().getExtras().getString("offerCurrency")); //Loading payment ProgressDialog loadingDialog = ProgressDialog.show(v.getContext(), "Payment", "Wait while the payment is finished", true); //Do the buy request to the server (The server do the payment with Stripe) piggate.RequestBuy(params).setListenerRequest(new Piggate.PiggateCallBack() { //onComplete method for JSONObject @Override public void onComplete(int statusCode, Header[] headers, String msg, JSONObject data) { loadingDialog.dismiss(); //Go back to the offer list passing the offer attributes (to exchange) Intent slideactivity = new Intent(buyOfferActivity.this, Activity_Logged.class); slideactivity.putExtra("offerID", getIntent().getExtras().getString("offerID")); slideactivity.putExtra("offerName", getIntent().getExtras().getString("offerName")); slideactivity.putExtra("offerDescription", getIntent().getExtras().getString("offerDescription")); slideactivity.putExtra("payment", true); slideactivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); Bundle bndlanimation = ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.slidefromleft, R.anim.slidetoright).toBundle(); startActivity(slideactivity, bndlanimation); } //onError method for JSONObject @Override public void onError(int statusCode, Header[] headers, String msg, JSONObject data) { //Show an error and go back to the credit card loadingDialog.dismiss(); //Go back to the offer list with the variable payment set to false (payment error) Intent slideactivity = new Intent(buyOfferActivity.this, Activity_Logged.class); slideactivity.putExtra("payment", false); slideactivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); Bundle bndlanimation = ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.slidefromleft, R.anim.slidetoright).toBundle(); startActivity(slideactivity, bndlanimation); } //onComplete method for JSONArray @Override public void onComplete(int statusCode, Header[] headers, String msg, JSONArray data) { loadingDialog.dismiss(); //Go back to the offer list passing the offer attributes (to exchange) Intent slideactivity = new Intent(buyOfferActivity.this, Activity_Logged.class); slideactivity.putExtra("offerID", getIntent().getExtras().getString("offerID")); slideactivity.putExtra("offerName", getIntent().getExtras().getString("offerName")); slideactivity.putExtra("offerDescription", getIntent().getExtras().getString("offerDescription")); slideactivity.putExtra("payment", true); slideactivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); Bundle bndlanimation = ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.slidefromleft, R.anim.slidetoright).toBundle(); startActivity(slideactivity, bndlanimation); } //onError method for JSONArray (Show an error and go back to the credit card) @Override public void onError(int statusCode, Header[] headers, String msg, JSONArray data) { //Show an error and go back to the credit card loadingDialog.dismiss(); //Go back to the offer list with the variable payment set to false (payment error) Intent slideactivity = new Intent(buyOfferActivity.this, Activity_Logged.class); slideactivity.putExtra("payment", false); slideactivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); Bundle bndlanimation = ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.slidefromleft, R.anim.slidetoright).toBundle(); startActivity(slideactivity, bndlanimation); } }).exec(); } }); //OnClick listener for the cancel button (Go back to the credit card) buttonCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { closeBuyLayout(); } }); }
From source file:com.feedhenry.armark.HelloFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = View.inflate(getActivity(), R.layout.hello_fragment, null); final TextView responseTextView = (TextView) view.findViewById(R.id.cloud_response); Button BtnUsuario = (Button) view.findViewById(R.id.BtnUsuario); BtnUsuario.setOnClickListener(new View.OnClickListener() { @Override/*from w ww .ja v a 2 s . co m*/ public void onClick(final View v) { responseTextView.setText(""); v.setEnabled(false); cloudCallUsuario(v, responseTextView); } }); //********************** Button BtnAlmacenes = (Button) view.findViewById(R.id.BtnAlmacenes); BtnAlmacenes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { responseTextView.setText(""); v.setEnabled(false); cloudCallAlmacenes(v, responseTextView); } }); //********************** Button BtnCategorias = (Button) view.findViewById(R.id.BtnCategorias); BtnCategorias.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { responseTextView.setText(""); v.setEnabled(false); cloudCallCategorias(v, responseTextView); } }); //********************** Button BtnPromociones = (Button) view.findViewById(R.id.BtnPromociones); BtnPromociones.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { responseTextView.setText(""); v.setEnabled(false); cloudCallPromociones(v, responseTextView); } }); //********************** Button BtnLogin = (Button) view.findViewById(R.id.BtnLogin); BtnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { responseTextView.setText(""); v.setEnabled(false); Intent myIntent = new Intent(view.getContext(), LoginActivity.class); startActivityForResult(myIntent, 0); } }); return view; }
From source file:com.example.pyrkesa.frag.User_Fragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setRetainInstance(true);/*from w w w . j av a 2s . c om*/ rootView = inflater.inflate(R.layout.user_fragment, container, false); userList = (ListView) rootView.findViewById(R.id.lt_user); // custom dialog final Dialog dialog = new Dialog(rootView.getContext()); d = dialog; userIcons = getResources().obtainTypedArray(R.array.userIcons);// load icons from userIcons1 = getResources().obtainTypedArray(R.array.userIcons1); userItems = new ArrayList<UserItem>(); adapter = new UserAdapter(getActivity(), userItems, getActivity()); userList.setAdapter(adapter); ImageButton addButton = (ImageButton) rootView.findViewById(R.id.add); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ModelFactory model = (ModelFactory) ModelFactory.getContext(); if (model.user.type == 1) { dialog.setContentView(R.layout.adduser_dialog); dialog.setTitle("Ajouter un utilisateur "); dialogTypes = getResources().getStringArray(R.array.user_type_dialog); // load Button dialogButtonOk = (Button) dialog.findViewById(R.id.button_ok); Button dialogButtonCancel = (Button) dialog.findViewById(R.id.button_cancel); final EditText Newlogin = (EditText) dialog.findViewById(R.id.dialogLogin); final EditText NewPW = (EditText) dialog.findViewById(R.id.dialogPW); final Spinner NewType = (Spinner) dialog.findViewById(R.id.dialogType); ArrayList<String> types = new ArrayList<String>(); for (String t : dialogTypes) { types.add(t); } NewType.setAdapter(new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_dropdown_item, types)); dialogButtonCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialogButtonOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ArrayList<String> temp = new ArrayList<String>(); String login = Newlogin.getText().toString(); String password = NewPW.getText().toString(); String type = NewType.getSelectedItem().toString(); if (login.equalsIgnoreCase("") && password.equalsIgnoreCase("") && type != null) { new AlertDialog.Builder(v.getContext()).setTitle("Attention") .setMessage("Veuillez remplir toutes les informations.").show(); } else { temp.add(login); temp.add(password); if (type.equalsIgnoreCase("admin")) { temp.add("1"); } else if (type.equalsIgnoreCase("utilisateur")) { temp.add("0"); } else { temp.add("0"); } } new addUser().execute(temp); } }); dialog.show(); } else { new AlertDialog.Builder(v.getContext()).setTitle("Attention") .setMessage("Opration interdite : Droits d'administration requis.").show(); } } }); // adding user items new LoadAllUser().execute(); return rootView; }
From source file:com.algo.hha.emojiicon.EmojiconsPopup.java
private View createCustomView() { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.emojicons, null, false); emojisPager = (ViewPager) view.findViewById(R.id.emojis_pager); emojisPager.setOnPageChangeListener(this); EmojiconRecents recents = this; mEmojisAdapter = new EmojisPagerAdapter( Arrays.asList(new EmojiconRecentsGridView(mContext, null, null, this), new EmojiconGridView(mContext, People.DATA, recents, this), new EmojiconGridView(mContext, Nature.DATA, recents, this), new EmojiconGridView(mContext, Objects.DATA, recents, this), new EmojiconGridView(mContext, Places.DATA, recents, this), new EmojiconGridView(mContext, Symbols.DATA, recents, this))); emojisPager.setAdapter(mEmojisAdapter); mEmojiTabs = new View[6]; mEmojiTabs[0] = view.findViewById(R.id.emojis_tab_0_recents); mEmojiTabs[1] = view.findViewById(R.id.emojis_tab_1_people); mEmojiTabs[2] = view.findViewById(R.id.emojis_tab_2_nature); mEmojiTabs[3] = view.findViewById(R.id.emojis_tab_3_objects); mEmojiTabs[4] = view.findViewById(R.id.emojis_tab_4_cars); mEmojiTabs[5] = view.findViewById(R.id.emojis_tab_5_punctuation); for (int i = 0; i < mEmojiTabs.length; i++) { final int position = i; mEmojiTabs[i].setOnClickListener(new OnClickListener() { @Override//w w w . ja v a 2 s . c om public void onClick(View v) { emojisPager.setCurrentItem(position); } }); } view.findViewById(R.id.emojis_backspace) .setOnTouchListener(new RepeatListener(1000, 50, new OnClickListener() { @Override public void onClick(View v) { if (onEmojiconBackspaceClickedListener != null) onEmojiconBackspaceClickedListener.onEmojiconBackspaceClicked(v); } })); // get last selected page mRecentsManager = EmojiconRecentsManager.getInstance(view.getContext()); int page = mRecentsManager.getRecentPage(); // last page was recents, check if there are recents to use // if none was found, go to page 1 if (page == 0 && mRecentsManager.size() == 0) { page = 1; } if (page == 0) { onPageSelected(page); } else { emojisPager.setCurrentItem(page, false); } return view; }
From source file:com.evandroid.musica.fragment.LyricsViewFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setRetainInstance(true);/*from w w w . j a v a2s. c om*/ setHasOptionsMenu(true); View layout = inflater.inflate(R.layout.lyrics_view, container, false); if (savedInstanceState != null) try { Lyrics l = Lyrics.fromBytes(savedInstanceState.getByteArray("lyrics")); if (l != null) this.mLyrics = l; mSearchQuery = savedInstanceState.getString("searchQuery"); mSearchFocused = savedInstanceState.getBoolean("searchFocused"); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } else { Bundle args = getArguments(); if (args != null) try { Lyrics lyrics = Lyrics.fromBytes(args.getByteArray("lyrics")); this.mLyrics = lyrics; if (lyrics != null && lyrics.getText() == null && lyrics.getArtist() != null) { String artist = lyrics.getArtist(); String track = lyrics.getTrack(); String url = lyrics.getURL(); fetchLyrics(artist, track, url); mRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.refresh_layout); startRefreshAnimation(); } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } if (layout != null) { Bundle args = savedInstanceState != null ? savedInstanceState : getArguments(); boolean screenOn = PreferenceManager.getDefaultSharedPreferences(getActivity()) .getBoolean("pref_force_screen_on", false); TextSwitcher textSwitcher = (TextSwitcher) layout.findViewById(R.id.switcher); textSwitcher.setFactory(new LyricsTextFactory(layout.getContext())); ActionMode.Callback callback = new CustomSelectionCallback(getActivity()); ((TextView) textSwitcher.getChildAt(0)).setCustomSelectionActionModeCallback(callback); ((TextView) textSwitcher.getChildAt(1)).setCustomSelectionActionModeCallback(callback); textSwitcher.setKeepScreenOn(screenOn); layout.findViewById(R.id.lrc_view).setKeepScreenOn(screenOn); TextView id3TV = (TextView) layout.findViewById(R.id.id3_tv); SpannableString text = new SpannableString(id3TV.getText()); text.setSpan(new UnderlineSpan(), 1, text.length() - 1, 0); id3TV.setText(text); final RefreshIcon refreshFab = (RefreshIcon) getActivity().findViewById(R.id.refresh_fab); refreshFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!mRefreshLayout.isRefreshing()) fetchCurrentLyrics(true); } }); FloatingActionButton fab = (FloatingActionButton) getActivity().findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent settingsIntent = new Intent(getActivity(), SettingsActivity.class); startActivity(settingsIntent); } }); if (args != null) refreshFab.setEnabled(args.getBoolean("refreshFabEnabled", true)); mScrollView = (NestedScrollView) layout.findViewById(R.id.scrollview); mRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.refresh_layout); TypedValue primaryColor = new TypedValue(); getActivity().getTheme().resolveAttribute(R.attr.colorPrimary, primaryColor, true); mRefreshLayout.setColorSchemeResources(primaryColor.resourceId, R.color.accent); float offset = getResources().getDisplayMetrics().density * 64; mRefreshLayout.setProgressViewEndTarget(true, (int) offset); mRefreshLayout.setOnRefreshListener(this); if (mLyrics == null) { if (!startEmtpy) fetchCurrentLyrics(false); } else if (mLyrics.getFlag() == Lyrics.SEARCH_ITEM) { mRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.refresh_layout); startRefreshAnimation(); if (mLyrics.getArtist() != null) fetchLyrics(mLyrics.getArtist(), mLyrics.getTrack()); } else //Rotation, resume update(mLyrics, layout, false); } if (broadcastReceiver == null) broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { searchResultLock = false; String artist = intent.getStringExtra("artist"); String track = intent.getStringExtra("track"); if (artist != null && track != null && mRefreshLayout.isEnabled()) { startRefreshAnimation(); new ParseTask(LyricsViewFragment.this, false, true).execute(mLyrics); } } }; return layout; }
From source file:com.android.calendar.EventInfoFragment.java
private void updateEvent(View view) { if (mEventCursor == null || view == null) { return;/* w w w . j a va 2s . c om*/ } Context context = view.getContext(); if (context == null) { return; } String eventName = mEventCursor.getString(EVENT_INDEX_TITLE); if (eventName == null || eventName.length() == 0) { eventName = getActivity().getString(R.string.no_title_label); } // 3rd parties might not have specified the start/end time when firing the // Events.CONTENT_URI intent. Update these with values read from the db. if (mStartMillis == 0 && mEndMillis == 0) { mStartMillis = mEventCursor.getLong(EVENT_INDEX_DTSTART); mEndMillis = mEventCursor.getLong(EVENT_INDEX_DTEND); if (mEndMillis == 0) { String duration = mEventCursor.getString(EVENT_INDEX_DURATION); if (!TextUtils.isEmpty(duration)) { try { Duration d = new Duration(); d.parse(duration); long endMillis = mStartMillis + d.getMillis(); if (endMillis >= mStartMillis) { mEndMillis = endMillis; } else { Log.d(TAG, "Invalid duration string: " + duration); } } catch (DateException e) { Log.d(TAG, "Error parsing duration string " + duration, e); } } if (mEndMillis == 0) { mEndMillis = mStartMillis; } } } mAllDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0; String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION); String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION); String rRule = mEventCursor.getString(EVENT_INDEX_RRULE); String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE); mHeadlines.setBackgroundColor(mCurrentColor); // What if (eventName != null) { setTextCommon(view, R.id.title, eventName); } // When // Set the date and repeats (if any) String localTimezone = Utils.getTimeZone(mActivity, mTZUpdater); Resources resources = context.getResources(); String displayedDatetime = Utils.getDisplayedDatetime(mStartMillis, mEndMillis, System.currentTimeMillis(), localTimezone, mAllDay, context); String displayedTimezone = null; if (!mAllDay) { displayedTimezone = Utils.getDisplayedTimezone(mStartMillis, localTimezone, eventTimezone); } // Display the datetime. Make the timezone (if any) transparent. if (displayedTimezone == null) { setTextCommon(view, R.id.when_datetime, displayedDatetime); } else { int timezoneIndex = displayedDatetime.length(); displayedDatetime += " " + displayedTimezone; SpannableStringBuilder sb = new SpannableStringBuilder(displayedDatetime); ForegroundColorSpan transparentColorSpan = new ForegroundColorSpan( resources.getColor(R.color.event_info_headline_transparent_color)); sb.setSpan(transparentColorSpan, timezoneIndex, displayedDatetime.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); setTextCommon(view, R.id.when_datetime, sb); } // Display the repeat string (if any) String repeatString = null; if (!TextUtils.isEmpty(rRule)) { EventRecurrence eventRecurrence = new EventRecurrence(); eventRecurrence.parse(rRule); Time date = new Time(localTimezone); date.set(mStartMillis); if (mAllDay) { date.timezone = Time.TIMEZONE_UTC; } eventRecurrence.setStartDate(date); repeatString = EventRecurrenceFormatter.getRepeatString(mContext, resources, eventRecurrence, true); } if (repeatString == null) { view.findViewById(R.id.when_repeat).setVisibility(View.GONE); } else { setTextCommon(view, R.id.when_repeat, repeatString); } // Organizer view is setup in the updateCalendar method // Where if (location == null || location.trim().length() == 0) { setVisibilityCommon(view, R.id.where, View.GONE); } else { final TextView textView = mWhere; if (textView != null) { textView.setAutoLinkMask(0); textView.setText(location.trim()); try { textView.setText(Utils.extendedLinkify(textView.getText().toString(), true)); // Linkify.addLinks() sets the TextView movement method if it finds any links. // We must do the same here, in case linkify by itself did not find any. // (This is cloned from Linkify.addLinkMovementMethod().) MovementMethod mm = textView.getMovementMethod(); if ((mm == null) || !(mm instanceof LinkMovementMethod)) { if (textView.getLinksClickable()) { textView.setMovementMethod(LinkMovementMethod.getInstance()); } } } catch (Exception ex) { // unexpected Log.e(TAG, "Linkification failed", ex); } textView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { try { return v.onTouchEvent(event); } catch (ActivityNotFoundException e) { // ignore return true; } } }); } } // Description if (description != null && description.length() != 0) { mDesc.setText(description); } // Launch Custom App if (Utils.isJellybeanOrLater()) { updateCustomAppButton(); } }