button cannot be seen even though set visibility android - android

I have a searchview and button next to it. And the button is make as visible GONE. when typing something on searchview I want to show the button. My problem is it is not showing the button properly even though i make the visibility to VISIBLE.
svSearchSentItem.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
btnClear.setVisibility(View.VISIBLE);
preLast = 0;
isQuickSearch = true;
currentMailInboxListMap = new ArrayList<Map<String, String>>();
setSentItemListView(query, 0, 50, true,false);
((DashboardActivity)getActivity()).mailSentSearchQuery=query;
searchCycle = 1;
svSearchSentItem.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.isEmpty()) {
}
else
{
btnClear.setVisibility(View.VISIBLE);
}
return false;
}
});
XML layout
LinearLayout
android:orientation="horizontal"
android:focusable="true"
android:focusableInTouchMode="true"
android:weightSum="8"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:id="#+id/layoutSearch">
<SearchView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/svMailSent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Search"
android:autoText="true"
android:inputType="text"
android:queryHint="Search"
android:layout_weight="6"
android:layout_centerInParent="true"
android:iconifiedByDefault="false"
/>
<Button
android:id="#+id/btnSentSearchClear"
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="Clear"
android:textAllCaps="false"
android:layout_weight="2"
android:visibility="gone"/>
</LinearLayout>

U can use ajax with android to check if the searchview is empty or not, if it is not empty then make view.visible else view.gone.
http://programmerguru.com/android-tutorial/android-ajax-auto-load
this might help!

It didn't help changing anything in XML layout. I found this solution instead. In the oncreateview, I get the layoutparams and assign it in the onQueryTextSubmit event in searchview.
oldLayoutParams = svSearchSentItems.getLayoutParams();
svSearchSentItem.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
btnClear.setVisibility(View.VISIBLE);
preLast = 0;
isQuickSearch = true;
currentMailInboxListMap = new ArrayList<Map<String, String>>();
setSentItemListView(query, 0, 50, true,false);
((DashboardActivity)getActivity()).mailSentSearchQuery=query;
searchCycle = 1;
svSearchSentItem.clearFocus();
svSearchSentItem.setLayoutParams(oldLayoutParams);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.isEmpty()) {
}
else
{
btnClear.setVisibility(View.VISIBLE);
}
return false;
}
});

sorry but you cant use those 3 properties together in this way :)
android:layout_width="130dp"
android:layout_height="wrap_content"
android:layout_weight="2"
when you use layout_weight you need set one of property: height or width to 0dp:
android:layout_height="0dp"
android:layout_width="0dp"
https://developer.android.com/guide/topics/ui/layout/linear.html
weight (float weight)
Indicates how much of the extra space in the LinearLayout will be allocated to the view associated with these LayoutParams. Specify 0 if the view should not be stretched. Otherwise the extra pixels will be pro-rated among all views whose weight is greater than 0.
i propose you to delete all properties and first set only:
id
width
height
if it you will see what u want then you can add some extra properties this way you will see when it fails :)
use this and report result :
<LinearLayout
android:id="#+id/layoutSearch"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="8">
<SearchView
android:id="#+id/svMailSent"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="6"/>
<Button
android:id="#+id/btnSentSearchClear"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"/>
</LinearLayout>
#ceph3us, I changed the layout as you suggested. But still I can't see the button. It seems that it is going right corner outside the screen – creative Pro
you are embedding badly the child view, or your parent is erroneously defined
and don't use "fill_parent" from api 8 is depreciated - btw os'es with api's < 8 are almost dead :)
LinearLayout.LayoutParams.FILL_PARENT;
public static class LayoutParams {
/**
* Special value for the height or width requested by a View.
* FILL_PARENT means that the view wants to be as big as its parent,
* minus the parent's padding, if any. This value is deprecated
* starting in API Level 8 and replaced by {#link #MATCH_PARENT}.
*/
#SuppressWarnings({"UnusedDeclaration"})
#Deprecated
public static final int FILL_PARENT = -1;
...
}
It didn't help changing anything in XML layout. I found this solution instead. In the oncreateview, I get the layoutparams and assign it in the onQueryTextSubmit event in searchview.
oldLayoutParams = svSearchSentItems.getLayoutParams();
YEAH BUDDY YOU ROCK!!!
copy paste does not require understanding - i wish to have more developers like you :)
see this is what you trying to do:
public class TestActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
final View btnClear = findViewById(R.id.btnSentSearchClear);
SearchView sv = (SearchView) findViewById(R.id.svMailSent);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
btnClear.setVisibility(newText!=null
&& !newText.isEmpty() ? View.VISIBLE : View.GONE);
return false;
}
});
}
FULL WORKING ANDROID STUDIO EXAMPLE ON GITHUB
https://github.com/c3ph3us/exampleHideButtonForSearchView/

Related

