I have a EdidText and a Button in a Fragment. When I click the Button i want to checks whether the EditText is empty or not. If is empty I want to return an error message, If notEmpty means move to other fragments or something further process.
I previously search the solution for my problem, but mostly I found the solution like ,
if(textView.getText().toString().trim().equals("")) {
textView.setError("something");
} else {
//do something;
}
The above code worked correctly, but what I ask, how to do this in a layout not programmatically.
I want to know is this is achieved through the layout xml file or not. If possible means please give me an example.
Thank you in advance.
You can't set an error in with XML.
you need to set it in the onCreate of your fragment. This way you won't see the difference if it is set in xml or in code.
You could write your own EditText and add an extra style attribute "error". After that you need to use your own EditText and again set the error in the onCreate.
Create a new class and extend it from EditText like this:
public class MyEditText extends EditText {
public MyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyEditText);
String error = a.getString(R.styleable.MyEditText_error);
a.recycle();
setError(error);
}
}
In Attr add this:
<declare-styleable name="MyEditText">
<attr name="error" format="reference|string" />
</declare-styleable>
After that you will need to always use MyEditText
Check it with this code
editText.getText().toString().isEmpty()
Related
Update: -----> SOLUTION
Since I asked this question I have read that if you disable the soft keyboard using the command setInputType(InputType.TYPE_NULL);, which I did, that it would disable the (blinking) cursor, which it does.
What I am doing is I created a keypad layout using Buttons and loading it as a fragment. (Android doesn't seem to allow the alteration of the soft keyboard to serve ones needs.) What I was wanting to do is re-enable the cursor so with a tap (click) the cursor could be positioned at the desired place in the String for editing.
EditText inherits from TextView, (one wouldn't think this method would part of TextView), which has a method called setShowSoftInputOnFocus(bool);. This method will disable the soft keyboard without disabling the cursor.
I am seeking to setup an EditText so a user can place the cursor at a desired random location in the EditText so part of the text can be modified. I would also like the cursor to be visible.
There is the Java code solution --> Set cursor position in edittext according to user click
Isn't there XML attributes to accomplish this?
If you want the user to define where the cursor should be setup, then you should do it programmatically as following:
EditText editText = findViewById(R.id.editText);
editText.setSelection(3); // Custom point Cursor
If you meant that user should be able to use the cursor, then simply set the cursor at the last as a good practice:
EditText editText = findViewById(R.id.editText);
editText.setSelection(editText.getText().length()); // End point Cursor
If you want to use XML and define this as a property, then you need to decide if this should be static or rather dependent on the user:
IF STATIC, THEN USE THE FOLLOWING ATTRIBUTE
android.selection
IF NOT STATIC AND DEPENDS ON THE USER
In that case you will need to bind your XML layout file with the respective ViewController, which could be Activity or a Fragment, and setup a Int value which the layout file can read.
If you want to set the initial cursor position through xml look at my answer
Maybe create a custom EditText and reuse in any xml layout, customise it to do what you want:
now in res/values/attrs.xml
<resources>
<declare-styleable name="MyCustomEditText">
<attr name="cursor_position" format="string" />
</declare-styleable>
</resources>
use custom edittext in xml layout
<com.example.yourpackage.CustomEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cursor_position="5" //it can be any index you want
..........
custom edit text
class CustomEditText extends EditText
{
public CustomEditText(Context context) {
super(context);
}
public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
//get attribute of cursor_position
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomEditText, defStyle, 0);
String index = a.getString(R.styleable.MyCustomEditText_cursor_position);
//set the cursor index
this.setSelection(Integer.parseInt(index));
}
}
hi guys I'm new to styling android layouts and I want to ask if there is a way to apply a drawable background to a widget (ex: all buttons in a layout) without having to type the android:drawable in each widget.
You can create class extend Button :
public class CustomButton extends Button {
public CustomButton(Context context, AttributeSet attrs) {
super(context, attrs);
//set drawable here
}
}
and in xml file call CustomButton :
<yourpackage.name.CustomButton
android:id="#+id/xxx"
android:text="CustomButton" />
You can add it in every layout but you can also add it programmatically by iterating every control on the page. I did this recently. I didn't like the result because it was impossible (literally) to check the existing styling to see if I needed to replace it -I didn't want to restyle labels- but it was something like this:
//change linerlayout to whatever viewgroup type you have
LinearLayout layout = (LinearLayout) findViewById(R.id.name_of_your_linearlayout);
for(int count = 0; count < layout.getChildCount(); count ++) {
if (layout.getChildAt(count)) instanceOf EditText) {
/*do your work here. Note you don't have to limit yourself
to theming. You could add an event to every button or textbox
at the same time */
}
}
By default, the setError makes an EditText look like the following:
There's a red exclamation. The error message pops-up when that particular EditText gains focus.
I'm creating a custom setError method:
validatedIcon = ContextCompat.getDrawable(getApplicationContext(), R.drawable.validated);
validatedIcon.setBounds(0, 0, validatedIcon.getIntrinsicWidth(), validatedIcon.getIntrinsicHeight());
firstName.setError("Please check your first name",validatedIcon);
My new error icon is a custom icon. But I don't want the error message to be displayed with it. I tried passing null as the message, but that removed the whole icon. I tried passing the empty string, but that simply made an empty box.
Alternative tried: I tried setting the icon using setCompoundDrawablesWithIntrinsicBounds, but even after much hair-pulling, it didn't work properly.
So, is there a way to get rid of the message-box in setError?
As Patel Hiren suggested in the comment, creating a custom class that extends EditText and overriding the setError method there solved my issue:
public class MyEditText extends EditText {
public MyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void setError(CharSequence error, Drawable icon) {
setCompoundDrawables(null, null, icon, null);
}
}
Also, in my layout file, I had to replace EditText with the fully qualified name (which is packagename.className) of this class. It worked fine.
You can set where you want firstName.setError(null);
I want to create a custom Android View (MyCustomView). In this View I want to have a property of a custom Type (MyCustomType). Similar to this:
MyCustomView extends LinearLayout {
private MyCustomType prop1;
public MyCustomType getProp1()
{
return this.prop1;
}
public void setProp1(MyCustomType value)
{
this.prop1 = value;}
}
}
So far so good. But now I want to be able to set the value of this property from XML. I can create a custom attribute with string, int, reference format, but I do not see how to define this attribute to be of MyCustomType format. I image something similar to this:
<declare-styleable name="MyCustomView">
<attr name="prop1" format="MyCustomType"/>
</declare-styleable>
Is this possible somehow? Or custom type attributes are possible to be set only from code behind?
Thank you!
I don`t really understand why you need this. but you can use format="String" and write full class name in property field in your layout. For example:
custom:prop1="com.example.MyCustomType"
then in constructor of your View:
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.MyCustomView,
0, 0);
String className = a.getString(R.id.prop1);
Class<MySustomType> c = Class.forName(className);
MySustomType prop = c.newInstance();
setProp1(prop);
You cannot use own property types with android framework. You can come with own proprties based on available types but that's it. Not sure what type you got in mind in your case, but in most cases whatever that custom thing is, it could be solved by available primitives.
I would like to be able to assign a xml attribute or style to a TextView that will make whatever text it has in ALL CAPITAL LETTERS.
The attributes android:inputType="textCapCharacters" and android:capitalize="characters" do nothing and look like they are for user inputed text, not a TextView.
I would like to do this so I can separate the style from the content. I know I could do this programmically but again I want keep style out of the content and the code.
I though that was a pretty reasonable request but it looks like you cant do it at this time. What a Total Failure. lol
Update
You can now use
textAllCaps
to force all caps.
What about android:textAllCaps?
By using AppCompat textAllCaps in Android Apps supporting older API's (less than 14)
There is one UI widgets that ships with AppCompat named CompatTextView is a Custom TextView extension that adds support for textAllCaps
For newer android API > 14 you can use :
android:textAllCaps="true"
A simple example:
<android.support.v7.internal.widget.CompatTextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:textAllCaps="true"/>
Source:developer.android
Update:
As it so happens CompatTextView was replaced by AppCompatTextView in
latest appcompat-v7 library ~ Eugen Pechanec
It is really very disappointing that you can't do it with styles (<item name="android:textAllCaps">true</item>) or on each XML layout file with the textAllCaps attribute, and the only way to do it is actually using theString.toUpperCase() on each of the strings when you do a textViewXXX.setText(theString).
In my case, I did not wanted to have theString.toUpperCase() everywhere in my code but to have a centralized place to do it because I had some Activities and lists items layouts with TextViews that where supposed to be capitalized all the time (a title) and other who did not... so... some people may think is an overkill, but I created my own CapitalizedTextView class extending android.widget.TextView and overrode the setText method capitalizing the text on the fly.
At least, if the design changes or I need to remove the capitalized text in future versions, I just need to change to normal TextView in the layout files.
Now, take in consideration that I did this because the App's Designer actually wanted this text (the titles) in CAPS all over the App no matter the original content capitalization, and also I had other normal TextViews where the capitalization came with the the actual content.
This is the class:
package com.realactionsoft.android.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewTreeObserver;
import android.widget.TextView;
public class CapitalizedTextView extends TextView implements ViewTreeObserver.OnPreDrawListener {
public CapitalizedTextView(Context context) {
super(context);
}
public CapitalizedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CapitalizedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public void setText(CharSequence text, BufferType type) {
super.setText(text.toString().toUpperCase(), type);
}
}
And whenever you need to use it, just declare it with all the package in the XML layout:
<com.realactionsoft.android.widget.CapitalizedTextView
android:id="#+id/text_view_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Some will argue that the correct way to style text on a TextView is to use a SpannableString, but I think that would be even a greater overkill, not to mention more resource-consuming because you'll be instantiating another class than TextView.
I've come up with a solution which is similar with RacZo's in the fact that I've also created a subclass of TextView which handles making the text upper-case.
The difference is that instead of overriding one of the setText() methods, I've used a similar approach to what the TextView actually does on API 14+ (which is in my point of view a cleaner solution).
If you look into the source, you'll see the implementation of setAllCaps():
public void setAllCaps(boolean allCaps) {
if (allCaps) {
setTransformationMethod(new AllCapsTransformationMethod(getContext()));
} else {
setTransformationMethod(null);
}
}
The AllCapsTransformationMethod class is not (currently) public, but still, the source is also available. I've simplified that class a bit (removed the setLengthChangesAllowed() method), so the complete solution is this:
public class UpperCaseTextView extends TextView {
public UpperCaseTextView(Context context) {
super(context);
setTransformationMethod(upperCaseTransformation);
}
public UpperCaseTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setTransformationMethod(upperCaseTransformation);
}
public UpperCaseTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setTransformationMethod(upperCaseTransformation);
}
private final TransformationMethod upperCaseTransformation =
new TransformationMethod() {
private final Locale locale = getResources().getConfiguration().locale;
#Override
public CharSequence getTransformation(CharSequence source, View view) {
return source != null ? source.toString().toUpperCase(locale) : null;
}
#Override
public void onFocusChanged(View view, CharSequence sourceText,
boolean focused, int direction, Rect previouslyFocusedRect) {}
};
}
Basically, write this in TextView of XML file:
android:textAllCaps="true"
It seems like there is permission on mobile keypad setting, so the easiest way to do this is:
editText.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
hope this will work
PixlUI project allows you to use textAllCaps in any textview or subclass of textview including:
Button,
EditText
AutoCompleteEditText
Checkbox
RadioButton
and several others.
You will need to create your textviews using the pixlui version rather than the ones from the android source, meaning you have to do this:
<com.neopixl.pixlui.components.textview.TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
pixlui:textAllCaps="true" />
PixlUI also allows you to set a custom typeface/font which you put in your assets folder.
I'm working on a Gradle fork of the PixlUI framework which uses gradle and allows one to specify textAllCaps as well as the typeface from styles rather than requiring them inline as the original project does.