How to create a bottom navigation bar with a snap-able indicator that always centers the selected option?
I have tried using TabLayout, had achieved the centering feature, but wasn't able to implement the snapping feature.
Design part:
<xxx.xxx.xxx.CenteringTabLayout
android:id="#+id/modes"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_alignParentBottom="true"
app:tabRippleColor="#android:color/transparent"
app:tabIndicatorFullWidth="false"
app:tabMode="scrolling"
app:tabIndicator="#drawable/mode_indicator"
app:tabGravity="center"
app:tabIndicatorHeight="30dp"
android:background="#android:color/transparent"
android:layout_marginVertical="12dp"
android:layout_marginHorizontal="8dp"/>
CenteringTabLayout.java
package xxx.xxx.xxx;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import androidx.camera.extensions.ExtensionMode;
import androidx.core.view.ViewCompat;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;
public class CenteringTabLayout extends TabLayout {
private final ArrayList<Integer> snapPoints = new ArrayList<>();
private int count = 0;
public CenteringTabLayout(Context context) {
super(context);
}
public CenteringTabLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CenteringTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private int sp = 0;
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
ViewGroup tabParent = (ViewGroup)getChildAt(0);
View firstTab = tabParent.getChildAt(0);
View lastTab = tabParent.getChildAt(tabParent.getChildCount()-1);
sp = (getWidth()/2) - (firstTab.getWidth()/2);
ViewCompat.setPaddingRelative(getChildAt(0), sp,0,(getWidth()/2) - (lastTab.getWidth()/2),0);
View centerTab = tabParent.getChildAt(tabParent.getChildCount()/2);
centerView(centerTab);
count = getTabCount();
snapPoints.clear();
int widthC = 0;
snapPoints.add(0);
for (int i = 0; i < count; ++i) {
View tabView = tabParent.getChildAt(i);
widthC+=tabView.getWidth()/2;
snapPoints.add(widthC + 19);
widthC+=tabView.getWidth()/2;
}
// widthC += tabParent.getChildAt(count-1).getWidth()/2;
snapPoints.add(widthC);
--count;
Log.i("TAG", Arrays.toString(snapPoints.toArray()));
}
private void centerView(View view){
scrollTo(getRelativeLeft(view) - sp - view.getPaddingLeft() , 0);
}
#Override
protected void onScrollChanged(int x, int t, int oldX, int oldT) {
if(Math.abs(oldX-x)<=1) return;
int i = 0;
while(i<count){
final int p = snapPoints.get(i);
final int n = snapPoints.get(++i);
Log.i("i:P,L,N", i+":"+p+","+x+","+n);
if(x>=p && x<=n){
--i;
if(getSelectedTabPosition()==i) return;
View tabView = Objects.requireNonNull(getTabAt(i)).view;
Log.i("Selected", String.valueOf(Objects.requireNonNull(getTabAt(i)).getText()));
tabView.performClick();
centerView(tabView);
return;
}
ExtensionMode;
}
super.onScrollChanged(x, t, oldX, oldT);
}
private int getRelativeLeft(View myView) {
if (myView.getParent() == myView.getRootView())
return myView.getLeft();
else
return myView.getLeft() + getRelativeLeft((View) myView.getParent());
}
}
I have roughly researched for other ways of doing it (using ViewPager + Button/ImageView and FrameLayout, bottom navigation bar, etc.) [not sure if they would fulfil all the requirements though], but does anyone know or could think of better way of implementing it?
You can try and use this library which does something similar to what you require with some incredible animations, but if you want to implement this exact behavior, ViewPager2 is your best option in my opinion, because it has all the features that you require and more, and you can customize it pretty easily.
Update:
For your specific use case, you can do it in a few steps:
Create an adapter for the ViewPager2 - when initializing, pass the list of modes you have as a text. I suggest you create a kind of dictionary with the index of every text value as the key and the text as the value, because to move between pages on click, or start from the middle, you need to call:
pager.setCurrentItem(itemIndex).
Set each page on click listener. See this link for how to do so.
Implement onPageSelcted() callback to show gesture of selecting item and switch between the camera modes. My implementation:
/**
* An extension function that gives a callback for moving between pages in the ViewPager2
*
* #param action A function to execute every time a different page is selected
*/
fun ViewPager2.onPageSelected(action: (Int) -> Unit) {
registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
action(position)
}
})
}
Initializing the adapter and the view pager:
List<String> modesList = new ArrayList();
modeslist.add("camera");
// todo: add the modes in the order that you want
CustomAdapter adapter = new CustomAdapter(modesList);
pager = (ViewPager2) findViewById(R.id.awesomepager); // Referencing the ViewPager
pager.setAdapter(adapter); // Setting view pager adapter
pager.setCurrentItem(theStartPositionIndex); // Setting the start position
pager.onPageSelected(page -> {
// todo: to what you want when a mode is selected
});
Hope this gives you a rough idea on how to implement your use case.
Related
I have used android.support.design.widget.TextInputLayout to make a password input that allows the user to toggle readability on the password. The xml is as follows:
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:hintEnabled="false"
app:passwordToggleDrawable="#drawable/password_toggle_selector"
app:passwordToggleEnabled="true" >
<android.support.design.widget.TextInputEditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="Password"
android:inputType="textPassword"/>
</android.support.design.widget.TextInputLayout>
The drawable selector is as described by How to customize android passwordToggleDrawable
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/password_toggle_show"
android:state_checked="true"/>
<item android:drawable="#drawable/password_toggle_hide"/>
</selector>
The issue is that the custom drawable becomes really large. Not larger than the edittext, but rather it seems to maximize its size while still fitting inside it (so, it seems to be bounded by the height of the element). However, if I leave the passwordToggleDrawable property unset, the drawable for the toggle is sized as is normal for android (I am sure you have seen the icon in other apps before). After much searching I have found a way to resize the custom one, but I am not happy with how its done (requires 2 extra xml files per drawable) and it only works for API 23+.
I would like to know if there is a good way to set the size of the drawable, or better yet, make it target the size of the default drawable?
I have tried setting the padding of the EditText as the source of TextInputLayout says that it gets the four paddings from it and apply to the mPasswordToggleView (line 1143), but it made no change on the icon and (as expected) also affected the padding of the EditText. I have tried setting minheight to 0. I have also tried changing between EditText and TextInputEditText (using the latter now as it seems to be recommended). I have tried switching the layout_height properties to wrap_content. I have tried scaling the drawable using xml's <scale> tag with the scale properties set. I have tried similarly with the <inset> tag. But none of those methods works.
The way I found (and am currently using) to resize the drawable that actually works is by using the xml tag <layer-list>, while setting the width and height properties. Then the <selector> xml file references those resized drawables instead of the png ones. But I don't like this solution because as I mentioned it requires API 23 and because of that results in a total of 4 extra xml files. It also sets the width and height by themselves, instead of keeping the ratio locked.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="#drawable/password_toggle_hide"
android:width="22dp"
android:height="15dp"/>
</layer-list>
TL;DR
How do I set the size of a custom passwordToggleDrawable in TextInputLayout? Preferably to same size as the default drawable.
I know this is an old question, but I faced the same problem and I believe I figure out a simple solution for this.
I'm using the TextInputLayout for the newest material library, and the only thing that I did was to find the reference for the endIcon from the TextInputLayout and change it's minimum dimensions.
val dimension = //here you get the dimension you want to
val endIconImageView = yourTextInputLayout.findViewById<ImageView>(R.id.text_input_end_icon)
endIconImageView.minimumHeight = dimension
endIconImageView.minimumWidth = dimension
yourTextInputLayout.requestLayout()
Important things to notice:
I did this on the OnFinishedInflated from a custom TextInputLayout, but I believe it will work fine on some activity class.
Cheers!
I face same problem. To avoid this situation I used png and set them based dpi like drawable-hdpi, drawable-mdpi etc. Also make those drawable as per radio. Hope that this tricks also work for you.
I were unable to find any solution to the question I actually asked, but I decided to instead solve the issue by disregarding the "in InputTextLayout" part of the question and implemented my own version of the class.
Mostly it is just a copy of InputTextLayout (sadly that class doesnt translate well for subclassing as everything is private) but with most of the stuff I dont need removed, and more importantly, with the CheckableImageButton mPasswordToggleView changed to a ViewGroup containing a View.
The ViewGroup is the clickable button, and handles setMinimumDimensions to keep the clickable area at min 48 dp, like the original did through design_text_input_password_icon.xml. This also makes small drawables not hug the right side of the screen as they are centered in the clickable area, giving the margin that the default drawable appears to have.
The View (or more precisely, a new subclass of it I called CheckableView) is the actual drawable (setBackground()), replacing the CheckableImageButton as the container of the drawable that lets it switch based on state_checked selector.
The xml-property passwordToggleSize allows a dimension to be set, which is used to scale the drawable. I opted to only have one value instead of width&height, and the drawable scales with its ratio locked such that its greatest dimension matches the dimension specified. I made the default size 24dp, as is specified for the default-drawable in design_ic_visibility.xml.
PasswordToggleLayout.java:
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.view.AbsSavedState;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.TextViewCompat;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.mylifediary.android.client.R;
public class PasswordToggleLayout extends LinearLayout {
// Default values from InputTextLayout's drawable and inflated layout
final int BUTTON_MIN_SIZE = 48; // The button is 48 dp at minimum.
final int DEFAULT_DRAWABLE_SIZE = 24; // The default drawable is 24 dp.
int mButtonMinSize;
final FrameLayout mInputFrame;
EditText mEditText;
private boolean mPasswordToggleEnabled;
private Drawable mPasswordToggleDrawable;
private CharSequence mPasswordToggleContentDesc;
ViewGroup mPasswordToggleViewGroup;
CheckableView mPasswordToggleView;
private boolean mPasswordToggledVisible;
private int mPasswordToggleSize;
private Drawable mPasswordToggleDummyDrawable;
private Drawable mOriginalEditTextEndDrawable;
private ColorStateList mPasswordToggleTintList;
private boolean mHasPasswordToggleTintList;
public PasswordToggleLayout(Context context) {
this(context, null);
}
public PasswordToggleLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public PasswordToggleLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOrientation(VERTICAL);
setWillNotDraw(false);
setAddStatesFromChildren(true);
mButtonMinSize = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, BUTTON_MIN_SIZE,
getResources().getDisplayMetrics());
mInputFrame = new FrameLayout(context);
mInputFrame.setAddStatesFromChildren(true);
addView(mInputFrame);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.PasswordToggleLayout, defStyleAttr,
R.style.Widget_Design_TextInputLayout);
mPasswordToggleEnabled = a.getBoolean(
R.styleable.PasswordToggleLayout_passwordToggleEnabled, false);
mPasswordToggleDrawable = a.getDrawable(
R.styleable.PasswordToggleLayout_passwordToggleDrawable);
mPasswordToggleContentDesc = a.getText(
R.styleable.PasswordToggleLayout_passwordToggleContentDescription);
if (a.hasValue(R.styleable.PasswordToggleLayout_passwordToggleTint)) {
mHasPasswordToggleTintList = true;
mPasswordToggleTintList = a.getColorStateList(
R.styleable.PasswordToggleLayout_passwordToggleTint);
}
mPasswordToggleSize = a.getDimensionPixelSize(
R.styleable.PasswordToggleLayout_passwordToggleSize,
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
DEFAULT_DRAWABLE_SIZE, getResources().getDisplayMetrics()));
a.recycle();
applyPasswordToggleTint();
}
private void setEditText(EditText editText) {
// If we already have an EditText, throw an exception
if (mEditText != null) {
throw new IllegalArgumentException(
"We already have an EditText, can only have one");
}
mEditText = editText;
final boolean hasPasswordTransformation = hasPasswordTransformation();
updatePasswordToggleView();
}
private void updatePasswordToggleView() {
if (mEditText == null) {
// If there is no EditText, there is nothing to update
return;
}
if (shouldShowPasswordIcon()) {
if (mPasswordToggleView == null) {
// Keep ratio
double w = mPasswordToggleDrawable.getIntrinsicWidth();
double h = mPasswordToggleDrawable.getIntrinsicHeight();
double scale = mPasswordToggleSize / Math.max(w,h);
int scaled_width = (int) (w * scale);
int scaled_height = (int) (h * scale);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT,
Gravity.CENTER_VERTICAL | Gravity.END | Gravity.RIGHT);
FrameLayout.LayoutParams lp2 = new FrameLayout.LayoutParams(
scaled_width, scaled_height, Gravity.CENTER);
mPasswordToggleViewGroup = new FrameLayout(this.getContext());
mPasswordToggleViewGroup.setMinimumWidth(mButtonMinSize);
mPasswordToggleViewGroup.setMinimumHeight(mButtonMinSize);
mPasswordToggleViewGroup.setLayoutParams(lp);
mInputFrame.addView(mPasswordToggleViewGroup);
mPasswordToggleViewGroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
passwordVisibilityToggleRequested(false);
}
});
mPasswordToggleView = new CheckableView(this.getContext());
mPasswordToggleView.setBackground(mPasswordToggleDrawable);
mPasswordToggleView.setContentDescription(mPasswordToggleContentDesc);
mPasswordToggleView.setLayoutParams(lp2);
mPasswordToggleViewGroup.addView(mPasswordToggleView);
}
if (mEditText != null && ViewCompat.getMinimumHeight(mEditText) <= 0) {
// We should make sure that the EditText has the same min-height
// as the password toggle view. This ensure focus works properly,
// and there is no visual jump if the password toggle is enabled/disabled.
mEditText.setMinimumHeight(
ViewCompat.getMinimumHeight(mPasswordToggleViewGroup));
}
mPasswordToggleViewGroup.setVisibility(VISIBLE);
mPasswordToggleView.setChecked(mPasswordToggledVisible);
// Need to add a dummy drawable as the end compound drawable so that
// the text is indented and doesn't display below the toggle view.
if (mPasswordToggleDummyDrawable == null) {
mPasswordToggleDummyDrawable = new ColorDrawable();
}
// Important to use mPasswordToggleViewGroup, as mPasswordToggleView
// wouldn't replicate the margin of the default-drawable.
mPasswordToggleDummyDrawable.setBounds(
0, 0, mPasswordToggleViewGroup.getMeasuredWidth(), 1);
final Drawable[] compounds = TextViewCompat.getCompoundDrawablesRelative(mEditText);
// Store the user defined end compound drawable so that we can restore it later
if (compounds[2] != mPasswordToggleDummyDrawable) {
mOriginalEditTextEndDrawable = compounds[2];
}
TextViewCompat.setCompoundDrawablesRelative(mEditText, compounds[0],
compounds[1], mPasswordToggleDummyDrawable, compounds[3]);
// Copy over the EditText's padding so that we match
mPasswordToggleViewGroup.setPadding(mEditText.getPaddingLeft(),
mEditText.getPaddingTop(), mEditText.getPaddingRight(),
mEditText.getPaddingBottom());
} else {
if (mPasswordToggleViewGroup != null
&& mPasswordToggleViewGroup.getVisibility() == VISIBLE) {
mPasswordToggleViewGroup.setVisibility(View.GONE);
}
if (mPasswordToggleDummyDrawable != null) {
// Make sure that we remove the dummy end compound drawable if
// it exists, and then clear it
final Drawable[] compounds = TextViewCompat.getCompoundDrawablesRelative(mEditText);
if (compounds[2] == mPasswordToggleDummyDrawable) {
TextViewCompat.setCompoundDrawablesRelative(mEditText,
compounds[0], compounds[1],
mOriginalEditTextEndDrawable, compounds[3]);
mPasswordToggleDummyDrawable = null;
}
}
}
}
private void applyPasswordToggleTint() {
if (mPasswordToggleDrawable != null && mHasPasswordToggleTintList) {
mPasswordToggleDrawable = DrawableCompat.wrap(mPasswordToggleDrawable).mutate();
DrawableCompat.setTintList(mPasswordToggleDrawable, mPasswordToggleTintList);
if (mPasswordToggleView != null
&& mPasswordToggleView.getBackground() != mPasswordToggleDrawable) {
mPasswordToggleView.setBackground(mPasswordToggleDrawable);
}
}
}
private void passwordVisibilityToggleRequested(boolean shouldSkipAnimations) {
if (mPasswordToggleEnabled) {
// Store the current cursor position
final int selection = mEditText.getSelectionEnd();
if (hasPasswordTransformation()) {
mEditText.setTransformationMethod(null);
mPasswordToggledVisible = true;
} else {
mEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
mPasswordToggledVisible = false;
}
mPasswordToggleView.setChecked(mPasswordToggledVisible);
if (shouldSkipAnimations) {
mPasswordToggleView.jumpDrawablesToCurrentState();
}
// And restore the cursor position
mEditText.setSelection(selection);
}
}
private boolean hasPasswordTransformation() {
return mEditText != null
&& mEditText.getTransformationMethod() instanceof PasswordTransformationMethod;
}
private boolean shouldShowPasswordIcon() {
return mPasswordToggleEnabled && (hasPasswordTransformation() || mPasswordToggledVisible);
}
#Override
public void addView(View child, int index, final ViewGroup.LayoutParams params) {
if (child instanceof EditText) {
// Make sure that the EditText is vertically at the bottom,
// so that it sits on the EditText's underline
FrameLayout.LayoutParams flp = new FrameLayout.LayoutParams(params);
flp.gravity = Gravity.CENTER_VERTICAL
| (flp.gravity & ~Gravity.VERTICAL_GRAVITY_MASK);
mInputFrame.addView(child, flp);
// Now use the EditText's LayoutParams as our own and update them
// to make enough space for the label
mInputFrame.setLayoutParams(params);
setEditText((EditText) child);
} else {
// Carry on adding the View...
super.addView(child, index, params);
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
updatePasswordToggleView();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
#Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.isPasswordToggledVisible = mPasswordToggledVisible;
return ss;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
if (ss.isPasswordToggledVisible) {
passwordVisibilityToggleRequested(true);
}
requestLayout();
}
static class SavedState extends AbsSavedState {
boolean isPasswordToggledVisible;
SavedState(Parcelable superState) {
super(superState);
}
SavedState(Parcel source, ClassLoader loader) {
super(source, loader);
isPasswordToggledVisible = (source.readInt() == 1);
}
#Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(isPasswordToggledVisible ? 1 : 0);
}
public static final Creator<SavedState> CREATOR = new ClassLoaderCreator<SavedState>() {
#Override
public SavedState createFromParcel(Parcel in, ClassLoader loader) {
return new SavedState(in, loader);
}
#Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in, null);
}
#Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
public static class CheckableView extends View {
private final int[] DRAWABLE_STATE_CHECKED =
new int[]{android.R.attr.state_checked};
private boolean mChecked;
public CheckableView(Context context) {
super(context);
}
public CheckableView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
}
public CheckableView(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setChecked(boolean checked) {
if (mChecked != checked) {
mChecked = checked;
refreshDrawableState();
}
}
#Override
public int[] onCreateDrawableState(int extraSpace) {
if (mChecked) {
return mergeDrawableStates(
super.onCreateDrawableState(extraSpace
+ DRAWABLE_STATE_CHECKED.length), DRAWABLE_STATE_CHECKED);
} else {
return super.onCreateDrawableState(extraSpace);
}
}
}
}
And then in an attrs.xml:
<declare-styleable name="PasswordToggleLayout">
<attr name="passwordToggleEnabled" format="boolean"/>
<attr name="passwordToggleDrawable" format="reference"/>
<attr name="passwordToggleContentDescription" format="string"/>
<attr name="passwordToggleTint" format="color"/>
<attr name="passwordToggleSize" format="dimension"/>
</declare-styleable>
Same issue for me. The problem comes from the gradle material API implementation:
implementation 'com.google.android.material:material:1.1.0'
downgrade to version 1.0.0 fixes the issue:
implementation 'com.google.android.material:material:1.0.0'
Is it possible to make the TextInputLayout label to show above the left drawable of an EditText perpendicularly when user focuses or types in the EditText.
Here is the xml of the EditText:
<android.support.design.widget.TextInputLayout
android:id="#+id/completion_date_layout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_weight="1"
android:orientation="horizontal">
<EditText
android:id="#+id/etTaskDate"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="#string/title_completion_date"
android:inputType="text"
android:drawableLeft="#drawable/ic_date"
android:paddingBottom="15dp"
android:drawablePadding="5dp"
android:textSize="#dimen/fields_text_size"/>
</android.support.design.widget.TextInputLayout>
Here is the desired output:
Here is the output that I am getting:
Thanks to Java's member access model and Google's developers who left a small loophole it could be achieved with a simple subclassing which repeats a minimum of the original code:
package android.support.design.widget;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
public final class TextInputLayoutEx extends TextInputLayout {
private final int mDefaultPadding = __4DP__;
private final Rect mTmpRect = new Rect();
public TextInputLayoutEx(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (isHintEnabled() && mEditText != null) {
final Rect rect = mTmpRect;
ViewGroupUtils.getDescendantRect(this, mEditText, rect);
mCollapsingTextHelper.setCollapsedBounds(
rect.left + mDefaultPadding, getPaddingTop(),
rect.right - mDefaultPadding, bottom - top - getPaddingBottom());
mCollapsingTextHelper.recalculate();
}
}
}
Here we put a new class to the same package which opens an access to the mCollapsingTextHelper with a package-level visibility and then repeat part of the code from the original onLayout method which manages field name positioning. The __4DP__ value is 4dp value converted to pixels, I'm pretty sure everyone has an utility method for this.
In your xml layout just switch from the android.support.design.widget.TextInputLayout to android.support.design.widget.TextInputLayoutEx so your layout looks like this:
<android.support.design.widget.TextInputLayoutEx
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Mobile">
<android.support.design.widget.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_phone_black_24dp"
android:drawablePadding="4dp"/>
</android.support.design.widget.TextInputLayoutEx>
And the result is
At the moment it works for com.android.support:design:25.3.1
I have made a workaround regarding this issue. It may be a bit unreliable but it works on my end.
Here is the code:
String spacer=" ";
EditText myEditText= (EditText)findViewById(R.id.myEditText);
myEditText.setText(spacer + "Today");
myEditText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_calendar, 0, 0, 0);
What I did here was placing a spacer before the text inside the editText, then add the drawable left programatically.
But make sure to remove those spaces before fetching the contents of the editText:
String title = myEditText.getText().toString().substring(8);
This means i cropped the 8 spaces before the word "Today".
You can use animation and frame_layout to animate the left icon, try this link, may be helpful for you.
You can try this custom class: find here
and then just change in xml
com.mycompany.myapp.CustomTextInputLayout
import android.content.Context;
import android.graphics.Rect;
import android.support.design.widget.TextInputLayout;
import android.util.AttributeSet;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class CustomTextInputLayout extends TextInputLayout {
private Object collapsingTextHelper;
private Rect bounds;
private Method recalculateMethod;
public CustomTextInputLayout(Context context) {
this(context, null);
}
public CustomTextInputLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomTextInputLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
adjustBounds();
}
private void init() {
try {
Field cthField = TextInputLayout.class.getDeclaredField("mCollapsingTextHelper");
cthField.setAccessible(true);
collapsingTextHelper = cthField.get(this);
Field boundsField = collapsingTextHelper.getClass().getDeclaredField("mCollapsedBounds");
boundsField.setAccessible(true);
bounds = (Rect) boundsField.get(collapsingTextHelper);
recalculateMethod = collapsingTextHelper.getClass().getDeclaredMethod("recalculate");
}
catch (NoSuchFieldException | IllegalAccessException | NoSuchMethodException e) {
collapsingTextHelper = null;
bounds = null;
recalculateMethod = null;
e.printStackTrace();
}
}
private void adjustBounds() {
if (collapsingTextHelper == null) {
return;
}
try {
bounds.left = getEditText().getLeft() + getEditText().getPaddingLeft();
recalculateMethod.invoke(collapsingTextHelper);
}
catch (InvocationTargetException | IllegalAccessException | IllegalArgumentException e) {
e.printStackTrace();
}
}
}
Im new in Android world. I want to put some parallax background effects in my app.
How can I do it? How to approach to this in Android?
Is there any productive way to create 2-3 layer parallax background? Is there some tool, or class in android API?
Or maybe I have to modify background image location or margins "manually" in code?
Im using API level 19.
I have tried to understand Paralloid library, but this is too big to understand without any explanation. Im new to Android and Java, im not familiar with all Layouts and other UI objects, however I'm familiar with MVC.
I started bounty, maybe someone can explain step by step how that library works.
This is what you can do:
In your activity/fragment layout file specify 2 ScrollView's (say background_sv and content_sv).
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.parallax.MyScrollView
android:id="#+id/background_sv"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/parallax_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="..." />
</com.example.parallax.MyScrollView>
<com.example.parallax.MyScrollView
android:id="#+id/content_sv"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</com.example.parallax.MyScrollView>
</RelativeLayout>
Add a dummy view in the content scrollview of the height of the background and make it transparent. Now, attach a scroll listener to the content_sv. When the content scrollview is scrolled, call
mBgScrollView.scrollTo(0, (int)(y /*scroll Of content_sv*/ / 2f));
The existing API's doesn't have the support to get the scroll events.
Hence, we need to create a Custom ScrollView, to provide the ScrollViewListener.
package com.example.parallax;
// imports;
public class MyScrollView extends ScrollView {
public interface ScrollViewListener {
void onScrollChanged(MyScrollView scrollView, int x, int y, int oldx, int oldy);
}
private ScrollViewListener scrollViewListener = null;
public MyScrollView(Context context) {
super(context);
}
public MyScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setScrollViewListener(ScrollViewListener scrollViewListener) {
this.scrollViewListener = scrollViewListener;
}
#Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {
super.onScrollChanged(x, y, oldx, oldy);
if(scrollViewListener != null) {
scrollViewListener.onScrollChanged(this, x, y, oldx, oldy);
}
}
}
Here is the activity which hosts both the content ScrollView and background ScrollView
package com.example.parallax;
// imports;
public class ParallaxActivity extends Activity implements ScrollViewListener {
private MyScrollView mBgScrollView;
private MyScrollView mContentScrollView;
#Override
public void onCreate(Bundle savedInstanceState) {
mBgScrollView = findViewById(R.id.background_sv);
mContentScrollView = findViewById(R.id.content_sv);
mContentScrollView.setOnScrollListener(this);
}
// this is method for onScrollListener put values according to your need
#Override
public void onScrollChanged(MyScrollView scrollView, int x, int y, int oldx, int oldy) {
super.onScrollChanged(scrollView, x, y, oldx, oldy);
// when the content scrollview will scroll by say 100px,
// the background scrollview will scroll by 50px. It will
// look like a parallax effect where the background is
// scrolling with a different speed then the content scrollview.
mBgScrollView.scrollTo(0, (int)(y / 2f));
}
}
I think the question is unclear, so this is not really an answer so much as an attempt to clarify with more detail than I could include in a comment.
My question is about what kind of parallax effect you want to achieve. Given these three examples (they are demo apps you can install from the Play Store), which if any has the type of parallax effect you want? Please answer in a comment.
Paralloid Demo
Parallax Scroll Demo
Google IO App
Given an answer, we all will find it easier to help out. If you edit your question to include this information, it will be improved.
The following contains an example application published by the author of Paralloid:
https://github.com/chrisjenx/Paralloid/tree/master/paralloidexample
From the GitHub page under the 'Getting Started' section:
Layout
ScrollView
This is an example, please refer to the paralloidexample App for full
code.
<FrameLayout ..>
<FrameLayout
android:id="#+id/top_content"
android:layout_width="match_parent"
android:layout_height="192dp"/>
<uk.co.chrisjenx.paralloid.views.ParallaxScrollView
android:id="#+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:id="#+id/scroll_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="192dp"/>
</uk.co.chrisjenx.paralloid.views.ParallaxScrollView>
</FrameLayout>
Fragment
Inside your onViewCreated() or onCreateView().
//...
FrameLayout topContent = (FrameLayout) rootView.findViewById(R.id.top_content);
ScrollView scrollView = (ScrollView) rootView.findViewById(R.id.scroll_view);
if (scrollView instanceof Parallaxor) {
((Parallaxor) scrollView).parallaxViewBy(topContent, 0.5f);
}
// TODO: add content to top/scroll content
Thats it!
Have a look at the Parallaxor interface for applicable Parallax
methods.
Hope this helps!
Also, here is a link to Google's 'getting started' page for android.
Also, here is a link to a 'java tutorial for complete beginners'.
As well as link to some documentation about layouts, which 'define the visual structure for a user interface'.
That being said, you would use the layout to define what the interface looks like and use the subsequent example code to define what happens when you interact with it.
P.S. You can see the application in action here
I use the ParallaxScroll library. Very easy to use, good samples and well documented.
Here is how it can be done using ScrollView and it's background image. I've committed the code in github.
You need to extend the ScrollView and Drawable classes.
By default the ScrollView background height will be same as viewport height. To achieve the parallax effect, the background height should be larger and should be based on the ScrollView child height and the background scrolling factor we want to impose.
Background scroll factor of 1 indicates, background height is same as ScrollView child height and hence background will scroll with same offset as the child scrolls.
0.5 indicates, background height is 0.5 times ScrollView child extended height and will scroll 50% slower compared to the child contents. This effectively brings the parallax scrolling effect.
Call following method from ScrollView constructor:
void init() {
// Calculate background drawable size before first draw of scrollview
getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
// Remove the listener
getViewTreeObserver().removeOnPreDrawListener(this);
mDrawable = (ParallaxDrawable) getBackground();
if(mDrawable != null && mDrawable instanceof ParallaxDrawable) {
// Get the only child of scrollview
View child = getChildAt(0);
int width = child.getWidth();
// calculate height of background based on child height and scroll factor
int height = (int) (getHeight() + (child.getHeight() - getHeight()) * mScrollFactor);
mDrawable.setSize(width, height);
}
return true;
}
});
}
When ScrollView is scrolled, take into consideration the scroll offset while drawing the background. This basically achieves the parallax effect.
ParallaxScrollView:
protected void onScrollChanged(int x, int y, int oldX, int oldY) {
if(mDrawable != null && mDrawable instanceof ParallaxDrawable) {
// set the scroll offset for the background drawable.
mDrawable.setScrollOffset(x*mScrollFactor, y*mScrollFactor);
}
}
ParallaxDrawable:
#Override
public void draw(Canvas canvas) {
// To move the background up, translate canvas by negative offset
canvas.translate(-mScrollXOffset, -mScrollYOffset);
mDrawable.draw(canvas);
canvas.translate(mScrollXOffset, mScrollYOffset);
}
protected void onBoundsChange(Rect bounds) {
// This sets the size of background drawable.
mDrawable.setBounds(new Rect(bounds.top, bounds.left, bounds.left + mWidth, bounds.top + mHeight));
}
Usage of ParallaxScrollView and ParallaxDrawable:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parallax_layout);
final ParallaxScrollView scrollView = (ParallaxScrollView) findViewById(R.id.sv);
ParallaxDrawable drawable = new ParallaxDrawable(getResources().getDrawable(R.drawable.bg));
scrollView.setBackground( drawable, 0.2f );
}
}
parallax_layout.xml:
<manish.com.parallax.ParallaxScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/sv"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#fff"
android:text="#string/text" />
<View
android:layout_width="match_parent"
android:layout_height="5dp" />
...
</LinearLayout>
</manish.com.parallax.ParallaxScrollView>
The Android API does not support much concrete tools for it as you probably noticed. In API 20 they added elevation which is an attribute for depth. This does not support parallax layouts itself but I would say it's a step by Google to make this kind of work easier. If you want a wild guess on if and when, I would say that parallax utilities could be added before API 25 is released, based on the latest update and the progress in battery efficiency.
For now all you need is to listen for some kind of movement and change the views positions based on a value representing elevation.
Your question made me upgrade my own project and this is how I did it using ViewDragHelper inside a Fragment.
public class MainFragment extends Fragment implements View.OnTouchListener {
private ImageView mDecor, mBamboo, mBackgroundBamboo;
private RelativeLayout mRootLayout;
private ViewDragHelper mDragHelper;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRootLayout = (RelativeLayout) inflater.inflate(R.layout.fragment_main, container, false);
mRootLayout.setOnTouchListener(this);
mDecor = (ImageView) mRootLayout.findViewById(R.id.decor);
mBamboo = (ImageView) mRootLayout.findViewById(R.id.bamboo);
mBackgroundBamboo = (ImageView) mRootLayout.findViewById(R.id.backround_bamboo);
mDragHelper = ViewDragHelper.create(mRootLayout, 1.0f, new ViewDragHelper.Callback() {
private final float MAX_LEFT = -0;
private final float MAX_TOP = -20;
private final float MAX_RIGHT = 50;
private final float MAX_BOTTOM = 10;
private final float MULTIPLIER = 0.1f;
private final int DECOR_ELEVATION = 3;
private final int FRONT_BAMBOO_ELEVATION = 6;
private final int BACKGROUND_BAMBOO_ELEVATION = 1;
private float mLeft = 0;
private float mTop = 0;
#Override
public boolean tryCaptureView(View view, int i) {
return true;
}
#Override
public int clampViewPositionVertical(View child, int top, int dy) {
mTop += dy * MULTIPLIER;
mTop = mTop > MAX_BOTTOM ? MAX_BOTTOM : mTop < MAX_TOP ? MAX_TOP : mTop;
mDecor.setTranslationY(mTop * DECOR_ELEVATION);
mBamboo.setTranslationY(mTop * FRONT_BAMBOO_ELEVATION);
mBackgroundBamboo.setTranslationY(mTop * BACKGROUND_BAMBOO_ELEVATION);
return 0;
}
#Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
mLeft += dx * MULTIPLIER;
mLeft = mLeft < MAX_LEFT ? MAX_LEFT : mLeft > MAX_RIGHT ? MAX_RIGHT : mLeft;
mDecor.setTranslationX(mLeft * DECOR_ELEVATION);
mBamboo.setTranslationX(mLeft * FRONT_BAMBOO_ELEVATION);
mBackgroundBamboo.setTranslationX(mLeft * BACKGROUND_BAMBOO_ELEVATION);
return 0;
}
#Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy){
mRootLayout.requestLayout();
}
});
return mRootLayout;
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mDragHelper.processTouchEvent(motionEvent);
// you can still use this touch listener for buttons etc.
return true;
}
}
Hi You can go with the below-given code for ParallaxView class
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.ArrayList;
public class ParallaxView extends SurfaceView implements Runnable {
private volatile boolean running;
private Thread gameThread = null;
// For drawing
private Paint paint;
private Canvas canvas;
private SurfaceHolder ourHolder;
// Holds a reference to the Activity
Context context;
// Control the fps
long fps =60;
// Screen resolution
int screenWidth;
int screenHeight;
ParallaxView(Context context, int screenWidth, int screenHeight) {
super(context);
this.context = context;
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
// Initialize our drawing objects
ourHolder = getHolder();
paint = new Paint();
}
#Override
public void run() {
while (running) {
long startFrameTime = System.currentTimeMillis();
update();
draw();
// Calculate the fps this frame
long timeThisFrame = System.currentTimeMillis() - startFrameTime;
if (timeThisFrame >= 1) {
fps = 1000 / timeThisFrame;
}
}
}
private void update() {
// Update all the background positions
}
private void draw() {
if (ourHolder.getSurface().isValid()) {
//First we lock the area of memory we will be drawing to
canvas = ourHolder.lockCanvas();
//draw a background color
canvas.drawColor(Color.argb(255, 0, 3, 70));
// Draw the background parallax
// Draw the rest of the game
paint.setTextSize(60);
paint.setColor(Color.argb(255, 255, 255, 255));
canvas.drawText("I am a plane", 350, screenHeight / 100 * 5, paint);
paint.setTextSize(220);
canvas.drawText("I'm a train", 50, screenHeight / 100*80, paint);
// Draw the foreground parallax
// Unlock and draw the scene
ourHolder.unlockCanvasAndPost(canvas);
}
}
// Clean up our thread if the game is stopped
public void pause() {
running = false;
try {
gameThread.join();
} catch (InterruptedException e) {
// Error
}
}
// Make a new thread and start it
// Execution moves to our run method
public void resume() {
running = true;
gameThread = new Thread(this);
gameThread.start();
}
}// End of ParallaxView
To know more you can go **
here
**: http://gamecodeschool.com/android/coding-a-parallax-scrolling-background-for-android/
I want to display the ToolTip(QuickAction View) when I am moving my cursor on the view. Can any one please give me the simple example for it? tooltip will only contains the text value.
Possibly using myView.setTooltipText(CharSequence) (from API-level 26) or TooltipCompat (prior to API-level 26) is an additonal option:
TooltipCompat.setTooltipText(myView, context.getString(R.string.myString));
Documentation says:
Helper class used to emulate the behavior of {#link View#setTooltipText(CharSequence)} prior to API level 26.
Using AndroidX is the recommended way.
Android 4.0 (API 14) and higher
AndroidX support Library added support for tooltips (small popup windows with descriptive text) for views and menu items.
Use setTooltipText to set the tooltip text which will be displayed in a small popup next to the view.
See the following example:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
TooltipCompat.setTooltipText(fab, "Send an email");
The tooltip will be displayed:
On long click, unless it is handled otherwise (by OnLongClickListener or a context menu).
On hover, after a brief delay since the pointer has stopped moving
To add the Appcompat library into your project,
Open the build.gradle file for your application.
Add the support library to the dependencies section.
dependencies {
compile "androidx.appcompat:appcompat:1.1.0"
}
Android 8.0 (API level 26) and higher
If your minimum supported version is Android 8.0 (API level 26) and higher, you can specify the tooltip text in a View by calling the setTooltipText() method. You can also set the tooltipText property using the corresponding XML.
To specify the tooltip text in your XML files, set the android:tooltipText attribute, as shown in the following example:
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:tooltipText="Send an email" />
To specify the tooltip text in your code, use the setTooltipText(CharSequence) method, as shown in the following example:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setTooltipText("Send an email");
Android supports "tool-tip" only for ActionBar buttons from Android 4.0 on. But as Jaguar already mentioned, tool-tips in Android doesnt make so much sense, since there is no concept of hovering.
From Android 4.0 the normal title text (that you set in the xml file or via code) will appear if you make a long click on the button. But if enough space is on the screen, it will be visible in the ActionBar all the time beside the icon.
If you want to have it for a custom view, you need to implement it yourself by adding a LongClickListener to your view, and show a Toast when pressed long:
view.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
Toast.makeText(v.getContext(), "My tool-tip text", Toast.LENGTH_SHORT).show();
return true;
}
}
Of course you should use a resource for the string, and not the hard coded string.
Starting with Android API 14+, there is an event for hovering. You can do,
view.setOnHoverListener(...)
and listen for MotionEvents such as ACTION_HOVER_ENTER and ACTION_HOVER_EXIT, instead of onLongClick.
Based on GregoryK's answer, I've created a new ImageButton class - see code below. To use it, all you need to do is replace the ImageButton in your layouts with com.yourpackage.ImageButtonWithToolTip and give it an android:contentDescription attribute (as that is the text that will be shown in the tool tip).
package com.yourpackage;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class ImageButtonWithToolTip extends ImageButton {
private static final int ESTIMATED_TOAST_HEIGHT_DIPS = 48;
public ImageButtonWithToolTip(Context context) {
super(context);
init();
}
public ImageButtonWithToolTip(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ImageButtonWithToolTip(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
#TargetApi(21)
public ImageButtonWithToolTip(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
/**
* You should set the android:contentDescription attribute in this view's XML layout file.
*/
String contentDescription = getContentDescription().toString();
if (TextUtils.isEmpty(contentDescription)) {
/**
* There's no content description, so do nothing.
*/
return false; // Not consumed
}
else {
final int[] screenPos = new int[2]; // origin is device display
final Rect displayFrame = new Rect(); // includes decorations (e.g. status bar)
view.getLocationOnScreen(screenPos);
view.getWindowVisibleDisplayFrame(displayFrame);
final Context context = view.getContext();
final int viewWidth = view.getWidth();
final int viewHeight = view.getHeight();
final int viewCenterX = screenPos[0] + viewWidth / 2;
final int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
final int estimatedToastHeight = (int) (ESTIMATED_TOAST_HEIGHT_DIPS
* context.getResources().getDisplayMetrics().density);
Toast toolTipToast = Toast.makeText(context, contentDescription, Toast.LENGTH_SHORT);
boolean showBelow = screenPos[1] < estimatedToastHeight;
if (showBelow) {
// Show below
// Offsets are after decorations (e.g. status bar) are factored in
toolTipToast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL,
viewCenterX - screenWidth / 2,
screenPos[1] - displayFrame.top + viewHeight);
}
else {
// Show above
// Offsets are after decorations (e.g. status bar) are factored in
// NOTE: We can't use Gravity.BOTTOM because when the keyboard is up
// its height isn't factored in.
toolTipToast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL,
viewCenterX - screenWidth / 2,
screenPos[1] - displayFrame.top - estimatedToastHeight);
}
toolTipToast.show();
return true; // Consumed
}
}
});
}
}
You can use the same approach for extending other views - for example, Button.
Android doesn't have tool tips. It is a touch-based UI. Current touch sensors can't generally detect hovering in a way that tool tips would be useful.
There's no concept of "hovering" in a touch screen, but you could set a LongClickListener for your View, and have a Toast appear after a long press.
If you need to show tool tip for any view, you can use CheatSheet util class from Roman Nurik. (Uses Toast and optionally content description to show tooltip.)
It is
Android helper class for showing cheat sheets (tooltips) for icon-only
UI elements on long-press. This is already default platform behavior
for icon-only action bar items and tabs. This class provides this
behavior for any other such UI element
package com.nbfc.tekis.tooltipexample;
import android.support.v7.app.AppCompatActivity; import
android.os.Bundle; import android.view.View; import
android.widget.Button; import android.widget.GridView;
import it.sephiroth.android.library.tooltip.Tooltip;
public class MainActivity extends AppCompatActivity {
/*Button button1,button2,button3,button4;*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void bottomTooltip(View view) {
Button button1=(Button)findViewById(R.id.button1);
Tooltip.make(this,new Tooltip.Builder()
.anchor(button1, Tooltip.Gravity.BOTTOM)
.closePolicy(new Tooltip.ClosePolicy()
.insidePolicy(true,false)
.outsidePolicy(true,false),4000)
.activateDelay(900)
.showDelay(400)
.text("Android tooltip bottom")
.maxWidth(600)
.withArrow(true)
.withOverlay(true)
.build())
.show();
}
public void topTooltip(View view) {
Button button3=(Button)findViewById(R.id.button3);
Tooltip.make(this,new Tooltip.Builder()
.anchor(button3, Tooltip.Gravity.TOP)
.closePolicy(new Tooltip.ClosePolicy()
.insidePolicy(true,false)
.outsidePolicy(true,false),4000)
.activateDelay(900)
.showDelay(400)
.text("Android tooltip top")
.maxWidth(600)
.withOverlay(true)
.withArrow(true)
.build())
.show();
}
public void rightTooltip(View view) {
Button button2=(Button)findViewById(R.id.button2);
Tooltip.make(this,new Tooltip.Builder()
.anchor(button2, Tooltip.Gravity.RIGHT)
.closePolicy(new Tooltip.ClosePolicy()
.insidePolicy(true,false)
.outsidePolicy(true,false),4000)
.activateDelay(900)
.showDelay(400)
.text("Android tooltip right")
.maxWidth(600)
.withArrow(true)
.withOverlay(true)
.build())
.show();
}
public void leftTooltip(View view) {
Button button4=(Button)findViewById(R.id.button4);
Tooltip.make(this,new Tooltip.Builder()
.anchor(button4, Tooltip.Gravity.LEFT)
.closePolicy(new Tooltip.ClosePolicy()
.insidePolicy(true,false)
.outsidePolicy(true,false),4000)
.text("Android tooltip left")
.maxWidth(600)
.withArrow(true)
.withOverlay(true)
.build())
.show();
}
}
add this to your button
android:tooltipText="Tooltip text goes here"
Based on ban's Answer, I've created this method.
It does not assume anything about the toast size. Simply places the tool tip gravity based on where the view is relative to the window (i.e. left/right/above/below the center of the window). The toast always starts from center of the view and will stretch towards the right/left/bottom/top respectively.
See Example
private static void setToastGravity(View view, Toast toast) {
final Rect viewRect = new Rect(); // view rect
final Rect windowRect = new Rect(); // window rect
view.getGlobalVisibleRect(viewRect);
view.getWindowVisibleDisplayFrame(windowRect);
int offsetX;
int offsetY;
int gravityX;
int gravityY;
if (viewRect.centerY() > windowRect.centerY()) {
// above
offsetY = windowRect.bottom - viewRect.centerY();
gravityY = Gravity.BOTTOM;
} else {
// tooltip below the view
offsetY = viewRect.centerY() - windowRect.top;
gravityY = Gravity.TOP;
}
if (viewRect.centerX() > windowRect.centerX()) {
// tooltip right of the view
offsetX = windowRect.right - viewRect.centerX();
gravityX = Gravity.END;
} else {
// tooltip left of the view
offsetX = viewRect.centerX() - windowRect.left;
gravityX = Gravity.START;
}
toast.setGravity(gravityX | gravityY, offsetX, offsetY);
}
https://github.com/skydoves/Balloon
This library provides a lightweight, popup like tooltips, fully customizable with an arrows and animations. 100% Kotlin with all necessary documentation. It is actively being managed as well.
Here are some gif from their page;
another,
I will Happy to help you
Please sir Try this ->
android-simple-tooltip
I hope that will work for you
Example :
Release
Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}
}
Add the dependency
dependencies {
implementation 'com.github.douglasjunior:android-simple-tooltip:0.2.3'
}
Add this code in your MainActivity class and make an object for your view which will you want to bind with tooltip
View yourView = findViewById(R.id.your_view);
new SimpleTooltip.Builder(this)
.anchorView(yourView)
.text("Texto do Tooltip")
.gravity(Gravity.END)
.animated(true)
.transparentOverlay(false)
.build()
.show();
I am using TableLayout. which have 100 of items to make it scrollable I am using Tablelayout inside ScrollView. But I have to detect whether the user have scrolled to the last row. If the user have scrolled to the last view then user will be shown a Toast message.
But How to know that the user has scrolled to the last row of the tablelayout. I have referred the code from TableLayout inside ScrollView.
http://huuah.com/using-tablelayout-on-android/
If new scrolled y position + scroll view height >= tableview height that means you have reached the end of list.
To achieve this you have to write your custiom scrollview.
Step-1 You have to create custom scroll view extending ScrollView
package com.sunil;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;
public class LDObservableScrollView extends ScrollView {
private LDObservableScrollViewListener scrollViewListener = null;
public LDObservableScrollView(Context context) {
super(context);
}
public LDObservableScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public LDObservableScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setScrollViewListener(LDObservableScrollViewListener scrollViewListener) {
this.scrollViewListener = scrollViewListener;
}
#Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {
super.onScrollChanged(x, y, oldx, oldy);
if(scrollViewListener != null) {
scrollViewListener.onScrollChanged(this, x, y, oldx, oldy);
}
}
}
Step-2 Create a Listener to detect scrollchanged
package com.sunil;
import LDObservableScrollView;
public interface LDObservableScrollViewListener {
void onScrollChanged(LDObservableScrollView scrollView, int x, int y, int oldx, int oldy);
}
Step-3 in layout xml instead of ScrollView use the custom scroll view
<com.abc.LDObservableScrollView android:layout_width="fill_parent" android:layout_marginTop="1dip"
android:id="#+id/OLF_ScrollView" android:layout_height="fill_parent" android:background="#drawable/small_list_back">
<TableLayout android:layout_width="fill_parent" android:id="#+id/OLF_tableLayout_TableLayout" android:layout_height="fill_parent">
</TableLayout>
</com.abc.LDObservableScrollView>
Step-4 In your activity class or where you want to detect the scroll event use the follwoing code
public class DetectHere implements LDObservableScrollViewListener{
...
LDObservableScrollView scrollView = (LDObservableScrollView)view.findViewById(R.id.OLF_ScrollView);
scrollView.setScrollViewListener(this);
.....
#Override
public void onScrollChanged(LDObservableScrollView scrollView, int x,
int y, int oldx, int oldy) {
// TODO Auto-generated method stub
if((scrollView.getHeight()+y) >= tableLayout.getHeight()){
Log.e("Custom Listener ", "END OF LIST OCCURRED ::");
}
}
This also worked for me, but my y value on the onScrollChanged never gets higher than the height on my samsung galaxy tab 2 7".
But it works on the galaxy tab 2 10.1"
Any ideas why?
[Edit]
I've seen now that this occurs when the screen is less than a certain height, 1000px for instance. Because when I made the content of my scroll less than 1200 on the 10.1" Galaxy tab 2, it stopped working for the maximum height detection.
[Edit]
I've found the solution, it wasn't detecting the size of the scroll correctly, in order to do that, what I've done was the following:
protected void onScrollChanged(int horizontalScrollPosition, int verticalScrollPosition, int previousHorizontalScrollPosition, int previousVerticalScrollPosition) {
int scrollTotalHeight = this.getChildAt(0).getHeight() - super.getHeight();
if(_previousImage != null)
if(verticalScrollPosition <= 0) _previousImage.setVisibility(View.GONE);
if(_nextImage != null)
if(verticalScrollPosition >= scrollTotalHeight) _nextImage.setVisibility(View.GONE);
super.onScrollChanged(horizontalScrollPosition, verticalScrollPosition, previousHorizontalScrollPosition, previousVerticalScrollPosition);
}