Android Search View not displaying any text

I am using search view . It was working before now its not responding, I cant see any text being typed in the Search View, also I am not getting back any call back when text is changed.
Here is the xml layout file,
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:iconifiedByDefault="false"
android:id="#+id/searchView"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/cardsRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent"
android:cacheColorHint="#android:color/transparent"/>
</LinearLayout>
Here is how I am setting SearchView Callback,
EditText searchEditText = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchEditText.setTextColor(getResources().getColor(R.color.colorPrimary));
searchEditText.setHintTextColor(getResources().getColor(R.color.dark_grey));
searchView.setOnQueryTextListener(this);
I am not getting any callbacks to these methods when I type in SearchView.
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
filterCards(newText);
return false;
}
I am implementing SearchView.OnQueryTextListener in my Fragment.
Thanks.
Try to give,
android:textColor="#000000"
to your android.support.v7.widget.SearchView
Note : May be your text is white color, that's why you can't to see.

Android SearchView change cursor position after hint icon

I am using android.support.v7.widget.SearchView and the hint icon is at the left of the cursor as shown in the image .
But i want to make the cursor begins after the hint search icon .
XML:
<android.support.v7.widget.SearchView
android:id="#+id/airlines_searchView"
android:iconifiedByDefault="false"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:onClick="EnableSearchView"
android:background="#fbf7f7"
/>
I got the EditText of the search view as following :
EditText search_text=(EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
and i don't know what are the required properties to set to it .
I checked That but no solutions found, any help please ?
Have to change the android:iconifiedByDefault to app:iconifiedByDefault
and add those two lines to avoid launching the keyboard on starting the activity and it is shown only after clicking searchview
android:focusable="false"
android:focusableInTouchMode="true"
So Try this:
<android.support.v7.widget.SearchView
android:id="#+id/airlines_searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:textStyle="normal"
android:layout_marginTop="15dp"
android:background="#fbf7f7"
android:focusable="false"
android:focusableInTouchMode="true"
app:iconifiedByDefault="false"/>
Set search view iconified by default to false on click and to true on close the search view
searchView.setOnSearchClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
searchView.setIconifiedByDefault( false );
}
} );
searchView.setOnQueryTextListener( new android.support.v7.widget.SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
//do search
}
#Override
public boolean onQueryTextChange(String newText) {
//do search
}
} );
searchView.setOnCloseListener( new android.support.v7.widget.SearchView.OnCloseListener() {
#Override
public boolean onClose() {
searchView.setIconifiedByDefault( true );
}
} );
<android.support.v7.widget.SearchView
android:id="#+id/airlines_searchView"
app:iconifiedByDefault="false"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:background="#fbf7f7"
/>
Instead of android:iconifiedByDefault="false" set app:iconifiedByDefault="false"

I want to set a transparent background layer when I click on the floating action menu.

This is what I have done so far. Created FloatingActionButton. Now As the + icon is pressed a translucent layer should be there at the back.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.getbase.floatingactionbutton.FloatingActionsMenu
android:id="#+id/actionMenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="60dp"
fab:fab_addButtonColorNormal="#color/primary"
fab:fab_addButtonColorPressed="#color/primary_dark"
fab:fab_addButtonPlusIconColor="#ffffff">
<com.getbase.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="openAudio"
fab:fab_colorNormal="#EA1E63"
fab:fab_colorPressed="#EA1E63"
fab:fab_icon="#drawable/ic_action_mic" />
</com.getbase.floatingactionbutton.FloatingActionsMenu>
</RelativeLayout
Try this.
floatingActionMenuButton.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {
#Override
public void onMenuToggle(boolean opened) {
if (opened) {
//menu opened
} else {
//menu closed
}
}
});
use setBackgroundResource or setBackgroundColor. I think first is pretty simple.
Second one takes an int as an argument. So, just convert your hex color (for example #55000000) into decimal and it will work as well.
I had the same issue and i fixed it in following way.
I added a relative layout which will match parent in both width and height.
Set its background color to black and set alpha to your required opacity.
<RelativeLayout
android:id="#+id/obstructor"
android:visibility="invisible"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:alpha="0.75"
android:background="#android:color/black">
</RelativeLayout>
And then on the menu item expanded and collapsed make this visible and invisible.
mFabMenu = (FloatingActionsMenu) findViewById(R.id.multiple_actions);
final RelativeLayout obstrucuterView = (RelativeLayout) findViewById(R.id.obstructor);
obstrucuterView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (obstrucuterView.getVisibility() == View.VISIBLE) {
mFabMenu.collapse();
return true;
}
return false;
}
});
mFabMenu.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() {
#Override
public void onMenuExpanded() {
if (obstrucuterView.getVisibility() == View.INVISIBLE)
obstrucuterView.setVisibility(View.VISIBLE);
}
#Override
public void onMenuCollapsed() {
if (obstrucuterView.getVisibility() == View.VISIBLE)
obstrucuterView.setVisibility(View.INVISIBLE);
}
});
Hope this helps.
There is another custom library which is more advanced than what you are using right now.
Get it here
Clans floating Action Button
Set this to true and it will solve your problem. Do let me know if it helps
fabPlusButton.setClosedOnTouchOutside(true);
If you are using Clans floating Action Button then perhaps fab:menu_backgroundColor might be something that you could have a look at if it satisfies your use-case. ofcourse the layout width and height should both match parent (This solution has worked for me)

