How to set Min text (Mandatory) and Max text in EditText - java

In my EditText field, I want to give some min text as mandatory and max text as the limit, is there any way to achieve that?
If one is to type text, the numeric count has to decrease. How would I do that?
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="24dp"
android:maxLength="175"
android:ems="10" />
this is my adding activity.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
System.out.println(PRAYER_CATEGORY.length);
tvPrayer = (TextView) findViewById(R.id.mystate);
spinnerPrayers = (Spinner) findViewById(R.id.spinnerstate);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, PRAYER_CATEGORY);
adapter_state
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerPrayers.setAdapter(adapter_state);
value=(EditText)findViewById(R.id.editText1);
value
.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
if (value.getText().toString().trim()
.length() < 3) {
value.setError("Failed");
} else {
value.setError(null);
}
}
else {
if (value.getText().toString().trim()
.length() < 3) {
value.setError("Failed");
} else {
value.setError(null);
}
}
}
});
btnSpeakprayer = (ImageButton) findViewById(R.id.btnSpeakprayer);
btn=(Button)findViewById(R.id.button1);
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
btn.setOnClickListener(this);

You can try this code
First of all you set your maxlength in xml file like this
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:inputType="textPassword"
android:lines="1"
android:maxLength="15"
android:maxLines="1"
android:singleLine="true" />
Then in your code you can write like this
et_billamt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
if (et_billamt.getText().toString().trim().length() < 5) {
et_billamt.setError("Failed");
} else {
// your code here
et_billamt.setError(null);
}
} else {
if (et_billamt.getText().toString().trim().length() < 5) {
et_billamt.setError("Failed");
} else {
// your code here
et_billamt.setError(null);
}
}
}
});
I designed if after no focus, so here you can write for min length condition and max length condition

Change your code TO this:
instead of value.getText().trim().length() try using value.getText().length()<3
value.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
if (value.getText().toString().trim().length() < 3)
value.setError("Failed");
else
value.setError(null);
}
}
});

Try this
EditText value =(EditText) findviewbyId(R.id.urEditTextId);// this line must be oncreate
// place these line where u want to check
String ed1=value .getText().toString();
int size=ed1.length();
you can match the digit and perform appropriate action
if(size==0)
//Toast : kindly enter atleast one letter
if(size>175)
//Toast : max length 175 char

you can extend the EditText class, and override the onTextChanged method to monitor the text length change by yourself. Then you can control the limitation.
public class CustomEditText extends EditText{
public CustomEditText(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
#Override
protected void onTextChanged(CharSequence text, int start,
int lengthBefore, int lengthAfter) {
// TODO Auto-generated method stub
Log.i("length", "input text length = " + text.length());
super.onTextChanged(text, start, lengthBefore, lengthAfter);
}
}

Here's an EditText and a Button:
EditText myEditText;
Button button;
In your onCreate():
myEditText = (EditText) findViewById(R.id.edittext);
button = (Button) findViewById(R.id.button);
Say you submit or use the value that a user types in the myEditText using the button. Set an 'OnClickListener' to this button:
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mEditText.length() < 1 ||
mEditText.length() > 175) {
mEditText.setError("Value should be between 1 and 175 characters in length");
mEditText.requestFocus();
} else {
// Value is valid (between 1 and 175 characters long)
String text = mEditText.getText().toString();
// submit
}
}
});

Related

Parsing user input in edittext field of the type date and check for correct date format

