I searched and found ways to make a single EditText not editable, such as
edittext.setKeyListener(null);
set EditText as android:focusable="false"
However, the problem with these methods is that I need to get references to each of the EditText views in my layout and individually implement the above statements. Is there a way by which I can make all EditText views in a layout not editable?
The application is this: I have a 'Display and Edit' activity, where the user is shown the current record in the database. At this point the displayed text should be read only. If required, he clicks an edit button and then the EditText views become editable.
I tried setting android:inputType="none" and android:focusable="false" in the root ViewGroup but that didn't work. Is there a way out?
If you want to achieve this programmatically,
public void setupUI(View view, boolean editable) {
if (view instanceof EditText) {
((EditText)view).setFocusable(editable);
//Here you can add any other code that needed to be done while changing focus of a particular edit text
return;
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView, editable);
}
}
}
Provide this method with your parent view of your fragment or activity.
When you are clicking edit button pass the parent view and true(i.e, editable) to the method and after editing pass parent view and false(i.e, not editable) instead.
From android:descendantFocusability docs:
Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus.
Apply this to the parent of those EditTexts:
android:descendantFocusability="blocksDescendants"
This will result the ViewGroup to block its descendants from receiving focus.
Related
I'm developing an app in Android in Kotlin, and in one activity I have 10 editText. How i could get the text of all editTexts within a for loop? EditTexts are into Constraint Layouts, which are into a Linear Layout.enter image description here
You can iterate over the child views of the parent view group and just gather the texts, something like this:
val parentView: ViewGroup = findViewById(R.id.parent)
for (i in 0 until parentView.childCount) {
val view: View = parentView.getChildAt(i)
if (view is EditText) {
Log.d("text", view.text.toString())
}
}
Change the R.id.parent to the correct id of course - the id of your constraint layout.
In my Android app there is a requirement that a number of UI elements should be disabled until a button click carryout. Can I disable all the UI elements in a layout by referring the layout without disable them one by one. Is it possible.Can some one help me.
You could disable all views recursively like this.
Just pass the layout as view to the method:
private void enableViews(View v, boolean enabled) {
if (v instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) v;
for (int i = 0;i<vg.getChildCount();i++) {
enableViews(vg.getChildAt(i), enabled);
}
}
v.setEnabled(enabled);
}
Just run enableViews(view, false) to disable, or enableViews(view, true) to enable again.
use following attribute in your xml layout( as a example textView)
android:visibility="gone"
in button click event
myText.setVisible(myText.VISIBLE)
you can either use them one by one or you can put all invisible content in a single layout and hide the layout. then once you want to show them, just VISIBLE the layout. then all will display
need any more comment.. just comment.
I would like to create a linear layout which would behave similarly to ImageButton.
<LinearLayout
android:id="#+id/container"
style="?WidgetHomeIconContainer">
<ImageView
android:id="#+id/icon"
style="?WidgetHomeIcon" />
<TextView
android:id="#+id/title"
style="?WidgetHomeLabel"
android:text="#string/title"
android:textAppearance="?attr/TextHomeLabel" />
</LinearLayout>
In styles of ImageView, TextView and LinearLayout, I set a selectors for all states.
Now:
when I click on ImageView (I tried it also with ImageButton) - it behaves correctly and the image is changed according the selector xml.
when I click on LinearLayout - the linear layout is clicked, but the the ImageView and TextView don't change it's drawable/appearance
So I would like to do the following. When I click on parent LinearLayout, I need to change all it's childs to pressed state.
I tried to add following code to LinearLayout onClickListener to propagate the click:
#Override
public void onClick(View v)
{
LinearLayout l = (LinearLayout) v;
for(int i = 0; i < l.getChildCount(); i++)
{
l.getChildAt(i).setClickable(true);
l.getChildAt(i).performClick();
}
}
But it still reamins the same. Thank you very much for any help.
Put
android:duplicateParentState="true"
in your ImageView and TextView..then the views get its drawable state (focused, pressed, etc.) from its direct parent rather than from itself.
Not only make for every child:
android:duplicateParentState="true"
But also additionally:
android:clickable="false"
This will prevent unexpected behaviour (or solution simply not working) if clickable child views are used.
SO Source
After having the same problem some months later, I found this solution:
private void setOnClickListeners() {
super.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onClick(v);
}
});
for (int index = 0; index < super.getChildCount(); index++) {
View view = super.getChildAt(index);
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onClick(v);
}
});
}
}
protected void onClick(View v) {
// something to do here...
}
In my case, no one of the other solutions works!
I finally had to use OnTouchListener as explained here, capturing the event when the user clicks in the parent view, and removing all childs OnClickListener.
So the idea is, delegate the click behavior to the parent, and notify the child that is really clicked, if you want to propagate the event. ¡¡That's what we are looking for!!
Then, we need to check which child has been clicked. You can find a reference here to know how it´s done. But the idea is basiclly getting the area of the child, and asking for who contains the clicked coordinates, to perform his action (or not).
At first, my child view failed to get click from parent. After investigating, what I need to do to make it work are:
remove click listener on child view
adding click listener on parent view
So, I don't need to add these on every children.
android:duplicateParentState="true"
android:clickable="false"
I only add duplicateParentState to one of my child view.
My child view is now listening to parent click event.
I like my UIs to be intuitive; each screen should naturally and unobtrusively guide the user on to the next step in the app. Barring that, I strive to make things as confusing and confounding as possible.
Just kidding :-)
I've got three TableRows, each containing a read-only and non-focusable EditText control and then a button to its right. Each button starts the same activity but with a different argument. The user makes a selection there and the sub-activity finishes, populating the appropriate EditText with the user's selection.
It's the classic cascading values mechanism; each selection narrows the available options for the next selection, etc. Thus I'm disabling both controls on each of the next rows until the EditText on the current row contains a value.
I need to do one of two things, in this order of preference:
When a button is clicked, immediately remove focus without setting focus to a different button
Set focus to the first button when the activity starts
The problem manifests after the sub-activity returns; the button that was clicked retains focus.
Re: #1 above - There doesn't appear to be a removeFocus() method, or something similar
Re: #2 above - I can use requestFocus() to set focus to the button on the next row, and that works after the sub-activity returns, but for some reason it doesn't work in the parent activity's onCreate().
I need UI consistency in either direction--either no buttons have focus after the sub-activity finishes or each button receives focus depending on its place in the logic flow, including the very first (and only) active button prior to any selection.
Using clearFocus() didn't seem to be working for me either as you found (saw in comments to another answer), but what worked for me in the end was adding:
<LinearLayout
android:id="#+id/my_layout"
android:focusable="true"
android:focusableInTouchMode="true" ...>
to my very top level Layout View (a linear layout). To remove focus from all Buttons/EditTexts etc, you can then just do
LinearLayout myLayout = (LinearLayout) activity.findViewById(R.id.my_layout);
myLayout.requestFocus();
Requesting focus did nothing unless I set the view to be focusable.
Old question, but I came across it when I had a similar issue and thought I'd share what I ended up doing.
The view that gained focus was different each time so I used the very generic:
View current = getCurrentFocus();
if (current != null) current.clearFocus();
You can use View.clearFocus().
Use View.requestFocus() called from onResume().
android:descendantFocusability="beforeDescendants"
using the following in the activity with some layout options below seemed to work as desired.
getWindow().getDecorView().findViewById(android.R.id.content).clearFocus();
in connection with the following parameters on the root view.
<?xml
android:focusable="true"
android:focusableInTouchMode="true"
android:descendantFocusability="beforeDescendants" />
https://developer.android.com/reference/android/view/ViewGroup#attr_android:descendantFocusability
Answer thanks to:
https://forums.xamarin.com/discussion/1856/how-to-disable-auto-focus-on-edit-text
About windowSoftInputMode
There's yet another point of contention to be aware of. By default,
Android will automatically assign initial focus to the first EditText
or focusable control in your Activity. It naturally follows that the
InputMethod (typically the soft keyboard) will respond to the focus
event by showing itself. The windowSoftInputMode attribute in
AndroidManifest.xml, when set to stateAlwaysHidden, instructs the
keyboard to ignore this automatically-assigned initial focus.
<activity
android:name=".MyActivity"
android:windowSoftInputMode="stateAlwaysHidden"/>
great reference
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/ll_root_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
LinearLayout llRootView = findViewBindId(R.id.ll_root_view);
llRootView.clearFocus();
I use this when already finished update profile info and remove all focus from EditText in my layout
====> Update: In parent layout content my EditText add line:
android:focusableInTouchMode="true"
What about just adding android:windowSoftInputMode="stateHidden" on your activity in the manifest.
Taken from a smart man commenting on this: https://stackoverflow.com/a/2059394/956975
I tried to disable and enable focusability for view and it worked for me (focus was reset):
focusedView.setFocusable(false);
focusedView.setFocusableInTouchMode(false);
focusedView.setFocusable(true);
focusedView.setFocusableInTouchMode(true);
First of all, it will 100% work........
Create onResume() method.
Inside this onResume() find the view which is focusing again and again by findViewById().
Inside this onResume() set requestFocus() to this view.
Inside this onResume() set clearFocus to this view.
Go in xml of same layout and find that top view which you want to be focused and set focusable true and focusableInTuch true.
Inside this onResume() find the above top view by findViewById
Inside this onResume() set requestFocus() to this view at the last.
And now enjoy......
android:focusableInTouchMode="true"
android:focusable="true"
android:clickable="true"
Add them to your ViewGroup that includes your EditTextView.
It works properly to my Constraint Layout. Hope this help
You could try turning off the main Activity's ability to save its state (thus making it forget what control had text and what had focus). You will need to have some other way of remembering what your EditText's have and repopulating them onResume(). Launch your sub-Activities with startActivityForResult() and create an onActivityResult() handler in your main Activity that will update the EditText's correctly. This way you can set the proper button you want focused onResume() at the same time you repopulate the EditText's by using a myButton.post(new Runnable(){ run() { myButton.requestFocus(); } });
The View.post() method is useful for setting focus initially because that runnable will be executed after the window is created and things settle down, allowing the focus mechanism to function properly by that time. Trying to set focus during onCreate/Start/Resume() usually has issues, I've found.
Please note this is pseudo-code and non-tested, but it's a possible direction you could try.
You do not need to clear focus, just add this code where you want to focus
time_statusTV.setFocusable(true);
time_statusTV.requestFocus();
InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
imm.showSoftInput( time_statusTV, 0);
Try the following (calling clearAllEditTextFocuses();)
private final boolean clearAllEditTextFocuses() {
View v = getCurrentFocus();
if(v instanceof EditText) {
final FocusedEditTextItems list = new FocusedEditTextItems();
list.addAndClearFocus((EditText) v);
//Focus von allen EditTexten entfernen
boolean repeat = true;
do {
v = getCurrentFocus();
if(v instanceof EditText) {
if(list.containsView(v))
repeat = false;
else list.addAndClearFocus((EditText) v);
} else repeat = false;
} while(repeat);
final boolean result = !(v instanceof EditText);
//Focus wieder setzen
list.reset();
return result;
} else return false;
}
private final static class FocusedEditTextItem {
private final boolean focusable;
private final boolean focusableInTouchMode;
#NonNull
private final EditText editText;
private FocusedEditTextItem(final #NonNull EditText v) {
editText = v;
focusable = v.isFocusable();
focusableInTouchMode = v.isFocusableInTouchMode();
}
private final void clearFocus() {
if(focusable)
editText.setFocusable(false);
if(focusableInTouchMode)
editText.setFocusableInTouchMode(false);
editText.clearFocus();
}
private final void reset() {
if(focusable)
editText.setFocusable(true);
if(focusableInTouchMode)
editText.setFocusableInTouchMode(true);
}
}
private final static class FocusedEditTextItems extends ArrayList<FocusedEditTextItem> {
private final void addAndClearFocus(final #NonNull EditText v) {
final FocusedEditTextItem item = new FocusedEditTextItem(v);
add(item);
item.clearFocus();
}
private final boolean containsView(final #NonNull View v) {
boolean result = false;
for(FocusedEditTextItem item: this) {
if(item.editText == v) {
result = true;
break;
}
}
return result;
}
private final void reset() {
for(FocusedEditTextItem item: this)
item.reset();
}
}
In my application I have a single EditText together with some TextViews, button and a spinner. My EditText receives focus since it is the only focusable view in this activity, I believe. My EditText shows with an orange border and cursor on the field.
Now I would like to remove the focus from this field (I don't want the cursor and border to show). Is there a way to do this?
I have been able to focus on the button by doing button.seFocusableInTouchMode() and button.requestFocus(). But this highlights the button and is obviously not what I want.
new to android.. tried
getWindow().getDecorView().clearFocus();
it works for me..
just to add .. your layout should have:
android:focusable="true"
android:focusableInTouchMode="true"
Did you try to use old good View.clearFocus()
check this question and the selected answer: Stop EditText from gaining focus at Activity startup It's ugly but it works, and as far as I know there's no better solution.
I will try to explain how to remove the focus (flashing cursor) from EditText view with some more details and understanding. Usually this line of code should work
editText.clearFocus()
but it could be situation when the editText still has the focus, and this is happening because clearFocus() method is trying to set the focus back to the first focusable view in the activity/fragment layout.
So if you have only one view in the activity which is focusable, and this usually will be your EditText view, then clearFocus() will set the focus again to that view, and for you it will look that clearFocus() is not working.
Remember that EditText views are focusable(true) by default so if you have only one EditText view inside your layout it will aways get the focus on the screen. In this case your solution will be to find the parent view(some layout , ex LinearLayout, Framelayout) inside your layout file and set to it this xml code
android:focusable="true"
android:focusableInTouchMode="true"
After that when you execute editText.clearFocus() the parent view inside your layout will accept the focus and your editText will be clear of the focus.
I hope this will help somebody to understand how clearFocus() is working.
if Edittext parent layout is Linear then add
android:focusable="true"
android:focusableInTouchMode="true"
like below
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:focusable="true"
android:focusableInTouchMode="true">
<EditText/>
............
when Edittext parent layout is Relative then
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
like
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true">
<EditText/>
............
I know is too late, but for somebody whit the same need editText.setFocusable(false) si what you are looking for.
Use the attached code to give the focus to "someone else", this is OK if you have a view where you simply want to dismiss the keyboard and release the focus, you don't really care about who gets it.
Use like this:
FocusHelper.releaseFocus(viewToReleaseFocusFrom)
public class FocusHelper {
public static void releaseFocus(View view) {
ViewParent parent = view.getParent();
ViewGroup group = null;
View child = null;
while (parent != null) {
if (parent instanceof ViewGroup) {
group = (ViewGroup) parent;
for (int i = 0; i < group.getChildCount(); i++) {
child = group.getChildAt(i);
if(child != view && child.isFocusable())
child.requestFocus();
}
}
parent = parent.getParent();
}
}
}
Doc:
The method traverses from the child view and up the view tree and looks for the first child to give focus to.
Edit:
You can also use the API for this:
View focusableView = v.focusSearch(View.FOCUS_DOWN);
if(focusableView != null) focusableView.requestFocus();
i had a similar problem with the editText, which gained focus since the activity was started. this problem i fixed easily like this:
you add this piece of code into the layout that contains the editText in xml:
android:id="#+id/linearlayout"
android:focusableInTouchMode="true"
dont forget the android:id, without it i've got an error.
the other problem i had with the editText is that once it gain the first focus, the focus never disappeared. this is a piece of my code in java, it has an editText and a button that captures the text in the editText:
editText=(EditText) findViewById(R.id.et1);
tvhome= (TextView)findViewById(R.id.tv_home);
etBtn= (Button) findViewById(R.id.btn_homeadd);
etBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
tvhome.setText( editText.getText().toString() );
//** this code is for hiding the keyboard after pressing the button
View view = Settings.this.getCurrentFocus();
if (view != null)
{
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
//**
editText.getText().clear();//clears the text
editText.setFocusable(false);//disables the focus of the editText
Log.i("onCreate().Button.onClickListener()", "et.isfocused= "+editText.isFocused());
}
});
editText.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(v.getId() == R.id.et1)
{
v.setFocusableInTouchMode(true);// when the editText is clicked it will gain focus again
//** this code is for enabling the keyboard at the first click on the editText
if(v.isFocused())//the code is optional, because at the second click the keyboard shows by itself
{
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
}
//**
Log.i("onCreate().EditText.onClickListener()", "et.isfocused= "+v.isFocused());
}
else
Log.i("onCreate().EditText.onClickListener()", "the listener did'nt consume the event");
}
});
hope it will help to some of you!
For me this worked
Add these attributes to your EditText
android:focusable="true"
android:focusableInTouchMode="true"
After this in your code you can simply write
editText.clearFocus()
Just find another view and give it focus instead.
var refresher = FindViewById<MvxSwipeRefreshLayout>(Resource.Id.refresher);
refresher.RequestFocus();
I've tryed much to clear focus of an edit text. clearfocus() and focusable and other things never worked for me.
So I came up with the idea of letting a fake edittext gain focus:
<LinearLayout
...
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
...
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--here comes your stuff-->
</LinearLayout>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fake"
android:textSize="1sp"/>
</LinearLayout>
then in your java code:
View view = Activity.this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
fake.requestFocus();
}
it will hide the keyboard and remove the focus of any edittext that has it. and also as you see the fake edittext is out of screen and can't be seen
Just include this line
android:selectAllOnFocus="false"
in the XML segment corresponding to the EditText layout.
You just have to clear the focus from the view as
EditText.clearFocus()
If I understand your question correctly, this should help you:
TextView tv1 = (TextView) findViewById(R.id.tv1);
tv1 .setFocusable(false);
You only have to set the ViewGroup with the attribute:
android:focusableInTouchMode="true"
The ViewGroup is the layout that includes every child view.
Just add this line in your parent layout(e.g., constraint or Linear)
android:focusableInTouchMode="true"
Since I was in a widget and not in an activity I did:
getRootView().clearFocus();
<EditText android:layout_height="wrap_content" android:background="#android:color/transparent" android:layout_width="match_parent"
android:clickable="false"
android:focusable="false"
android:textSize="40dp"
android:textAlignment="center"
android:textStyle="bold"
android:textAppearance="#style/Base.Theme.AppCompat.Light.DarkActionBar"
android:text="AVIATORS"/>