SwiperefreshLayout in Android

i am using SwipeRefreshLayout in my below layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/homePageBackground"
android:orientation="vertical" >
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeRefreshLayout_listView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<fragment
android:id="#+id/announcementHomefragment"
android:name="in.test.app.AnnouncementFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/homePageBackground" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:background="#color/homePageBackground" >
<TextView
android:id="#+id/newsTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:gravity="center"
android:text="#string/new_list"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/white"
android:textStyle="bold" />
<fragment
android:id="#+id/newshomefragment"
android:name="in.test.app.NewsFragment"
android:layout_width="wrap_content"
android:layout_height="190dp"
android:layout_below="#id/newsTitle"
android:layout_marginTop="-15dp" />
<TextView
android:id="#+id/productTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/newshomefragment"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:gravity="center"
android:text="#string/product_in_home"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/white"
android:textStyle="bold" />
<fragment
android:id="#+id/proCategoryhomefragment"
android:name="in.test.app.CategoryFragment"
android:layout_width="wrap_content"
android:layout_height="170dp"
android:layout_below="#id/productTitle"
android:layout_marginTop="-15dp" />
<TextView
android:id="#+id/trainingTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/proCategoryhomefragment"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:layout_marginTop="2dp"
android:gravity="center"
android:text="#string/trainings_in_home"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/white"
android:textStyle="bold" />
<fragment
android:id="#+id/trainingfragment"
android:name="in.test.app.TrainingFragment"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_below="#id/trainingTitle"
android:layout_marginBottom="10dp"
android:layout_marginTop="-15dp" />
</RelativeLayout>
</ScrollView>
</LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>
When I pull down my SwipeRefreshLayout it is working, but as you can see in the above code I have a scroll view inside that. So when I am pulling down my scroll view, it goes down and half the images are not showing because it came down. When I am trying to pull up again my scroll view is not going up. Instead, SwipeRefreshLayout is getting call. What should i do?
Please help me out.
I would say it's better to have an extended SwipeRefreshLayout with listener to be able to add various conditions from the classes that display this layout.
Something like the following:
GeneralSwipeRefreshLayout.java
public class GeneralSwipeRefreshLayout extends SwipeRefreshLayout {
private OnChildScrollUpListener mScrollListenerNeeded;
public interface OnChildScrollUpListener {
boolean canChildScrollUp();
}
public GeneralSwipeRefreshLayout(Context context) {
super(context);
}
public GeneralSwipeRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* Listener that controls if scrolling up is allowed to child views or not
*/
public void setOnChildScrollUpListener(OnChildScrollUpListener listener) {
mScrollListenerNeeded = listener;
}
#Override
public boolean canChildScrollUp() {
if (mScrollListenerNeeded == null) {
Log.e(GeneralSwipeRefreshLayout.class.getSimpleName(), "listener is not defined!");
}
return mScrollListenerNeeded != null && mScrollListenerNeeded.canChildScrollUp();
}
}
And then inside your class that displays SwipeRefreshLayout containing ListView or GridView layout, you can do something like this:
mSwipeLayout.setOnChildScrollUpListener(new OnChildScrollUpListener() {
#Override
public boolean canChildScrollUp() {
return mListView.getFirstVisiblePosition() > 0 ||
mListView.getChildAt(0) == null ||
mListView.getChildAt(0).getTop() < 0;
}
});
Just create a class which extends SwipeRefreshLayout and override the method canChildScrollUp(). Return true when you want scroll down for your control.
For example for scrollview you may try this,
#override.
boolean canChildScrollUp()
{
//your condition to check scrollview reached at top while scrolling
if(scrollview.getScrollY() == 0.0)
return true;
else
return false;
}
As others have already stated, if you don't have your scrollable view (ie listview) as the direct child of the SwipeRefreshLayout, the stock canChildScrollUp will not work.
Has to do with the simple logic SwipeRefreshLayout uses in checking the ability of the child view to scroll.
I was using a ListView inside an ActionbarActivity, and wanted to include an empty view whenever my listview was empty. This caused problems, since the SwipeRefreshLayout class can only have a single child. Note it also checks this child's ability to scrollUp to determine if a pull down causes the child to scrollUp, or if it causes the childs content to refresh.
So if you want to use the same logic as SwipeRefreshLayout, just extend the class, and create a method to allow you to pass in the handle to your scrollable view. Note the stock implementation uses canScrollVertically() which does exactly what we want, but only appears in SDK >= 14.
Also don't forget to include the constructor that contains the param "AttributeSet", when you extend the class, otherwise you will have problems using the class in your layout files.
So, in the onCreate method of your Activity (in my case it was an ActionBarActivity) that includes the list view, just call setMyScrollableView passing in your ListView or whatever view you use that scrolls.
/*Constructor*/
public MySwipeRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
View mMyScrollableView = null; //The content that get's pulled down.
/*Method used to pass in my scrollable view*/
public void setMyScrollableView(View view){
mMyScrollableView = view;
}
/**
* #return Whether it is possible for the child view of this layout to
* scroll up. This was taken for the most part directly from SwipeRefreshLayout
*/
public boolean canChildScrollUp() {
if(mMyScrollableView == null)
return false;
if (android.os.Build.VERSION.SDK_INT < 14) {
if (mMyScrollableView instanceof AbsListView) {
final AbsListView absListView = (AbsListView) mMyScrollableView;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
} else {
return mMyScrollableView.getScrollY() > 0;
}
} else {
return ViewCompat.canScrollVertically(mMyScrollableView, -1);
}
}
The solution from #User22791 works perfectly and, based on that, I created a library available on github that you can use (and modify) for make the usage of swipeRefreshLayout easier for developers. It's here: https://github.com/dagova/referencedSwipeRefreshLayout
Basically you just have to reference in your layout the view to be checked in the method canChildScrollUp. I hope it will be useful.
I also found the other answers didn't quite work.
Took me a while of head scratching to figure out that they are using the method getScrollY() which as this answer explains, is a View method describing how far it's been scroll within a container, not a method to describe how much your Scroll container has been scrolled.
If you use the same technique as in the other answers (overriding the canChildScrollUp() method) you can easily check if the Scrollable is at it's highest point:
#Override
public boolean canChildScrollUp() {
return !isListAtTop();
}
private boolean isListAtTop() {
if(mGridView.getChildCount() == 0) return true;
return mGridView.getChildAt(0).getTop() == 0;
}
(As you can see, I'm using a GridView, but you can use a ListView too)
Easier solution is to use onScrollListener and check if user can see firstElement.
someView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (isViewAtTop()) {
swipeLayout.setEnabled(true);
} else {
swipeLayout.setEnabled(false);
}
}
}
#Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem == 0) {
swipeLayout.setEnabled(true);
} else {
swipeLayout.setEnabled(false);
}
}
});
Where method isViewAtTop() is some other method, that checks this View is scrolled to the top
Ok I have got it working. If the SwipeRefreshLayout is the root of the layout and the ScrollView resides deep into the hierarchy (I had put the ScrollView inside a RelativeLayout) and not the direct child of the SwipeRefreshLayout, it won’t detect a swipe up on the ScrollView properly.
You should create a custom class that extends SwipeRefreshLayout and override canChildScrollUp() method in SwipRefreshLayout
Here is a example :
public class CustomSwipeRefreshLayout extends SwipeRefreshLayout {
private ScrollView scrollview;
public CustomSwipeRefreshLayout(Context context) {
super(context);
}
public CustomSwipeRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setView(ScrollView view) {
this.scrollview = view;
}
#Override
public boolean canChildScrollUp() {
return scrollview.getScrollY() != 0;
}
}