I am working on an Android app and processing user input from an edittext field. I want to check if the user entered a correct date format; however, for reasons that I don´t understand, I need to convert the type of the edittext type date to a string and then convert it back to a float number, to check against a regular expression and that is not working correctly.
The editactivity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/et_normal_text"
android:hint="Enter the title of your selfie"
android:inputType="text"
android:textStyle="bold"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/et_name"
android:hint="Enter the title of your selfie"
android:inputType="text"
android:textStyle="bold"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/name"
android:hint="Enter the title of your selfie"
android:inputType="text"
android:textStyle="bold"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/et_location"
android:hint="Enter the title of your selfie"
android:inputType="text"
android:textStyle="bold"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/et_email_address"
android:textStyle="bold"
android:inputType="textEmailAddress"
android:hint="Enter Email Address"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/ed_date"
android:hint="Enter Date"
android:inputType="date"
android:textStyle="bold"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/location"
android:hint="Enter Location"
android:inputType="textAutoComplete"
android:textStyle="bold"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:id="#+id/btn_submit" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="106dp"
android:padding="1dp"
android:layout_weight="0.98"></ImageView>
<Button
android:id="#+id/btnCapture"
android:layout_width="135dp"
android:layout_height="wrap_content"
android:text="Take picture" />
<Button
android:id="#+id/save"
android:layout_width="135dp"
android:layout_height="wrap_content"
android:text="Save" />
<Button
android:id="#+id/cancel"
android:layout_width="135dp"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Cancel" />
<Button
android:id="#+id/image"
android:layout_width="135dp"
android:layout_height="wrap_content"
android:text="See Image" />
</LinearLayout>
The EditActivity:
package gmbh.packagename.myselfieme;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.icu.util.Calendar;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import static gmbh.packagename.myselfieme.R.drawable.marker;
import static gmbh.packagename.myselfieme.R.id.date;
import static gmbh.packagename.myselfieme.R.id.time;
import static gmbh.packagename.myselfieme.R.string.snippet;
public class EditActivity extends Activity {
public static int count = 0;
static final int REQUEST_TAKE_PHOTO = 1;
private static final String KEY_MARKER_ID = "id";
private static final String KEY_MARKER_TITLE = "title";
private static final String KEY_MARKER_DATE = "date";
private static final String KEY_MARKER_LOC = "location";
private static final String KEY_MARKER_LAT = "latlng";
private static final String KEY_MARKER_NAME = "name";
private static final String KEY_MARKER_PIC = "picture";
private static final int CAMERA_REQUEST = 1888;
private EditText etNormalText;
private EditText etName;
private EditText etLocation;
private EditText etEmailAddrss;
private EditText etDate;
private Button btnSubmit;
private ImageView imageView;
Bitmap photo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editactivity);
PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(this);
helper.getReadableDatabase();
registerViews();
this.imageView = (ImageView) this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.btnCapture);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
private void registerViews() {
etNormalText = (EditText) findViewById(R.id.et_normal_text);
etName = (EditText) findViewById(R.id.et_name);
etLocation = (EditText) findViewById(R.id.et_location);
// TextWatcher would let us check validation error on the fly
etNormalText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
Validation.hasText(etNormalText);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
etName.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
Validation.hasText(etName);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
etLocation.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
Validation.hasText(etLocation);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
etEmailAddrss = (EditText) findViewById(R.id.et_email_address);
etEmailAddrss.addTextChangedListener(new TextWatcher() {
// after every change has been made to this editText, we would like to check validity
public void afterTextChanged(Editable s) {
Validation.isEmailAddress(etEmailAddrss, true);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
etDate = (EditText) findViewById(R.id.ed_date);
etDate.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
Validation.isDate(etDate, false);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
btnSubmit = (Button) findViewById(R.id.btn_submit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.w("EditActivity", "clicking on btn_submit");
/*
Validation class will check the error and display the error on respective fields
but it won't resist the form submission, so we need to check again before submit
*/
if ( checkValidation () )
submitForm();
else
Toast.makeText(EditActivity.this, "Form contains error", Toast.LENGTH_LONG).show();
}
});
final LatLng latlng = getIntent().getParcelableExtra("location");
final EditText title = (EditText) findViewById(R.id.title);
final EditText date = (EditText) findViewById(R.id.ed_date);
final EditText location = (EditText) findViewById(R.id.location);
final EditText name = (EditText) findViewById(R.id.name);
Button button = (Button) findViewById(R.id.save);
Button cancelbutton = (Button) findViewById(R.id.cancel);
Button imagebutton = (Button) findViewById(R.id.image);
imagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(EditActivity.this, ImageActivity.class);
myIntent.putExtra("marker", marker);
myIntent.putExtra("BitmapImage", photo);
EditActivity.this.startActivity(myIntent);
setResult(Activity.RESULT_OK, myIntent);
}
});
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(date.getText().length()<1){
// Display toast
Toast.makeText(getApplicationContext(), "Please enter something !",Toast.LENGTH_LONG).show();
}
}
});
date.addTextChangedListener(new TextWatcher(){
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
if(date.getText().length()<1){
// Display toast
Toast.makeText(getApplicationContext(), "Please enter something !",Toast.LENGTH_LONG).show();
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
//String ss = date.getText().toString();
int o = 0;
//String regEx ="^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d{2}$";
/*
if ((ss.charAt(2) == '/') && (ss.charAt(4) == '/')) {
}*/
int ss = date.getInputType();
if (ss == (InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_DATE))
{
int dateInput = Integer.parseInt(date.getText().toString());
//(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)
Toast.makeText(EditActivity.this, "Format Is right", Toast.LENGTH_LONG).show();
}
/* if (ss.matches("\\d{4}-\\d{2}-\\d{2}")) {
Toast.makeText(EditActivity.this, "Format Is right", Toast.LENGTH_LONG).show();
}*/
/*if(date.getText().length()<4){
// Display toast
Toast.makeText(getApplicationContext(), "Please enter something !",Toast.LENGTH_LONG).show();
}*/
else {
date.setTextColor(Color.RED);
date.setText("Invalid Format");
}
//ss = "";
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
Bitmap resized = Bitmap.createScaledBitmap(photo, (int) (photo.getWidth() * 0.5), (int) (photo.getHeight() * 0.5), true);
//Bitmap.Config conf = Bitmap.Config.ARGB_8888;
//Bitmap bmp = Bitmap.createBitmap(150, 150, conf);
Canvas canvas1 = new Canvas();
Rect rectangle = new Rect(0,0,100,100);
canvas1.drawBitmap(resized, new Rect(0,0,100,100), rectangle, null);
resized = addBorderToBitmap(resized, 10, Color.WHITE);
// Add a border around the bitmap as shadow
resized = addBorderToBitmap(resized, 3, Color.LTGRAY);
MarkerOptions marker = new MarkerOptions().position(latlng)
.icon(BitmapDescriptorFactory.fromBitmap(resized))
.draggable(true);
if (title.getText() != null) {
marker.title(title.getText().toString());
}
if( date.getText().toString().length() == 0 )
date.setError( "date is required!" );
marker.snippet(date.getText().toString());
if (name.getText() !=null) {
marker.snippet(name.getText().toString());
}
if (location.getText() !=null) {
marker.snippet(location.getText().toString());
}
Intent resultIntent = new Intent();
resultIntent.putExtra("marker", marker);
resultIntent.putExtra("BitmapImage", photo); // passing the bitmap to the next activity . and retrieve it to the next activity
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
});}
public static Bitmap overlay(Bitmap bmp, Bitmap resized) {
Bitmap bmOverlay = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp, new Matrix(), null);
canvas.drawBitmap(resized, 0, 0, null);
return bmOverlay;
}
private void submitForm() {
// Submit your form here. your form is valid
Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
Log.w("EditActivity", "submitForm");
}
private boolean checkValidation() {
Log.w("EditActivity", "checkValidation");
boolean ret = true;
if (!Validation.hasText(etNormalText)) ret = false;
if (!Validation.isEmailAddress(etEmailAddrss, true)) ret = false;
if (!Validation.isDate(etDate, false)) ret = false;
return ret;
}
public void onClick(View v) {
// TODO:
// Launch Activity Two
// Hint: use Context's startActivity() method
// Create an intent stating which Activity you would like to start
Intent myIntent = new Intent(EditActivity.this, MapsActivity.class);
// Launch the Activity using the intent
EditActivity.this.startActivity(myIntent);
}
protected Bitmap addBorderToBitmap(Bitmap resized, int borderWidth, int borderColor) {
// Initialize a new Bitmap to make it bordered bitmap
Bitmap dstBitmap = Bitmap.createBitmap(
resized.getWidth() + borderWidth * 2, // Width
resized.getHeight() + borderWidth * 2, // Height
Bitmap.Config.ARGB_8888 // Config
);
/*
Canvas
The Canvas class holds the "draw" calls. To draw something, you need 4 basic
components: A Bitmap to hold the pixels, a Canvas to host the draw calls (writing
into the bitmap), a drawing primitive (e.g. Rect, Path, text, Bitmap), and a paint
(to describe the colors and styles for the drawing).
*/
// Initialize a new Canvas instance
Canvas canvas = new Canvas(dstBitmap);
// Initialize a new Paint instance to draw border
Paint paint = new Paint();
paint.setColor(borderColor);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(borderWidth);
paint.setAntiAlias(true);
Rect rect = new Rect(
borderWidth / 2,
borderWidth / 2,
canvas.getWidth() - borderWidth / 2,
canvas.getHeight() - borderWidth / 2
);
// Draw a rectangle as a border/shadow on canvas
canvas.drawRect(rect, paint);
// Draw source bitmap to canvas
canvas.drawBitmap(resized, borderWidth, borderWidth, null);
resized.recycle();
// Return the bordered circular bitmap
return dstBitmap;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
this.imageView.setImageBitmap(photo);
}
}
}
The problem is in this snippet of code here:
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
//String ss = date.getText().toString();
int o = 0;
//String regEx ="^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d{2}$";
/*
if ((ss.charAt(2) == '/') && (ss.charAt(4) == '/')) {
}*/
int ss = date.getInputType();
if (ss == (InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_DATE))
{
int dateInput = Integer.parseInt(date.getText().toString());
//(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)
Toast.makeText(EditActivity.this, "Format Is right", Toast.LENGTH_LONG).show();
}
/* if (ss.matches("\\d{4}-\\d{2}-\\d{2}")) {
Toast.makeText(EditActivity.this, "Format Is right", Toast.LENGTH_LONG).show();
}*/
/*if(date.getText().length()<4){
// Display toast
Toast.makeText(getApplicationContext(), "Please enter something !",Toast.LENGTH_LONG).show();
}*/
else {
date.setTextColor(Color.RED);
date.setText("Invalid Format");
}
//ss = "";
}
});
This is the validation.java:
package gmbh.package.myselfieme;
import android.widget.EditText;
import java.util.regex.Pattern;
public class Validation {
// Regular Expression
// you can change the expression based on your need
private static final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private static final String DATE_REGEX = "^\\d{4}-\\d{2}-\\d{2}$";
// Error Messages
private static final String REQUIRED_MSG = "required";
private static final String EMAIL_MSG = "invalid email";
private static final String DATE_MSG = "###-#######";
// call this method when you need to check email validation
public static boolean isEmailAddress(EditText editText, boolean required) {
return isValid(editText, EMAIL_REGEX, EMAIL_MSG, required);
}
// call this method when you need to check phone number validation
public static boolean isDate(EditText editText, boolean required) {
return isValid(editText, DATE_REGEX, DATE_MSG, required);
}
// return true if the input field is valid, based on the parameter passed
public static boolean isValid(EditText editText, String regex, String errMsg, boolean required) {
String text = editText.getText().toString().trim();
// clearing the error, if it was previously set by some other values
editText.setError(null);
// text required and editText is blank, so return false
if ( required && !hasText(editText) ) return false;
// pattern doesn't match so returning false
if (required && !Pattern.matches(regex, text)) {
editText.setError(errMsg);
return false;
};
return true;
}
// check the input field has any text or not
// return true if it contains text otherwise false
public static boolean hasText(EditText editText) {
String text = editText.getText().toString().trim();
editText.setError(null);
// length 0 means there is no text
if (text.length() == 0) {
editText.setError(REQUIRED_MSG);
return false;
}
return true;
}
}
This is the error message:
Process: gmbh.packagename.myselfieme, PID: 17795
java.lang.NumberFormatException: Invalid int: "2505250525"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:413)
at java.lang.Integer.parseInt(Integer.java:367)
at java.lang.Integer.parseInt(Integer.java:334)
at gmbh.packagename.myselfieme.EditActivity$10.afterTextChanged(EditActivity.java:203)
Actually, why do I need to read the input in an input type of date, cast it to an integer and check if this integer value has the right format? Isn`t there any other, better way? I just want to check that the users does not enter more than 6 digits and that these digits have the right format.
Any hints or help would be appreciated, thanks!
I just want to check that the users does not enter more than 6 digits and that these digits have the right format.
Lets say, required format is dd-mm-yy
Use regex - \d{2}-\d{2}-\d{2}
For example,
if (inputSTR.matches("\\d{2}-\\d{2}-\\d{2}")) {
// input matches to required pattern
} else {
// Show error msg
}
First, Tim Biegeleisen’s comment that you should use a date picker rather than an EditText is probably well worth considering.
Anyway, if you get your date as a string, the recommended way of validating it is to try to parse it into a date and see if you succeed — not through a regular expression. And you certainly shouldn’t try to parse it as an integer, that is bound to fail. My code would go something like:
String ss = date.getText().toString();
if (ss.isEmpty()) {
// tell the user to enter something
} else {
try {
LocalDate.parse(ss);
// tell the user the format is right
} catch (DateTimeParseException dtpe) {
// tell the user that this is not a valid date
}
}
I am assuming that your date should be in the format yyyy-MM-dd. This is the default parse format for LocalDate, so it’s rather straightforward if you know about exceptions and try/catch constructs. If you require a different format, you will need to specify it through a DateTimeFormatter.
The advantage over the regex approach is it gives you much better validation. ^\\d{4}-\\d{2}-\\d{2}$ will accept 2017-29-11 and 2017-11-92 as dates, where the parsing approach will catch if the month is not 1 through 12 or the day-of-month is not within the number of days in that month.
Now you are at it, if you need to keep your date (likely since you asked the user to enter it), keep it as a LocalDate object rather than a string. This will prepare your app for doing all sorts of operations on the date. Whenever you need a string, just use LocalDate.toString(). Or use a DateTimeFormatter if you want the string as for example “Sunday November 19, 2017” or even in German or some other language.
I am using java.time, the modern Java date and time API also known as JSR-310. Unfortunately this doesn’t come with most Android devices yet. The solution is the ThreeTenABP, the backport of JSR-310 to Android. I encourage you to get this and start coding.

EditText cursor visible even if the EditText is not editable

I need to introduce data in an EditText but i want to use an virtual keyboard, not the android keyboard. If I use setKeyListener(null) the cursor is invisible even after using setCursorVisible(true).
Is it possible to make an EditText where even if it isn't editable the cursor is visible ?
EDIT 2 :
I found an partial method to do that, but it's not working when i'm double taping the EditText.
I made an setOnClickListner() and an setOnLongClickListner() method for the EditText. In this methods I hide the Soft Input from the Window, also i use setTextIsSelectable(false). My only problem is that when I double tap the EditText the soft input keyboard shows and I dont know how to hide it, I tried to use android:windowSoftInputMode="stateAlwaysHidden" in manifest, but it doesn't work either.
EDIT :
Here is the code that I'm using at this moment for my base converter calculator.
public class MainActivity extends AppCompatActivity {
EditText number;
EditText base;
boolean baseB = false;
String numberS = "0";
String baseS = "10";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
//make the EditText for number and base not editable
number = (EditText) findViewById(R.id.number);
number.setKeyListener(null);
base = (EditText) findViewById(R.id.base);
base.setKeyListener(null);
//... more code here (changing fonts for each EditText and changing status bar color
}
// I have a function for each button all are the same
public void onClickBaseChange(View v) {
if (baseB) {
baseB = false;
// i use toasts at this moment to know when i'm on number or base field
Toast.makeText(this, "Number", Toast.LENGTH_SHORT).show();
} else {
baseB = true;
Toast.makeText(this, "Base", Toast.LENGTH_SHORT).show();
}
}
public void onClickB0(View v) {
if (numberS.length() > 0 && !numberS.equals("0") && !baseB) {
numberS += "0";
number = (EditText) findViewById(R.id.number);
number.setText(numberS, TextView.BufferType.EDITABLE);
number.setSelection(numberS.length());
} else {
if (Integer.valueOf(baseS) >= 1) {
baseS += "0";
base = (EditText) findViewById(R.id.base);
base.setText(baseS, TextView.BufferType.EDITABLE);
}
}
}
public void onClickB1(View v) {
if (numberS.equals("0")) {
numberS = "1";
} else {
numberS += "1";
}
number = (EditText) findViewById(R.id.number);
number.setText(numberS, TextView.BufferType.EDITABLE);
number.requestFocus();
number.setSelection(numberS.length());
}
And the xml looks like this :
<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/colorBackground"
tools:context="manastur.calculator.MainActivity">
<EditText
android:id="#+id/base"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:layout_marginTop="120dp"
android:background="#android:color/transparent"
android:cursorVisible="true"
android:text=""
android:textColor="#color/text"
android:textSize="30dp" />
<EditText
android:id="#+id/number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="50dp"
android:background="#android:color/transparent"
android:cursorVisible="true"
android:text=""
android:textColor="#color/text"
android:textSize="50dp" />
<LinearLayout
android:id="#+id/secondRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/firstRow"
android:layout_centerHorizontal="true">
<Button
android:id="#+id/b1"
android:layout_width="85dp"
android:layout_height="85dp"
android:background="#drawable/b1"
android:onClick="onClickB1" />
<Button
android:id="#+id/b2"
android:layout_width="85dp"
android:layout_height="85dp"
android:background="#drawable/b2"
android:onClick="onClickB2" />
<!-- from this point on is the same, there are 5 LinearLayouts which
represents the 5 rows of button of the num pad -->
Use this code to achieve that,
While develop I took reference from native Dialpad code
KeypadlessKeypad.java
import android.content.Context;
import android.graphics.Rect;
import android.support.v4.view.MotionEventCompat;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class KeypadlessKeypad extends EditText {
private static final Method mShowSoftInputOnFocus = getSetShowSoftInputOnFocusMethod(
EditText.class, "setShowSoftInputOnFocus", boolean.class);
public static Method getSetShowSoftInputOnFocusMethod(Class<?> cls, String methodName, Class<?>... parametersType) {
Class<?> sCls = cls.getSuperclass();
while (sCls != Object.class) {
try {
return sCls.getDeclaredMethod(methodName, parametersType);
} catch (NoSuchMethodException e) {
// Just super it again
}
sCls = sCls.getSuperclass();
}
return null;
}
private Context mContext;
/**
* Listener for Copy, Cut and Paste event
* Currently callback only for Paste event is implemented
*/
private OnEditTextActionListener mOnEditTextActionListener;
public KeypadlessKeypad(Context context) {
super(context);
mContext = context;
init();
}
public KeypadlessKeypad(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init();
}
public KeypadlessKeypad(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
mContext = context;
init();
}
#Override
protected void onSelectionChanged(int selStart, int selEnd) {
super.onSelectionChanged(selStart, selEnd);
}
public final void appendText(CharSequence text) {
append(text, 0, text.length());
}
/***
* Initialize all the necessary components of TextView.
*/
private void init() {
setSingleLine(true);
synchronized (this) {
setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
setFocusableInTouchMode(true);
}
reflexSetShowSoftInputOnFocus(false); // Workaround.
// Ensure that cursor is at the end of the input box when initialized. Without this, the
// cursor may be at index 0 when there is text added via layout XML.
setSelection(getText().length());
}
#Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
hideKeyboard();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
final boolean ret = super.onTouchEvent(event);
// Must be done after super.onTouchEvent()
hideKeyboard();
return ret;
}
private void hideKeyboard() {
final InputMethodManager imm = ((InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE));
if (imm != null && imm.isActive(this)) {
imm.hideSoftInputFromWindow(getApplicationWindowToken(), 0);
}
}
private void reflexSetShowSoftInputOnFocus(boolean show) {
if (mShowSoftInputOnFocus != null) {
invokeMethod(mShowSoftInputOnFocus, this, show);
} else {
// Use fallback method. Not tested.
hideKeyboard();
}
}
public static Object invokeMethod(Method method, Object receiver, Object... args) {
try {
return method.invoke(receiver, args);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
return null;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int textViewWidth = View.MeasureSpec.getSize(widthMeasureSpec);
int height = getMeasuredHeight();
this.setMeasuredDimension(textViewWidth, height);
}
#Override
protected void onTextChanged(CharSequence text, int start, int before,
int after) {
super.onTextChanged(text, start, before, after);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
}
#Override
public boolean onTextContextMenuItem(int id) {
boolean consumed = super.onTextContextMenuItem(id);
switch (id) {
case android.R.id.paste:
if (mOnEditTextActionListener != null) {
mOnEditTextActionListener.onPaste();
}
break;
}
return consumed;
}
/**
* Setter method for {#link #mOnEditTextActionListener}
*
* #param onEditTextActionListener
* Instance of the {#link OnEditTextActionListener}
*/
public void setOnEditTextActionListener(OnEditTextActionListener onEditTextActionListener) {
this.mOnEditTextActionListener = onEditTextActionListener;
}
private Rect mRect = new Rect();
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
final int action = MotionEventCompat.getActionMasked(event);
int[] location = new int[2];
getLocationOnScreen(location);
mRect.left = location[0];
mRect.top = location[1];
mRect.right = location[0] + getWidth();
mRect.bottom = location[1] + getHeight();
int x = (int) event.getX();
int y = (int) event.getY();
if (action == MotionEvent.ACTION_DOWN && !mRect.contains(x, y)) {
InputMethodManager input = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
input.hideSoftInputFromWindow(getWindowToken(), 0);
}
return super.dispatchTouchEvent(event);
}
#Override
public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED) {
// Since we're replacing the text every time we add or remove a
// character, only read the difference. (issue 5337550)
final int added = event.getAddedCount();
final int removed = event.getRemovedCount();
final int length = event.getBeforeText().length();
if (added > removed) {
event.setRemovedCount(0);
event.setAddedCount(1);
event.setFromIndex(length);
} else if (removed > added) {
event.setRemovedCount(1);
event.setAddedCount(0);
event.setFromIndex(length - 1);
} else {
return;
}
} else if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED) {
// The parent EditText class lets tts read "edit box" when this View has a focus, which
// confuses users on app launch (issue 5275935).
return;
}
super.sendAccessibilityEventUnchecked(event);
}
/**
* Interface to get callback from the Edittext copy, cut and paste event
* For time being only the Paste Event callback is generated
*/
public interface OnEditTextActionListener {
/**
* If Edittext get paste event then this method will be called
*/
void onPaste();
}
}
In your xml you can give like this,
<[package name].KeypadlessKeypad
android:id="#+id/dialnumbertv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00000000"
android:cursorVisible="false"
android:ellipsize="start"
android:gravity="center"
android:inputType="phone"
android:singleLine="true"
android:textIsSelectable="true"
android:textSize="30sp"
android:textStyle="italic"
android:visibility="visible"/>
And in your fragment you can implement like this,
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mDialNumbertv = view.findViewById(R.id.dialnumbertv);
mDialNumbertv.setCursorVisible(false);
mDialNumbertv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isDigitsEmpty()) {
mDialNumbertv.setCursorVisible(true);
}
}
});
mDialNumbertv.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) {
}
#Override
public void afterTextChanged(Editable s) {
if (isDigitsEmpty()) {
mDialNumbertv.setCursorVisible(false);
}
// updateDeleteButton();
}
});
mDialNumbertv.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Ref https://android.googlesource.com/platform/packages/apps/Contacts/+/39948dc7e34dc2041b801058dada28fedb80c388/src/com/android/contacts/dialpad/DialpadFragment.java
// Right now EditText does not show the "paste" option when cursor is not visible.
// To show that, make the cursor visible, and return false, letting the EditText
// show the option by itself.
mDialNumbertv.setCursorVisible(true);
return false;
}
});
mDialNumbertv.setOnEditTextActionListener(
new KeypadlessKeypad.OnEditTextActionListener() {
#Override
public void onPaste() {
// If some content pasted on mDialNumbertv
// we need to run some search on Contact and Price
String mobileNumber = mDialNumbertv.getText().toString();
if (TextUtils.isEmpty(mobileNumber)) {
return;
}
// updateContactName(mobileNumber);
}
});
}
private KeypadlessKeypad mDialNumbertv;
private boolean isDigitsEmpty() {
return mDialNumbertv.length() == 0;
}
private void setClickedDigit(final String digitToSet) {
if (!TextUtils.isEmpty(digitToSet)) {
char digit = digitToSet.charAt(0);
String mobileNumber = mDialNumbertv.getText() + digitToSet;
mDialNumbertv.getText().insert(mDialNumbertv.getSelectionStart(), digitToSet);
// If the cursor is at the end of the text we hide it.
final int length = mDialNumbertv.length();
if (length == mDialNumbertv.getSelectionStart() && length == mDialNumbertv.getSelectionEnd()) {
mDialNumbertv.setCursorVisible(false);
}
}
}
I wanted the same behavior which I achieved as follows -
Make a custom class that will override 2 methods of AppCompatEditText.
class CustomEditText(context: Context?, attrs: AttributeSet) : AppCompatEditText(context, attrs) {
override fun onCheckIsTextEditor(): Boolean {
return true
}
override fun isTextSelectable(): Boolean {
return true
}
}
In the XML file, create EditText using this custom view.
<com.ui.custom.CustomEditText
android:id="#+id/et_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="none"
android:focusable="true"
android:gravity="center"
android:focusableInTouchMode="true"/>
Now, just add onFocusChangeListener and set editText.setKeyListener = null.
binding.etEmail.onFocusChangeListener = OnFocusChangeListener { v, hasFocus ->
if (hasFocus) {
binding.etEmail.keyListener = null
}
}
You can add the same on onTouch if that is the requirement.
The main issue here is that onCheckIsTextEditor() of View class always returns false, which leads to cursor never blinking or being visible even if setCursorVisible(true) was called in code.
I hope it helps.
You can use edittext.setselection(0)
or
maybe you can request focus using requestfocus()

Android app - Inputting integers from buttons depending on number of presses

I'm writing a calculator app for android using android studio. I want to used 4 buttons for inputting values and functions. However the way I am currently doing it takes the input from the text written on the button. So for my button 1/2/3 when this is pressed 1/2/3 is passed to the textView.
Below is my MainActivity:
package com.example.myfirstapp;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MediaController;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private int[] operatorButtons = {R.id.operators};
private int[] numericButtons = {R.id.onetwothree, R.id.fourfivesix, R.id.seveneightninezero};
private boolean lastNumeric, stateError;
private TextView txtScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (TextView) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
setOperatorOnClickListener();
}
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
lastNumeric = false;
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
// Equal button
/*findViewById(R.id.btnEqual).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqual();
}
});*/
}
}
and my activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtScreen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="right|center_vertical"
android:maxLength="16"
android:padding="10dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30sp"
android:typeface="serif" />
<!--<Button-->
<!--android:id="#+id/equal1"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="100dp"-->
<!--android:text="="-->
<!--/>-->
<Button
android:id="#+id/equal2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="="
android:layout_alignParentBottom="true"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/txtScreen"
android:orientation="vertical"
android:layout_above="#id/equal2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="#+id/onetwothree"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="1/2/3"/>
<Button
android:id="#+id/fourfivesix"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="4/5/6"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="#+id/seveneightninezero"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="7/8/9/0"/>
<Button
android:id="#+id/operators"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="+-*/"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Will it be possible for me to get the input of 1, 2 or 3 from my first button for example? So on 1 press you get 1, 2 press gives 2 etc.
Any suggestions/ ideas on how I can move forward with this are greatly appreciated.
Kind Regards,
Ben
You could use a timer or delay variable to detect single, double or triple taps. This post may be of interest. If the time interval is not a factor, you could just keep track of the last pressed button and if the same button is being pressed again, update the text accordingly.
If you follow approach one, the code for the click listener for button onetwothree may be something like this (I commented out setNumericOnClickListener() and setOperatorOnClickListener(); in mainActivity onCreate and added the following):
Button onetwothree = (Button) findViewById(R.id.onetwothree);
onetwothree.setOnTouchListener(new View.OnTouchListener() {
Handler handler = new Handler();
int numberOfTaps = 0;
long lastTapTimeMs = 0;
long touchDownMs = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchDownMs = System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacksAndMessages(null);
if ((System.currentTimeMillis() - touchDownMs) > ViewConfiguration.getTapTimeout()) {
//it was not a tap
numberOfTaps = 0;
lastTapTimeMs = 0;
break;
}
if (numberOfTaps > 0
&& (System.currentTimeMillis() - lastTapTimeMs) < ViewConfiguration.getDoubleTapTimeout()) {
numberOfTaps += 1;
} else {
numberOfTaps = 1;
}
lastTapTimeMs = System.currentTimeMillis();
if (numberOfTaps == 1) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("1");
} else txtScreen.append("1");
}
}, ViewConfiguration.getDoubleTapTimeout());
}else if (numberOfTaps == 2) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("2");
} else txtScreen.append("2");
}
}, ViewConfiguration.getDoubleTapTimeout());
} else if (numberOfTaps == 3) {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("3");
} else txtScreen.append("3");
}
}
return true;
}
});
Complete MainActivity:
package com.example.myfirstapp;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private int[] operatorButtons = {R.id.operators};
private int[] numericButtons = {R.id.onetwothree, R.id.fourfivesix, R.id.seveneightninezero};
private boolean lastNumeric, stateError;
private TextView txtScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (TextView) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
// setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
// setOperatorOnClickListener();
Button onetwothree = (Button) findViewById(R.id.onetwothree);
onetwothree.setOnTouchListener(new View.OnTouchListener() {
Handler handler = new Handler();
int numberOfTaps = 0;
long lastTapTimeMs = 0;
long touchDownMs = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchDownMs = System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacksAndMessages(null);
if ((System.currentTimeMillis() - touchDownMs) > ViewConfiguration.getTapTimeout()) {
//it was not a tap
numberOfTaps = 0;
lastTapTimeMs = 0;
break;
}
if (numberOfTaps > 0
&& (System.currentTimeMillis() - lastTapTimeMs) < ViewConfiguration.getDoubleTapTimeout()) {
numberOfTaps += 1;
} else {
numberOfTaps = 1;
}
lastTapTimeMs = System.currentTimeMillis();
if (numberOfTaps == 1) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("1");
} else txtScreen.append("1");
}
}, ViewConfiguration.getDoubleTapTimeout());
}else if (numberOfTaps == 2) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("2");
} else txtScreen.append("2");
}
}, ViewConfiguration.getDoubleTapTimeout());
} else if (numberOfTaps == 3) {
if (txtScreen.getText().toString() == "") {
txtScreen.setText("3");
} else txtScreen.append("3");
}
}
return false;
}
});
}
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
lastNumeric = false;
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
}
}
You can take all numbers when doing some operation
(Button) plusBtn = (Button) findViewById(R.id.plusBtn);
plusBtn.setOnClickListener(new OnClickListener(){
#Override
public voidonClick(View v){
number1 = Integer.parseInt(txtScreen.getText().toString());
});
Where number1 is global int. But I don't know how it can help you and if it is a good approach. You could find a better solution, just remember how to parse the String from your TextView to Integer for your calculation.

how to know the check box value of a particular row of a listview

hey how can i know that the below checkbox when clicked is from which row of the list.
is there any way of knowing that. Every time yo is returning false which is its default value.
checkBox.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
callBlockOptions callBlockOptions = (callBlockOptions) cb.getTag();
callBlockOptions.setChecked( cb.isChecked() );
String yo;
if(callBlockOptions.getPosition()=="0")
{
callBlockOptions.setAllCalls();
}
if(callBlockOptions.getAllCalls() ==true)
yo="true";
else
yo="false";
Toast.makeText(getContext(), callBlockOptions.getPosition(), Toast.LENGTH_LONG).show();
}
});
}
After seeing your code, one thing you might want to try is setting listeners for the individual children within the ListView. You could do something like this:
ListView listView = (ListView)findViewById(R.id.listView);
int count = listView.getChildCount();
for (int x = 0; x < count; x++)
{
Class<? extends View> c = listView.getChildAt(x).getClass();
if (c == CheckBox.class)
{
CheckBox checkBox = (CheckBox)(listView.getChildAt(x));
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton compoutButton, boolean isChecked) {
// TODO Auto-generated method stub
callBlockOptions.isChecked = isChecked;
}
});
}
else if (c == TextView.class)
{
TextView textView = (TextView)(listView.getChildAt(x));
textView.setOnEditorActionListener(new OnEditorActionListener(){
#Override
public boolean onEditorAction(TextView tView, int arg1, KeyEvent arg2) {
// TODO Auto-generated method stub
callBlockOptions.name = tView.getText().toString();
return true;
}
});
}
You probably want your other class to be like this:
public class callBlockOptions {
public static String name;
public static Boolean isChecked;
}
Then you can get and set name and isChecked like this:
callBlockOptions.isChecked = false;
Boolean boolVal = callBlockOptions.isChecked;

EditText array FocusChange

I have 80 EditText fields (cube[i]) and want to read what is in inside the text fields when the text field loses focus.
I can detect when any of the EditTexts (cube) loses focus but I cannot detect exactly which one, Im trying to find which cube is focused on.
the line "EditText cube = (EditText) v.getClass();" is giving me an error
Maybe I can use the View v?
for (int i = 0; i < cube.length; i++) {
cube[i].setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
EditText cube = (EditText) v.getClass();
String s = cube.getText().toString();
//cubecolor();
}
}
});
}
}
Any help is appreciated.
while creating set some tag to the editText like this (pseudo code)
EditText edit = new EditText(context);
edit.setTag(Integer.valueOf(i)); // i is within the for loop;
Now during the onFocus get the tag
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
EditText cube = (EditText) v;
Integer tag = (Integer)cube.getTag();
//code to sort out which cube based on tag
String s = cube.getText().toString();
//cubecolor();
}
}
This worked, Thanks Dante.
for (int i = 0; i < cube.length; i++) {
cube[i].setTag(Integer.valueOf(i)); // give cubes tags
}
for (int i = 0; i < cube.length; i++) {
cube[i].setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
Integer tag = (Integer) v.getTag();
String s = cube[tag].getText().toString();
Log(TAG, " Content" + s);
revert_cubecolor(tag);
}
}
});
}

Categories

Resources