This question already has answers here:
Android EditText.setError() yields invisible error text
(5 answers)
Closed 9 years ago.
I have following small block of code to set validation on edit text when a button is pressed and display the validation message in a dialog.
Java Code
setContentView(R.layout.addnewcontacts);
Button buttonSave = (Button) findViewById(R.id.buttonSave);
final EditText editTextName = (EditText) findViewById(R.id.editTextName);
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (editTextName.getText().toString().length() == 0) {
editTextName.setError( "First name is required!" );
}
}
});
}
Code is working fine but the popup is not displaying text in it.
Screen shot :
Why popup is not showing text?
Call EditText.setError() with a SpannableStringBuilder object.
Check this previous SO question: Android EditText.setError() yields invisible error text
Use EditText.setTextColor(int color) to set the required color for the text element.
Just add edittext color into your xml file.
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#android:color/black" />
it's very simple just follow the below code it is working fine.
final EditText et=(EditText)findViewById(R.id.editText1);
Button bt=(Button)findViewById(R.id.button1);
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(et.getText().toString().length()==0){
et.setError("it is wrong");
}
}
});
please check the theme you have applied .Use basic theme to check error text
Related
I have a simple button that looks like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:tag="general"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#343535"
android:orientation="vertical"
tools:context=".fragments.GeneralFragment">
<Button
android:id="#+id/hello"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/hello" />
Instead of static, these buttons should now be dynamic
Button button = (Button) layout.getChildAt(0);
for(String text : readFromSharedPreferences) {
// Set the layout
Button btn = new Button(this.getContext());
btn.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
btn.setText(text);
btn.setTag(text);
btn.setLayoutParams(button.getLayoutParams());
btn.setBackground(button.getBackground());
layout.addView(btn);
The static button has an animation when I click on it. That looks like this:
But the dynamic button has no animation. So when I click on it, nothing happens. That looks like this:
How can I add this animation to my dynamic buttons?
Update
I have figured out that my loop contains an on-touch listener. That looks like this:
btn.setOnTouchListener(new OnSwipeTouchListener(getContext()) {
// No code in here
});
If I remove that listener (even if it contains no code), the animation works great but I would like to keep it, because of my swipe function that is placed into it.
That is my whole code:
// Swiping to link
btn.setOnTouchListener(new OnSwipeTouchListener(getContext()) {
#Override
public void onSwipeLeft() {
super.onSwipeLeft();
// Alert to ask
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Delete");
builder.setMessage("Do you want to delete?");
// Delete
builder.setPositiveButton("Yes", (dialog, which) -> {
// Set the SharedPreferences as String
ArrayList<String> currentSharedPreferences = readFromSharedPreferences(getContext());
currentSharedPreferences.remove(btn.getTag().toString());
Gson gson = new Gson();
String currentSharedPreferencesAsText = gson.toJson(currentSharedPreferences);
// Update the SharedPreference k-text
SharedPreferences mPrefs = getContext().getSharedPreferences("k-texts", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
prefsEditor.putString("k-text", currentSharedPreferencesAsText);
prefsEditor.apply();
// Start the animation
btn.animate()
.translationX(-btn.getWidth())
.alpha(0.0f)
.setDuration(300)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
btn.clearAnimation();
btn.setVisibility(View.GONE);
Snackbar.make(view, "Entry deleted.", Snackbar.LENGTH_LONG).setAction("Delete", null).show();
}
});
});
// Cancel
builder.setNegativeButton("No", (dialog, which) -> {
// Silence is golden
});
builder.show();
}
#Override
public void onClick() {
MainActivity mainActivity = new MainActivity();
Tts tts = new Tts(getContext(), _mediaPlayer, mainActivity.barTop, mainActivity.barBottom);
try {
tts.say(btn.getTag().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
Well I could use
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return false;
}
Then the animation will work but onClick() wouldn't work anymore.
Another update
I had a similar problem on another view. There my static button was not having a click effect. Then I have just simply added android:foreground="?attr/selectableItemBackground" and it worked! The same way I have just tried with my dynamic button. So I have added btn.setForeground(button.getForeground()); but that doesn't do anything.
Use MaterialButton instead of Button. MaterialButton is a subtype of Button that supports additional features. The Button that is in your XML layout is actually a MaterialButton if you're using a Material Components theme. The theme automatically swaps out Buttons for MaterialButtons when your XML is inflated. So, when dynamically creating buttons in your Java code, you must use MaterialButton if you want it to match the original.
Also, when using MaterialButton, never call setBackground() because this causes undefined behavior. It likely will prevent the ripple effect from occurring as well.
Alternatively, you can define your Button in its own XML file, even with the layout params it needs for LinearLayout. Then inflate the XML each time you need another button.
for(String text : readFromSharedPreferences) {
Button btn = requireContext().getLayoutInflater()
.inflate(R.layout.my_button, layout, true); // true adds it to layout
btn.setText(text);
btn.setTag(text);
}
I'm new to Android developing and now I'm trying to simulate click on my AutoCompleteTextView object.
I'm expecting default android's keyboard appearance with the possibility to type something at the element
Here is a simple function, where I'm trying to perform it:
private void someTestMethodName() {
AutoCompleteTextView tagSearchInput = findViewById(R.id.autoCompleteTextView);
tagSearchInput.performClick();
}
And here is .xml element defining:
<AutoCompleteTextView
android:id="#+id/autoCompleteTextView"
android:text="TextView"
android:layout_width="188dp"
android:layout_height="62dp"
android:layout_alignParentStart="true"
android:layout_marginStart="108dp"
android:layout_alignParentTop="true"
android:layout_marginTop="292dp"/>
Calling performClick on a TextView does not pop up the soft keyboard, but you can quite easily do that yourself:
private void someTestMethodName() {
AutoCompleteTextView tagSearchInput = findViewById(R.id.autoCompleteTextView);
showSoftKeyboard(tagSearchInput);
}
public void showSoftKeyboard(View view){
if(view.requestFocus()){
InputMethodManager imm =(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view,InputMethodManager.SHOW_IMPLICIT);
}
}
More information can be found here: https://github.com/codepath/android_guides/wiki/Working-with-the-Soft-Keyboard
i never used performClick, you cant use setOnClickListener to catch a click
tagSearchInput.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do somthing
}
});
This question already has answers here:
One OnClickHandler for multiple Buttons
(6 answers)
Closed 7 years ago.
I have an activity that is a full screen of 25 buttons. I was wondering if there was a more efficent was to create listeners for them so that they change colour when clicked instead of:
Button buttonA1;
Button buttonA2;
Button buttonA3;
...
buttonA1 = (Button) findViewById(R.id.buttonA1);
buttonA2 = (Button) findViewById(R.id.buttonA2);
buttonA3 = (Button) findViewById(R.id.buttonA3);
...
and then adding a listener for each...
Is it possible to condense all this into considerably less lines of code?
In xml file, you can implement OnClickListener for button like this :
...
<Button android:id="#+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="myMethod" />
Then, in your java file
public void myMethod(View v) {
// does something very interesting
}
You can set in your XML file the android:onClick for each button.
android:onClick="onClick"
Then in your MainActivity you can use something like.
public void onClick(View v) {
//Handle the buttons
public void onClick(View v) {
switch(v.getId())
{
case R.id.button_a_id:
// handle button A click;
break;
case R.id.button_b_id:
// handle button B click;
break;
default:
throw new RuntimeException("Unknow button ID");
}
}
Hope it helps.
I have a android project that generates random numbers as the button's text. If you click a button the value of the corresponding button should be displayed in the edittext.
I am already getting the value of the buttons and also able to display it in the edittext. I have 12 buttons and 2 edittexts. What I want is, if I will do the first click then first value will display in the first edittext and in the second click the value will display in the second edittext.
My problem is that in the first click the value is getting displayed in the 2 edittexts simultaneously. Hope you can help me, here is my code:
b1=(Button)findViewById(R.id.b1);
et1=(EditText)findViewById(R.id.first);
et2=(EditText)findViewById(R.id.second);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
str=((Button)v).getText().toString();
et1.setText(str);
et2.setText(str);
}
});
b1 = one of the buttons.
et1 and et2= the two edittexts.
str = empty string
That doesn't surprise me. You don't distinguish your cases within your onClickListener.
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
str=((Button)v).getText().toString();
// Check which edit text
if(isFirstClick()) {
et1.setText(str);
setFirstClick(false);
} else {
et2.setText(str);
}
}
});
See the 'isFirstClick()' like some kind of pseudo code, maybe you can also check if your first editbox is still empty or something like that.
Both #Averroes and #Sambuca have provided a smiliar solution which should work:
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
str=((Button)v).getText().toString();
if((et1.getText().toString()).equals(""))
et1.setText(str);
else
et2.setText(str);
}
});
In case you can do more than 2 clicks and your requirement is to output to textBox1 on odd clisk and Textbox2 on even click - use a boolean variable.
in my app i have placed three edit boxes with a ok button. Before pressing the ok button the user must enter all the edit text fields, if any of the edit text is been left empty i want to give an alert box.
in the edit text box the field name such as "Name", "Age" should be in diminished and when it is clicked it must get disappeared.
How to do this , pls anyone help me
Check length:
if (edit1.getText().length() > 0 && edit2.getText.length() > 0 && edit3.getText.length() > 0) {
// Do your normal code here
} else {
// Call your alert dialog creation
}
Diminished? You mean a hint (which is shown when there's no text in the field)? This is done like this...
XML inside the EditText field:
android:hint="Clear by clicking"
Source code:
nameEditText.setHint("Clear by clicking");
Remove text on click (if you have already created an EditText field called nameEditText):
// Clear text when clicked
nameEditText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
nameEditText.setText("");
}
});
And then do what Vladimir said
Just use AlertDialog. Check all the conditions and if there is an error build a dialog and show it.
you can design this ui in your activity, and this activity should have the theme android:theme="#android:style/Theme.Dialog". And when you want your activity to disappear. simpally call finish()
its simple..
for name checking :
if(editname.getText().tostring().length==0)
show alert...
AlertDialog.Builder builder=new AlertDialog.Builder(context);
builder.setTitle("something,");
builder.setMessage("something..");
builder.show():
you can also add button...by
builder.setNeutralButton("name",new DialogInterface.onclick
............}
just try this
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage("Error Msg).setPositiveButton("OK", alertClickListener).show();
DialogInterface.OnClickListener alertClickListener = new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
}
};
In your Ok Button OnClick do the following
if (et1.getText().toString().length() != 0) {
emailid = String.valueOf(et1.getText());
}
if((emailid==null|| emailid=="")){
tvError.setVisibility(View.VISIBLE);
tvError.setText("All fields are Mandatory");
Toast.makeText(Signin.this,"All fields are Mandatory", Toast.LENGTH_SHORT).show();
}else{
// Your operation
}
where et1 is Edit box 1,emailid is String ..
In your XML file create a textview with option android:visibility="GONE"..
Now in if part Make that textview visible if error occurs or do your process in Else..
Also you can keep toast mesaage...
use this it is best as compared with all validation check