How to switch between hide and view password

Is there a clever way to let the user switch between hide and view password in an android EditText?
A number of PC based apps let the user do this.
It is really easy to achieve since the Support Library v24.2.0.
What you need to do is just:
Add the design library to your dependencies
dependencies {
compile "com.android.support:design:24.2.0"
}
Use TextInputEditText in conjunction with TextInputLayout
<android.support.design.widget.TextInputLayout
android:id="#+id/etPasswordLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:passwordToggleEnabled="true"
android:layout_marginBottom="#dimen/login_spacing_bottom">
<android.support.design.widget.TextInputEditText
android:id="#+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/fragment_login_password_hint"
android:inputType="textPassword"/>
</android.support.design.widget.TextInputLayout>
The passwordToggleEnabled attribute will do the job!
In your root layout don't forget to add xmlns:app="http://schemas.android.com/apk/res-auto"
You can customize your password toggle by using:
app:passwordToggleDrawable - Drawable to use as the password input visibility toggle icon.
app:passwordToggleTint - Icon to use for the password input visibility toggle.
app:passwordToggleTintMode - Blending mode used to apply the background tint.
More details in TextInputLayout documentation.
For AndroidX
Replace android.support.design.widget.TextInputLayout with com.google.android.material.textfield.TextInputLayout
Replace android.support.design.widget.TextInputEditText with com.google.android.material.textfield.TextInputEditText
You can dynamically change the attributes of a TextView. If you would set the XML Atrribute android:password to true the view would show dots if you set it to false the text is shown.
With the method setTransformationMethod you should be able to change this attributes from code. (Disclaimer: I have not tested if the method still works after the view is displayed. If you encounter problems with that leave me a comment for me to know.)
The full sample code would be
yourTextView.setTransformationMethod(new PasswordTransformationMethod());
to hide the password. To show the password you could set one of the existing transformation methods or implement an empty TransformationMethod that does nothing with the input text.
yourTextView.setTransformationMethod(new DoNothingTransformation());
To show the dots instead of the password set the PasswordTransformationMethod:
yourEditText.setTransformationMethod(new PasswordTransformationMethod());
of course you can set this by default in your edittext element in the xml layout with
android:password
To re-show the readable password, just pass null as transformation method:
yourEditText.setTransformationMethod(null);
To show:
editText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
To hide:
editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
After each of these the cursor is reset, so:
editText.setSelection(editText.length());
You can use app:passwordToggleEnabled="true"
here is example given below
<android.support.design.widget.TextInputLayout
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:passwordToggleEnabled="true"
android:textColorHint="#color/colorhint"
android:textColor="#color/colortext">
I had the same issue and it is very easy to implement.
All you have to do is wrap your EditText field in a (com.google.android.material.textfield.TextInputLayout) and in that add ( app:passwordToggleEnabled="true" ).
This will show the eye in the EditText field and when you click on it the password will appear and disappear when clicked again.
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColorHint="#B9B8B8"
app:passwordToggleEnabled="true">
<EditText
android:id="#+id/register_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginRight="44dp"
android:backgroundTint="#BEBEBE"
android:hint="Password"
android:inputType="textPassword"
android:padding="16dp"
android:textSize="18sp" />
</com.google.android.material.textfield.TextInputLayout>
Use checkbox and change the input type accordingly.
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int start,end;
Log.i("inside checkbox chnge",""+isChecked);
if(!isChecked){
start=passWordEditText.getSelectionStart();
end=passWordEditText.getSelectionEnd();
passWordEditText.setTransformationMethod(new PasswordTransformationMethod());;
passWordEditText.setSelection(start,end);
}else{
start=passWordEditText.getSelectionStart();
end=passWordEditText.getSelectionEnd();
passWordEditText.setTransformationMethod(null);
passWordEditText.setSelection(start,end);
}
}
private boolean isPasswordVisible;
private TextInputEditText firstEditText;
...
firstEditText = findViewById(R.id.et_first);
...
private void togglePassVisability() {
if (isPasswordVisible) {
String pass = firstEditText.getText().toString();
firstEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
firstEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
firstEditText.setText(pass);
firstEditText.setSelection(pass.length());
} else {
String pass = firstEditText.getText().toString();
firstEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
firstEditText.setInputType(InputType.TYPE_CLASS_TEXT);
firstEditText.setText(pass);
firstEditText.setSelection(pass.length());
}
isPasswordVisible= !isPasswordVisible;
}
At first this is the screen loaded with an image vector asset visibility
on click it will change to this image visibility off
code for above password switch(xml code)
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/laypass"
android:layout_width="330dp"
android:layout_height="50dp"
android:layout_marginTop="24dp"
app:layout_constraintEnd_toEndOf="#+id/editText3"
app:layout_constraintStart_toStartOf="#+id/editText3"
app:layout_constraintTop_toBottomOf="#+id/editText3">
<EditText
android:id="#+id/edit_password"
style="#style/EditTextTheme"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/round"
android:drawableLeft="#drawable/ic_password"
android:drawablePadding="10dp"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textColor="#color/cyan92a6"
android:textColorHint="#color/cyan92a6"
android:textCursorDrawable="#null"
android:textSize="18sp"
/>
<ImageView
android:id="#+id/show_pass_btn"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginEnd="8dp"
android:alpha=".5"
android:onClick="ShowHidePass"
android:padding="5dp"
android:src="#drawable/ic_visibility"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/laypass"
app:layout_constraintTop_toTopOf="#+id/edit_password" />
</androidx.constraintlayout.widget.ConstraintLayout>
Java code for button operation
public void ShowHidePass(View view) {
if(view.getId()==R.id.show_pass_btn){
if(edit_password.getTransformationMethod().equals(PasswordTransformationMethod.getInstance())){
((ImageView)(view)).setImageResource(R.drawable.ic_visibility_off);
//Show Password
edit_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
else{
((ImageView)(view)).setImageResource(R.drawable.ic_visibility);
//Hide Password
edit_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
}
It's work for me.This will help you definitely
showpass.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(!isChecked){
// show password
password_login.setTransformationMethod(PasswordTransformationMethod.getInstance());
Log.i("checker", "true");
}
else{
Log.i("checker", "false");
// hide password
password_login.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
I feel I want answer this question even there some good answers ,
according to documentation TransformationMethod do our mission
TransformationMethod
TextView uses TransformationMethods to do things like replacing the
characters of passwords with dots, or keeping the newline characters
from causing line breaks in single-line text fields.
Notice I use butter knife, but its the same if user check show password
#OnCheckedChanged(R.id.showpass)
public void onChecked(boolean checked){
if(checked){
et_password.setTransformationMethod(null);
}else {
et_password.setTransformationMethod(new PasswordTransformationMethod());
}
// cursor reset his position so we need set position to the end of text
et_password.setSelection(et_password.getText().length());
}
I'm able to add the ShowPassword / HidePassword code with just a few lines, self-contained in a block:
protected void onCreate(Bundle savedInstanceState) {
...
etPassword = (EditText)findViewById(R.id.password);
etPassword.setTransformationMethod(new PasswordTransformationMethod()); // Hide password initially
checkBoxShowPwd = (CheckBox)findViewById(R.id.checkBoxShowPwd);
checkBoxShowPwd.setText(getString(R.string.label_show_password)); // Hide initially, but prompting "Show Password"
checkBoxShowPwd.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
if (isChecked) {
etPassword.setTransformationMethod(null); // Show password when box checked
checkBoxShowPwd.setText(getString(R.string.label_hide_password)); // Prompting "Hide Password"
} else {
etPassword.setTransformationMethod(new PasswordTransformationMethod()); // Hide password when box not checked
checkBoxShowPwd.setText(getString(R.string.label_show_password)); // Prompting "Show Password"
}
}
} );
...
In very simple form:
private fun updatePasswordVisibility(editText: AppCompatEditText) {
if (editText.transformationMethod is PasswordTransformationMethod) {
editText.transformationMethod = null
} else {
editText.transformationMethod = PasswordTransformationMethod()
}
editText.setSelection(editText.length())
}
Hope it helps.
private int passwordNotVisible=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
showPassword = (ImageView) findViewById(R.id.show_password);
showPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText paswword = (EditText) findViewById(R.id.Password);
if (passwordNotVisible == 1) {
paswword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
passwordNotVisible = 0;
} else {
paswword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
passwordNotVisible = 1;
}
paswword.setSelection(paswword.length());
}
});
}
Try https://github.com/maksim88/PasswordEditText project at github.
You dont even need to change your Java code using it. Just change
EditText
tag to
com.maksim88.passwordedittext.PasswordEditText
in your XML file.
You can SHOW/HIDE password using this below code:
XML CODE:
<EditText
android:id="#+id/etPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="21dp"
android:layout_marginTop="14dp"
android:ems="10"
android:inputType="textPassword" >
<requestFocus />
</EditText>
<CheckBox
android:id="#+id/cbShowPwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/etPassword"
android:layout_below="#+id/etPassword"
android:text="#string/show_pwd" />
JAVA CODE:
EditText mEtPwd;
CheckBox mCbShowPwd;
mEtPwd = (EditText) findViewById(R.id.etPassword);
mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);
mCbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// show password
mEtPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
// hide password
mEtPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
Try this:
First define a flag as global like this:
private boolean isShowPassword = false;
And set listener to handle tap on show and hide password button:
imgPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isShowPassword) {
etPassword.setTransformationMethod(new PasswordTransformationMethod());
imgPassword.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_hide));
isShowPassword = false;
}else{
etPassword.setTransformationMethod(null);
imgPassword.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_show));
isShowPassword = true;
}
}
});
show and hide password Edit_Text with check Box
XML
<?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">
<EditText
android:inputType="textPassword"
android:id="#+id/edtPass"
android:textSize="20dp"
android:hint="password"
android:padding="20dp"
android:background="#efeaea"
android:layout_width="match_parent"
android:layout_margin="20dp"
android:layout_height="wrap_content" />
<CheckBox
android:background="#ff4"
android:layout_centerInParent="true"
android:textSize="25dp"
android:text="show password"
android:layout_below="#id/edtPass"
android:id="#+id/showPassword"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:gravity="top|right"
android:layout_height="wrap_content" />
</RelativeLayout>
java code
package com.example.root.sql2;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.Toolbar;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
public class password extends AppCompatActivity {
EditText password;
CheckBox show_hide_password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hide);
findViewById();
show_hide_pass();
}//end onCreate
public void show_hide_pass(){
show_hide_password.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (!b){
// hide password
password.setTransformationMethod(PasswordTransformationMethod.getInstance());
}else{
// show password
password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
} // end show_hide_pass
public void findViewById(){ // find ids ui and
password = (EditText) findViewById(R.id.edtPass);
show_hide_password = (CheckBox) findViewById(R.id.showPassword);
}//end findViewById
}// end class
Did you try with setTransformationMethod? It's inherited from TextView and want a TransformationMethod as a parameter.
You can find more about TransformationMethods here.
It also has some cool features, like character replacing.
What I did was to
Create an edit text view and a normal text view
Make them overlap with each other by using constraint layout (just like Facebook app login screen)
Attach an onClickListener to the normal text view so that it changes the input type of the edit text view accordingly (Visible / Non-visible)
You may check out this video for a more detailed steps and explanations https://youtu.be/md3eVaRzdIM
Hope it helps :)
Here is my solution without using TextInputEditText and Transformation method.
XML
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
style="#style/FormLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/username" />
<EditText
android:id="#+id/loginUsername"
style="#style/EditTextStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_person_outline_black_24dp"
android:drawableStart="#drawable/ic_person_outline_black_24dp"
android:inputType="textEmailAddress"
android:textColor="#color/black" />
<TextView
style="#style/FormLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="#string/password" />
<EditText
android:id="#+id/loginPassword"
style="#style/EditTextStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableEnd="#drawable/ic_visibility_off_black_24dp"
android:drawableLeft="#drawable/ic_lock_outline_black_24dp"
android:drawableRight="#drawable/ic_visibility_off_black_24dp"
android:drawableStart="#drawable/ic_lock_outline_black_24dp"
android:inputType="textPassword"
android:textColor="#color/black" />
</LinearLayout>
Java Code
boolean VISIBLE_PASSWORD = false; //declare as global variable befor onCreate()
loginPassword = (EditText)findViewById(R.id.loginPassword);
loginPassword.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_LEFT = 0;
final int DRAWABLE_TOP = 1;
final int DRAWABLE_RIGHT = 2;
final int DRAWABLE_BOTTOM = 3;
if (event.getAction() == MotionEvent.ACTION_UP) {
if (event.getRawX() >= (loginPassword.getRight() - loginPassword.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
// your action here
//Helper.toast(LoginActivity.this, "Toggle visibility");
if (VISIBLE_PASSWORD) {
VISIBLE_PASSWORD = false;
loginPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
loginPassword.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_outline_black_24dp, 0, R.drawable.ic_visibility_off_black_24dp, 0);
} else {
VISIBLE_PASSWORD = true;
loginPassword.setInputType(InputType.TYPE_CLASS_TEXT);
loginPassword.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_outline_black_24dp, 0, R.drawable.ic_visibility_black_24dp, 0);
}
return false;
}
}
return false;
}
});
According to this source, if you have migrated your project to AndroidX, then you can replace
compile "com.android.support:design:24.2.0"
with
implementation "com.google.android.material:material:1.0.0"
Then all you have to do is to put the code below to your layout file:
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:passwordToggleEnabled="true"
android:hint="#string/hint_text">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.google.android.material.textfield.TextInputLayout>
More information about material TextInputLayout can be found here.
To this source, it is recommended to migrate to AndroidX from Android Support Library:
AndroidX is the open-source project that the Android team uses to
develop, test, package, version and release libraries within Jetpack.
AndroidX is a major improvement to the original Android Support
Library. Like the Support Library, AndroidX ships separately from the
Android OS and provides backwards-compatibility across Android
releases. AndroidX fully replaces the Support Library by providing
feature parity and new libraries. In addition AndroidX includes the
following features:
All packages in AndroidX live in a consistent namespace starting with
the string androidx. The Support Library packages have been mapped
into corresponding androidx.* packages. For a full mapping of all the
old classes and build artifacts to the new ones, see the Package
Refactoring page.
Unlike the Support Library, AndroidX packages are separately
maintained and updated. The androidx packages use strict Semantic
Versioning starting with version 1.0.0. You can update AndroidX
libraries in your project independently.
All new Support Library development will occur in the AndroidX
library. This includes maintenance of the original Support Library
artifacts and introduction of new Jetpack components.
A good solution. Set up a button, then use this code:
public void showPassword(View v)
{
TextView showHideBtnText = (TextView) findViewById(R.id.textView1);
if(showHideBtnText.getText().toString().equals("Show Password")){
password.setTransformationMethod(null);
showHideBtnText.setText("Hide");
} else{
password.setTransformationMethod(new PasswordTransformationMethod());
showHideBtnText.setText("Show Password");
}
}
1 - Make a selector file "show_password_selector.xml"
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/pwd_hide"
android:state_selected="true"/>
<item android:drawable="#drawable/pwd_show"
android:state_selected="false" />
</selector>
2 - Aet "show_password_selector" file into imageview.
<ImageView
android:id="#+id/iv_pwd"
android:layout_width="#dimen/_35sdp"
android:layout_height="#dimen/_25sdp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="#dimen/_15sdp"
android:src="#drawable/show_password_selector" />
3 - Put below code in java file.
iv_new_pwd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (iv_new_pwd.isSelected()) {
iv_new_pwd.setSelected(false);
Log.d("mytag", "in case 1");
edt_new_pwd.setInputType(InputType.TYPE_CLASS_TEXT);
} else {
Log.d("mytag", "in case 1");
iv_new_pwd.setSelected(true);
edt_new_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
}
});
You have to ask if the current text is already shown with dots, the function PasswordTransformationMethod.getInstance() allow you to do that.
This is my funtion in kotlin:
fun hideAndShowPassword(editText: EditText, indicator: ImageView) {
if (editText.transformationMethod == PasswordTransformationMethod.getInstance()) {
editText.transformationMethod = HideReturnsTransformationMethod.getInstance()
indicator.setImageDrawable(
ContextCompat.getDrawable(
editText.context,
R.drawable.eye
)
)
indicator.imageTintList =
ContextCompat.getColorStateList(editText.context, R.color.colorTintIcons)
} else {
editText.transformationMethod = PasswordTransformationMethod.getInstance()
indicator.setImageDrawable(
ContextCompat.getDrawable(
editText.context,
R.drawable.eye_off
)
)
indicator.imageTintList =
ContextCompat.getColorStateList(editText.context, R.color.colorTintIcons)
}
editText.setSelection(editText.text.length)
}
It seems that input_layout.isPasswordVisibilityToggleEnabled = true is deprecated. And in my case I did it that way in Kotlin:
input_edit_text.inputType = TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_PASSWORD
input_layout.endIconMode = END_ICON_PASSWORD_TOGGLE
Where input_edit_text is com.google.android.material.textfield.TextInputEditText and input_layout is com.google.android.material.textfield.TextInputLayout. Of course you should import these asl well:
import android.text.InputType.TYPE_CLASS_TEXT
import android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD
import com.google.android.material.textfield.TextInputLayout.END_ICON_PASSWORD_TOGGLE
My may customize the icon with provided methods as these:
input_layout.endIconDrawable = ...
input_layout.setEndIconOnClickListener { }
input_layout.setEndIconOnLongClickListener(...)
I used a OnClickListener() which is associated to the button that I want to use as toogle.
private EditText email_et, contraseña_et;
protected void onCreate(Bundle savedInstanceState) {
....
contraseña_et = (EditText) findViewById(R.id.contraseña_et);
....
vercontra_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int inputType = contraseña_et.getInputType();
if (inputType == 129){
contraseña_et.setInputType(1);
} else {
contraseña_et.setInputType(129);
}
contraseña_et.setSelection(contraseña_et.getText().length());
}
});
Reading docs, the int value seems to be different so I debugged to find the correct values, it's working awesome and is a little bit easier this way.
[Contraseña is password in spanish, btw]
In XML do like this
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="vertical"
>
<RelativeLayout
android:id="#+id/REFReLayTellFriend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<EditText
android:id="#+id/etpass1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:bottomLeftRadius="10dp"
android:bottomRightRadius="50dp"
android:fontFamily="#font/frutiger"
android:gravity="start"
android:inputType="textPassword"
android:hint="#string/regpass_pass1"
android:padding="20dp"
android:paddingBottom="10dp"
android:textColor="#000000"
android:textColorHint="#d3d3d3"
android:textSize="14sp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp"/>
<ImageButton
android:id="#+id/imgshowhide1"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="10dp"
android:background="#drawable/showpass"
android:layout_alignRight="#+id/etpass1"/>
</RelativeLayout>
boolean show=true;
//on image click inside password do this
if(show){
imgshowhide2.setBackgroundResource(0);
imgshowhide2.setBackgroundResource(R.drawable.hide);
etpass2.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
etpass2.setSelection(etpass2.getText().length());
show=false;
}else{
imgshowhide2.setBackgroundResource(0);
imgshowhide2.setBackgroundResource(R.drawable.showpass);
//etpass1.setInputType(InputType.TYPE_TEXT);
etpass2.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
etpass2.setSelection(etpass2.getText().length());
show=true;
}
My Kotlin extension . write once use everywhere
fun EditText.tooglePassWord() {
this.tag = !((this.tag ?: false) as Boolean)
this.inputType = if (this.tag as Boolean)
InputType.TYPE_TEXT_VARIATION_PASSWORD
else
(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD)
this.setSelection(this.length()) }
You can keep this method in any file and use it everywhere
use it like this
ivShowPassword.click { etPassword.tooglePassWord() }
where ivShowPassword is clicked imageview (eye) and etPassword is Editext
Add this method:
fun EditText.revertTransformation() {
transformationMethod = when(transformationMethod) {
is PasswordTransformationMethod -> SingleLineTransformationMethod.getInstance()
else -> PasswordTransformationMethod.getInstance()
}
}
Call it will switch between input type state (you may change the Single-Line transformation to your favorite). Usage example:
editText.revertTransformation()

Categories

Resources