EditText setCompoundDrawablesWithIntrinsicBounds() not working after setError() - android

I have an custom widget which has an clear button set as the right drawable using setCompoundDrawablesWithIntrinsicBounds() method.
Now I need to add errors to the widget and I've tried to use the default functionality and rely on the setError() method.
The issue I'm having is that after I set the error, my right drawable won't be shown again, even if I set it again afterwards.
Does anyone encountered this issue and maybe found an solution to the problem?
Thank you.
LE:
I forgot to mention that if I use setError("My error hint text", null) instead of setError("Please choose an valid destination!") everything works fine, but as you can guess the error icon won't be shown.
LLE:
This is my custom class which handles the display of the clear icon and the action for it.
/**
* Class of {#link android.widget.AutoCompleteTextView} that includes a clear (dismiss / close) button with a
* OnClearListener to handle the event of clicking the button
* <br/>
* Created by ionut on 26.04.2016.
*/
public class ClearableAutoCompleteTextView extends AppCompatAutoCompleteTextView implements View.OnTouchListener {
/**
* The time(in milliseconds) used for transitioning between the supported states.
*/
private static final int TRANSITION_TIME = 500;
/**
* Flag for hide transition.
*/
private static final int TRANSITION_HIDE = 101;
/**
* Flag for show transition.
*/
private static final int TRANSITION_SHOW = 102;
/**
* Image representing the clear button. (will always be set to the right of the view).
*/
#DrawableRes
private static int mImgClearButtonRes = R.drawable.ic_clear_dark;
/**
* Task with the role of showing the clear action button.
*/
private final Runnable showClearButtonRunnable = new Runnable() {
#Override
public void run() {
Message msg = transitionHandler.obtainMessage(TRANSITION_SHOW);
msg.sendToTarget();
}
};
/**
* Task with the role of hiding the clear action button.
*/
private final Runnable hideClearButtonRunnable = new Runnable() {
#Override
public void run() {
Message msg = transitionHandler.obtainMessage(TRANSITION_HIDE);
msg.sendToTarget();
}
};
/**
* Flag indicating if the default clear functionality should be disabled.
*/
private boolean mDisableDefaultFunc;
// The default clear listener which will clear the input of any text
private OnClearListener mDefaultClearListener = new OnClearListener() {
#Override
public void onClear() {
getEditableText().clear();
setText(null);
}
};
/**
* Touch listener which will receive any touch events that this view handles.
*/
private OnTouchListener mOnTouchListener;
/**
* Custom listener which will be notified when an clear event was made from the clear button.
*/
private OnClearListener onClearListener;
/**
* Transition drawable used when showing the clear action.
*/
private TransitionDrawable mTransitionClearButtonShow = null;
/**
* Transition drawable used when hiding the clear action.
*/
private TransitionDrawable mTransitionClearButtonHide = null;
private AtomicBoolean isTransitionInProgress = new AtomicBoolean(false);
private final Handler transitionHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case TRANSITION_HIDE:
setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
isTransitionInProgress.set(false);
break;
case TRANSITION_SHOW:
setCompoundDrawablesWithIntrinsicBounds(0, 0, mImgClearButtonRes, 0);
isTransitionInProgress.set(false);
break;
default:
super.handleMessage(msg);
}
}
};
/* Required methods, not used in this implementation */
public ClearableAutoCompleteTextView(Context context) {
super(context);
init();
}
/* Required methods, not used in this implementation */
public ClearableAutoCompleteTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
/* Required methods, not used in this implementation */
public ClearableAutoCompleteTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (getCompoundDrawables()[2] == null) {
// Pass the touch event to other listeners, if none, the normal flow is resumed
return null != mOnTouchListener && mOnTouchListener.onTouch(v, event);
}
// React only when the UP event is detected
if (event.getAction() != MotionEvent.ACTION_UP) {
return false;
}
// Detect the clear button area of touch
int x = (int) event.getX();
int y = (int) event.getY();
int left = getWidth() - getPaddingRight() - getCompoundDrawables()[2].getIntrinsicWidth();
int right = getWidth();
boolean tappedX = x >= left && x <= right && y >= 0 && y <= (getBottom() - getTop());
if (tappedX) {
// Allow clear events only when the transition is not in progress
if (!isTransitionInProgress.get()) {
if (!mDisableDefaultFunc) {
// Call the default functionality only if it wasn't disabled
mDefaultClearListener.onClear();
}
if (null != onClearListener) {
// Call the custom clear listener so that any member listening is notified of the clear event
onClearListener.onClear();
}
}
}
// Pass the touch event to other listeners, if none, the normal flow is resumed
return null != mOnTouchListener && mOnTouchListener.onTouch(v, event);
}
#Override
public void setOnTouchListener(OnTouchListener l) {
// Instead of using the super, we manually handle the touch event (only one listener can exist normally at a
// time)
mOnTouchListener = l;
}
private void init() {
// Set the bounds of the button
setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
if (getCompoundDrawablePadding() == 0) {
// We want to have some default padding, in case no one is specified in the xml
setCompoundDrawablePadding(Dimensions.dpToPx(getContext(), 5f));
}
enableTransitionClearButton();
// if the clear button is pressed, fire up the handler. Otherwise do nothing
super.setOnTouchListener(this);
}
#Override
public void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(state);
updateClearButton();
}
#Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
updateClearButton();
}
/**
* When hiding/showing the clear button an transition drawable will be used instead of the default drawable res.
*/
public void enableTransitionClearButton() {
mTransitionClearButtonShow =
(TransitionDrawable) ContextCompat.getDrawable(getContext(), R.drawable.ic_clear_fade_in);
mTransitionClearButtonHide =
(TransitionDrawable) ContextCompat.getDrawable(getContext(), R.drawable.ic_clear_fade_out);
mTransitionClearButtonShow.setCrossFadeEnabled(true);
mTransitionClearButtonHide.setCrossFadeEnabled(true);
}
/**
* When hiding/showing the clear button the default drawable res will be used instead of the transition drawable.
*/
#SuppressWarnings("unused")
public void disableTransitionClearButton() {
mTransitionClearButtonShow = null;
isTransitionInProgress.set(false);
transitionHandler.removeCallbacks(hideClearButtonRunnable);
transitionHandler.removeCallbacks(showClearButtonRunnable);
}
/**
* Set an custom listener which will get notified when an clear event was triggered from the clear button.
*
* #param clearListener
* The listener
* #param disableDefaultFunc
* {#code true} to disable the default clear functionality, usually meaning it will be
* handled by the
* calling member. {#code false} allow the default functionality of clearing the input.
*
* #see #setOnClearListener(OnClearListener)
*/
public void setOnClearListener(final OnClearListener clearListener, boolean disableDefaultFunc) {
this.onClearListener = clearListener;
this.mDisableDefaultFunc = disableDefaultFunc;
}
/**
* Set an custom listener which will get notified when an clear event was triggered from the clear button.
*
* #param clearListener
* The listener
*
* #see #setOnClearListener(OnClearListener, boolean)
*/
public void setOnClearListener(final OnClearListener clearListener) {
setOnClearListener(clearListener, false);
}
/**
* Disable the default functionality of the clear event - calling this won't allow for the input to be
* automatically
* cleared (it will give the ability to make custom implementations and react to the event before the clear).
*/
#SuppressWarnings("unused")
public void disableDefaultClearFunctionality() {
mDisableDefaultFunc = true;
}
/**
* Enable the default functionality of the clear event. Will automatically clear the input when the clear button is
* clicked.
*/
#SuppressWarnings("unused")
public void enableDefaultClearFunctionality() {
mDisableDefaultFunc = false;
}
/**
* Automatically show/hide the clear button based on the current input detected.
* <br/>
* If there is no input the clear button will be hidden. If there is input detected the clear button will be shown.
*/
public void updateClearButton() {
if (isEmpty()) {
hideClearButton();
} else {
showClearButton();
}
}
private boolean isEmpty() {
if (null == getText()) {
// Invalid editable text
return true;
} else if (TextUtils.isEmpty(getText().toString())) {
// Empty
return true;
} else if (TextUtils.isEmpty(getText().toString().trim())) {
// White spaces only
return true;
}
return false;
}
/**
* Hide the clear button.
* <br/>
* If an transition drawable was provided, it will be used to create an fade out effect, otherwise the default
* drawable resource will be used.
*/
public void hideClearButton() {
if (getCompoundDrawables()[2] == null) {
// The clear button was already hidden - do nothing
return;
}
if (null == mTransitionClearButtonHide) {
setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
return;
}
mTransitionClearButtonHide.resetTransition();
isTransitionInProgress.set(true);
mTransitionClearButtonHide.startTransition(TRANSITION_TIME);
setCompoundDrawablesWithIntrinsicBounds(null, null, mTransitionClearButtonHide, null);
transitionHandler.removeCallbacks(showClearButtonRunnable);
transitionHandler.removeCallbacks(hideClearButtonRunnable);
transitionHandler.postDelayed(hideClearButtonRunnable, TRANSITION_TIME);
}
/**
* Show the clear button.
* <br/>
* If an transition drawable was provided, it will be used to create an fade in effect, otherwise the default
* drawable resource will be used.
*/
public void showClearButton() {
if (getCompoundDrawables()[2] != null) {
// The clear button was already set - do nothing
return;
}
if (null == mTransitionClearButtonShow) {
setCompoundDrawablesWithIntrinsicBounds(0, 0, mImgClearButtonRes, 0);
return;
}
isTransitionInProgress.set(true);
mTransitionClearButtonShow.startTransition(TRANSITION_TIME);
setCompoundDrawablesWithIntrinsicBounds(null, null, mTransitionClearButtonShow, null);
transitionHandler.removeCallbacks(hideClearButtonRunnable);
transitionHandler.removeCallbacks(showClearButtonRunnable);
transitionHandler.postDelayed(showClearButtonRunnable, TRANSITION_TIME);
}
/**
* Custom contract which is used to notify any listeners that an clear event was triggered.
*/
public interface OnClearListener {
/**
* Clear event from the clear button triggered.
*/
void onClear();
}
}
When I want to display the error I use the following command:
// Enable and show the error
mClearView.requestFocus(); // we need to request focus, otherwise the error won't be shown
mClearView.setError("Please choose an valid destination!", null);
If I use:
mClearView.setError("Please choose an valid destination!"), so that the error icon to be shown, the clear button won't be shown anymore after this.

Since the documentation of setCompoundDrawablesWithIntrinsicBounds() (not so) clearly states that subsequent calls should overwrite the previously set drawables, and the documentation of setError() says the following:
Sets the right-hand compound drawable of the TextView to the "error" icon and sets an error message that will be displayed in a
popup when the TextView has focus.
I assume this is a bug.
Calling setError(null) and setting the previously set drawables to null before setting your new drawable is a possible workaround:
void setError(String error) {
editText.setError(error);
}
void setCompoundDrawableRight(Drawable rightDrawable) {
editText.setError(null);
editText.setCompoundDrawables(null, null, null, null);
editText.setCompoundDrawablesWithIntrinsicBounds(null, null, rightDrawable, null);
}

Related

How to achieve Buttery Smooth ViewPager Shake animation

I am investigating Android ViewPager animation in my current project.
I would like to give my users an affordance in relation to my ViewPager.
The effect I am looking for it to "shake" the ViewPager from left to right to partially show the neighbouring pages to the selected page.
When the user selects the first page (F), I would "Shake" between F and F + 1.
When the user selects the last page (L), I would "Shake" between L and L - 1.
Otherwise, when the user selects any other page (X), I would "Shake" between X - 1, X and X + 1.
I have tried the following approaches which have all given unsatisfactory results.
Fake drag using screen density to calculate shake distance and valueAnimator and ObjectAnimator.
Animating ViewPager.PageTransformer.
I am unable to get a satisfactory "Shake" effect.
I would like to achieve a Spring Dampening style of animation.
The FakeDrag was closest, although the effect was not reliable, it seemed to never work correctly the first time I started the animation.
Even the FakeDrag would not give the desired smooth shake between page swipes.
I would like to employ the physics-based animations on my view pager but couldn't see how.
Is it possible to achieve my desired animation?
UPDATE
I have developed this code which gives the desired effect, however its JANKY!
#Override
protected void onResume() {
super.onResume();
final Handler handler = new Handler();
handler.postDelayed(() -> animateViewPager(ANIMATION_OFFSET, ANIMATION_DURATION), ANIMATION_DELAY);
}
/**
* #param offset
* #param duration
*/
private void animateViewPager(final int offset, final int duration) {
if (animator.isRunning()) {
return;
}
animator.removeAllUpdateListeners();
animator.removeAllListeners();
animator.setIntValues(0, -offset);
animator.setDuration(duration);
animator.setRepeatCount(getRepeatCount());
animator.setRepeatMode(ValueAnimator.RESTART);
animator.addUpdateListener(constructUpdateListener());
animator.addListener(constructAnimatorListener());
animator.start();
}
/**
*
* #return
*/
private Animator.AnimatorListener constructAnimatorListener() {
return new AnimatorListenerAdapter() {
#Override
public void onAnimationStart(final Animator animation) {
animFactor = 1;
}
#Override
public void onAnimationEnd(final Animator animation) {
viewPager.endFakeDrag();
if (xAnimation == null) {
xAnimation = createSpringAnimation(viewPager, SpringAnimation.X, 0, SpringForce.STIFFNESS_LOW, SpringForce.DAMPING_RATIO_HIGH_BOUNCY);
} else {
xAnimation.cancel();
}
viewPager.animate().x(viewPager.getWidth() * 0.1f).setDuration(0).start();
xAnimation.start();
}
#Override
public void onAnimationRepeat(final Animator animation) {
animFactor = -1;
}
};
}
/**
* #return
*/
private int getRepeatCount() {
if (isOnlyPage()) {
return 0;
}
if (isFirstListItem()) {
return REPEAT_ONCE;
}
if (isLastListItem()) {
return REPEAT_ONCE;
}
return REPEAT_TWICE;
}
#SuppressWarnings("StatementWithEmptyBody")
private ValueAnimator.AnimatorUpdateListener constructUpdateListener() {
return animation -> {
final Integer value = animFactor * (Integer) animation.getAnimatedValue();
if (viewPager.isFakeDragging()) {
} else {
viewPager.beginFakeDrag();
}
viewPager.fakeDragBy(value);
};
}
/**
* #param view
* #param property
* #param finalPosition
* #param stiffness
* #param dampingRatio
* #return
*/
private SpringAnimation createSpringAnimation(final View view, final DynamicAnimation.ViewProperty property, final float finalPosition, final float stiffness, final float dampingRatio) {
final SpringAnimation animation = new SpringAnimation(view, property);
final SpringForce springForce = new SpringForce(finalPosition);
springForce.setStiffness(stiffness);
springForce.setDampingRatio(dampingRatio);
animation.setSpring(springForce);
return animation;
}

Toolbar colors under API 21 [duplicate]

I have the following code. I can only see the action bar color change. But, the status bar does not change.
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- App branding color for the app bar -->
<item name="colorPrimary">#009688</item>
<!-- Darker variant for the status bar and contextual app bars -->
<item name="colorPrimaryDark">#00796B</item>
<!-- Theme UI controls like checkboxes and text fields -->
<item name="colorAccent">#536DFE</item>
</style>
In API level 19, changing the status bar color is not natively supported. But the good thing is that Kitkat brought Translucent UI styling for both the status bar and navigation bar.
There is a very nice library which lets you tint the system bars with either colors or drawables you want.
How to use
Step 1
Add this to your build.grade in Android Studio.
dependencies {
compile 'com.readystatesoftware.systembartint:systembartint:1.0.3'
}
Step 2
Please set android:windowTranslucentNavigation or android:windowTranslucentStatus theme attributes to trueor set the FLAG_TRANSLUCENT_NAVIGATION or FLAG_TRANSLUCENT_STATUS flags to your Activity window in code.
Step 3
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setNavigationBarTintEnabled(true);
}
There are lots of customizations that you can do with this library. Just go through the library page I gave a link to or check the sample app.
Add this Code in you onCreate
SystemBarTintManager tintManager;
setTranslucentStatus(true);
tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.YOUR_COLOR);
And create a method somewhere in same class.
private void setTranslucentStatus(boolean on) {
// TODO Auto-generated method stub
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
SystemBarTintManager class
import java.lang.reflect.Method;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout.LayoutParams;
/**
* Class to manage status and navigation bar tint effects when using KitKat
* translucent system UI modes.
*
*/
public class SystemBarTintManager {
static {
// Android allows a system property to override the presence of the navigation bar.
// Used by the emulator.
// See https://github.com/android/platform_frameworks_base/blob/master/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java#L1076
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
try {
Class c = Class.forName("android.os.SystemProperties");
Method m = c.getDeclaredMethod("get", String.class);
m.setAccessible(true);
sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
} catch (Throwable e) {
sNavBarOverride = null;
}
}
}
/**
* The default system bar tint color value.
*/
public static final int DEFAULT_TINT_COLOR = 0x99000000;
private static String sNavBarOverride;
private final SystemBarConfig mConfig;
private boolean mStatusBarAvailable;
private boolean mNavBarAvailable;
private boolean mStatusBarTintEnabled;
private boolean mNavBarTintEnabled;
private View mStatusBarTintView;
private View mNavBarTintView;
/**
* Constructor. Call this in the host activity onCreate method after its
* content view has been set. You should always create new instances when
* the host activity is recreated.
*
* #param activity The host activity.
*/
#TargetApi(19)
public SystemBarTintManager(Activity activity) {
Window win = activity.getWindow();
ViewGroup decorViewGroup = (ViewGroup) win.getDecorView();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// check theme attrs
int[] attrs = {android.R.attr.windowTranslucentStatus,
android.R.attr.windowTranslucentNavigation};
TypedArray a = activity.obtainStyledAttributes(attrs);
try {
mStatusBarAvailable = a.getBoolean(0, false);
mNavBarAvailable = a.getBoolean(1, false);
} finally {
a.recycle();
}
// check window flags
WindowManager.LayoutParams winParams = win.getAttributes();
int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if ((winParams.flags & bits) != 0) {
mStatusBarAvailable = true;
}
bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
if ((winParams.flags & bits) != 0) {
mNavBarAvailable = true;
}
}
mConfig = new SystemBarConfig(activity, mStatusBarAvailable, mNavBarAvailable);
// device might not have virtual navigation keys
if (!mConfig.hasNavigtionBar()) {
mNavBarAvailable = false;
}
if (mStatusBarAvailable) {
setupStatusBarView(activity, decorViewGroup);
}
if (mNavBarAvailable) {
setupNavBarView(activity, decorViewGroup);
}
}
/**
* Enable tinting of the system status bar.
*
* If the platform is running Jelly Bean or earlier, or translucent system
* UI modes have not been enabled in either the theme or via window flags,
* then this method does nothing.
*
* #param enabled True to enable tinting, false to disable it (default).
*/
public void setStatusBarTintEnabled(boolean enabled) {
mStatusBarTintEnabled = enabled;
if (mStatusBarAvailable) {
mStatusBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
}
}
/**
* Enable tinting of the system navigation bar.
*
* If the platform does not have soft navigation keys, is running Jelly Bean
* or earlier, or translucent system UI modes have not been enabled in either
* the theme or via window flags, then this method does nothing.
*
* #param enabled True to enable tinting, false to disable it (default).
*/
public void setNavigationBarTintEnabled(boolean enabled) {
mNavBarTintEnabled = enabled;
if (mNavBarAvailable) {
mNavBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
}
}
/**
* Apply the specified color tint to all system UI bars.
*
* #param color The color of the background tint.
*/
public void setTintColor(int color) {
setStatusBarTintColor(color);
setNavigationBarTintColor(color);
}
/**
* Apply the specified drawable or color resource to all system UI bars.
*
* #param res The identifier of the resource.
*/
public void setTintResource(int res) {
setStatusBarTintResource(res);
setNavigationBarTintResource(res);
}
/**
* Apply the specified drawable to all system UI bars.
*
* #param drawable The drawable to use as the background, or null to remove it.
*/
public void setTintDrawable(Drawable drawable) {
setStatusBarTintDrawable(drawable);
setNavigationBarTintDrawable(drawable);
}
/**
* Apply the specified alpha to all system UI bars.
*
* #param alpha The alpha to use
*/
public void setTintAlpha(float alpha) {
setStatusBarAlpha(alpha);
setNavigationBarAlpha(alpha);
}
/**
* Apply the specified color tint to the system status bar.
*
* #param color The color of the background tint.
*/
public void setStatusBarTintColor(int color) {
if (mStatusBarAvailable) {
mStatusBarTintView.setBackgroundColor(color);
}
}
/**
* Apply the specified drawable or color resource to the system status bar.
*
* #param res The identifier of the resource.
*/
public void setStatusBarTintResource(int res) {
if (mStatusBarAvailable) {
mStatusBarTintView.setBackgroundResource(res);
}
}
/**
* Apply the specified drawable to the system status bar.
*
* #param drawable The drawable to use as the background, or null to remove it.
*/
#SuppressWarnings("deprecation")
public void setStatusBarTintDrawable(Drawable drawable) {
if (mStatusBarAvailable) {
mStatusBarTintView.setBackgroundDrawable(drawable);
}
}
/**
* Apply the specified alpha to the system status bar.
*
* #param alpha The alpha to use
*/
#TargetApi(11)
public void setStatusBarAlpha(float alpha) {
if (mStatusBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mStatusBarTintView.setAlpha(alpha);
}
}
/**
* Apply the specified color tint to the system navigation bar.
*
* #param color The color of the background tint.
*/
public void setNavigationBarTintColor(int color) {
if (mNavBarAvailable) {
mNavBarTintView.setBackgroundColor(color);
}
}
/**
* Apply the specified drawable or color resource to the system navigation bar.
*
* #param res The identifier of the resource.
*/
public void setNavigationBarTintResource(int res) {
if (mNavBarAvailable) {
mNavBarTintView.setBackgroundResource(res);
}
}
/**
* Apply the specified drawable to the system navigation bar.
*
* #param drawable The drawable to use as the background, or null to remove it.
*/
#SuppressWarnings("deprecation")
public void setNavigationBarTintDrawable(Drawable drawable) {
if (mNavBarAvailable) {
mNavBarTintView.setBackgroundDrawable(drawable);
}
}
/**
* Apply the specified alpha to the system navigation bar.
*
* #param alpha The alpha to use
*/
#TargetApi(11)
public void setNavigationBarAlpha(float alpha) {
if (mNavBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mNavBarTintView.setAlpha(alpha);
}
}
/**
* Get the system bar configuration.
*
* #return The system bar configuration for the current device configuration.
*/
public SystemBarConfig getConfig() {
return mConfig;
}
/**
* Is tinting enabled for the system status bar?
*
* #return True if enabled, False otherwise.
*/
public boolean isStatusBarTintEnabled() {
return mStatusBarTintEnabled;
}
/**
* Is tinting enabled for the system navigation bar?
*
* #return True if enabled, False otherwise.
*/
public boolean isNavBarTintEnabled() {
return mNavBarTintEnabled;
}
private void setupStatusBarView(Context context, ViewGroup decorViewGroup) {
mStatusBarTintView = new View(context);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getStatusBarHeight());
params.gravity = Gravity.TOP;
if (mNavBarAvailable && !mConfig.isNavigationAtBottom()) {
params.rightMargin = mConfig.getNavigationBarWidth();
}
mStatusBarTintView.setLayoutParams(params);
mStatusBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
mStatusBarTintView.setVisibility(View.GONE);
decorViewGroup.addView(mStatusBarTintView);
}
private void setupNavBarView(Context context, ViewGroup decorViewGroup) {
mNavBarTintView = new View(context);
LayoutParams params;
if (mConfig.isNavigationAtBottom()) {
params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getNavigationBarHeight());
params.gravity = Gravity.BOTTOM;
} else {
params = new LayoutParams(mConfig.getNavigationBarWidth(), LayoutParams.MATCH_PARENT);
params.gravity = Gravity.RIGHT;
}
mNavBarTintView.setLayoutParams(params);
mNavBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
mNavBarTintView.setVisibility(View.GONE);
decorViewGroup.addView(mNavBarTintView);
}
/**
* Class which describes system bar sizing and other characteristics for the current
* device configuration.
*
*/
public static class SystemBarConfig {
private static final String STATUS_BAR_HEIGHT_RES_NAME = "status_bar_height";
private static final String NAV_BAR_HEIGHT_RES_NAME = "navigation_bar_height";
private static final String NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME = "navigation_bar_height_landscape";
private static final String NAV_BAR_WIDTH_RES_NAME = "navigation_bar_width";
private static final String SHOW_NAV_BAR_RES_NAME = "config_showNavigationBar";
private final boolean mTranslucentStatusBar;
private final boolean mTranslucentNavBar;
private final int mStatusBarHeight;
private final int mActionBarHeight;
private final boolean mHasNavigationBar;
private final int mNavigationBarHeight;
private final int mNavigationBarWidth;
private final boolean mInPortrait;
private final float mSmallestWidthDp;
private SystemBarConfig(Activity activity, boolean translucentStatusBar, boolean traslucentNavBar) {
Resources res = activity.getResources();
mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
mSmallestWidthDp = getSmallestWidthDp(activity);
mStatusBarHeight = getInternalDimensionSize(res, STATUS_BAR_HEIGHT_RES_NAME);
mActionBarHeight = getActionBarHeight(activity);
mNavigationBarHeight = getNavigationBarHeight(activity);
mNavigationBarWidth = getNavigationBarWidth(activity);
mHasNavigationBar = (mNavigationBarHeight > 0);
mTranslucentStatusBar = translucentStatusBar;
mTranslucentNavBar = traslucentNavBar;
}
#TargetApi(14)
private int getActionBarHeight(Context context) {
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TypedValue tv = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
result = context.getResources().getDimensionPixelSize(tv.resourceId);
}
return result;
}
#TargetApi(14)
private int getNavigationBarHeight(Context context) {
Resources res = context.getResources();
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (hasNavBar(context)) {
String key;
if (mInPortrait) {
key = NAV_BAR_HEIGHT_RES_NAME;
} else {
key = NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME;
}
return getInternalDimensionSize(res, key);
}
}
return result;
}
#TargetApi(14)
private int getNavigationBarWidth(Context context) {
Resources res = context.getResources();
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (hasNavBar(context)) {
return getInternalDimensionSize(res, NAV_BAR_WIDTH_RES_NAME);
}
}
return result;
}
#TargetApi(14)
private boolean hasNavBar(Context context) {
Resources res = context.getResources();
int resourceId = res.getIdentifier(SHOW_NAV_BAR_RES_NAME, "bool", "android");
if (resourceId != 0) {
boolean hasNav = res.getBoolean(resourceId);
// check override flag (see static block)
if ("1".equals(sNavBarOverride)) {
hasNav = false;
} else if ("0".equals(sNavBarOverride)) {
hasNav = true;
}
return hasNav;
} else { // fallback
return !ViewConfiguration.get(context).hasPermanentMenuKey();
}
}
private int getInternalDimensionSize(Resources res, String key) {
int result = 0;
int resourceId = res.getIdentifier(key, "dimen", "android");
if (resourceId > 0) {
result = res.getDimensionPixelSize(resourceId);
}
return result;
}
#SuppressLint("NewApi")
private float getSmallestWidthDp(Activity activity) {
DisplayMetrics metrics = new DisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
} else {
// TODO this is not correct, but we don't really care pre-kitkat
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
}
float widthDp = metrics.widthPixels / metrics.density;
float heightDp = metrics.heightPixels / metrics.density;
return Math.min(widthDp, heightDp);
}
/**
* Should a navigation bar appear at the bottom of the screen in the current
* device configuration? A navigation bar may appear on the right side of
* the screen in certain configurations.
*
* #return True if navigation should appear at the bottom of the screen, False otherwise.
*/
public boolean isNavigationAtBottom() {
return (mSmallestWidthDp >= 600 || mInPortrait);
}
/**
* Get the height of the system status bar.
*
* #return The height of the status bar (in pixels).
*/
public int getStatusBarHeight() {
return mStatusBarHeight;
}
/**
* Get the height of the action bar.
*
* #return The height of the action bar (in pixels).
*/
public int getActionBarHeight() {
return mActionBarHeight;
}
/**
* Does this device have a system navigation bar?
*
* #return True if this device uses soft key navigation, False otherwise.
*/
public boolean hasNavigtionBar() {
return mHasNavigationBar;
}
/**
* Get the height of the system navigation bar.
*
* #return The height of the navigation bar (in pixels). If the device does not have
* soft navigation keys, this will always return 0.
*/
public int getNavigationBarHeight() {
return mNavigationBarHeight;
}
/**
* Get the width of the system navigation bar when it is placed vertically on the screen.
*
* #return The width of the navigation bar (in pixels). If the device does not have
* soft navigation keys, this will always return 0.
*/
public int getNavigationBarWidth() {
return mNavigationBarWidth;
}
/**
* Get the layout inset for any system UI that appears at the top of the screen.
*
* #param withActionBar True to include the height of the action bar, False otherwise.
* #return The layout inset (in pixels).
*/
public int getPixelInsetTop(boolean withActionBar) {
return (mTranslucentStatusBar ? mStatusBarHeight : 0) + (withActionBar ? mActionBarHeight : 0);
}
/**
* Get the layout inset for any system UI that appears at the bottom of the screen.
*
* #return The layout inset (in pixels).
*/
public int getPixelInsetBottom() {
if (mTranslucentNavBar && isNavigationAtBottom()) {
return mNavigationBarHeight;
} else {
return 0;
}
}
/**
* Get the layout inset for any system UI that appears at the right of the screen.
*
* #return The layout inset (in pixels).
*/
public int getPixelInsetRight() {
if (mTranslucentNavBar && !isNavigationAtBottom()) {
return mNavigationBarWidth;
} else {
return 0;
}
}
}
}

How to override default text selection of android webview os 4.1+?

Before posting this question I've searched a lot but could not find any clear answers on this issue.
I have to override default text selection of android webview & show my custom text selection dialog options. I have tried this sample code project.
This sample project works on following devices & emulator :
Acer Iconia a500 tablet : 10 inch : Android OS - 3.0
Acer Iconia a500 tablet : 10 inch : Android OS - 3.2
Samsung Galaxy Tab : 10 inch : Android OS - 4.0
Samsung Galaxy Tab : 7 inch : Android OS - 4.0
Emulator : Skin-WVGA800 : Android OS - 4.1.2
Not working on following devices :
Samsung Galaxy Tab : 10 inch : Android OS - 4.1.2
Samsung Galaxy Tab : 7 inch : Android OS - 4.1.2
On android os version 4.1 & 4.1+ instead of showing my custom text selection option dialog, it shows android system's default action bar for text selection.
I have searched a lot on this, many suggested to use onLongClick() method of the interface
I have already asked a question on this forum please see this link, with answers to this questions I am able to clone onLongClick() event but I can't stop default text selection action bar.
For this scenario I have few questions.
1.Why onLongClick() method stops working for device running on android os version 4.1+ ?
2.How to stop default text selection action bar on long pressing on the text from webview ?
This is my custom webview class.
package com.epubreader.ebook;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.Region;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Display;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.epubreader.R;
import com.epubreader.drag.DragController;
import com.epubreader.drag.DragLayer;
import com.epubreader.drag.DragListener;
import com.epubreader.drag.DragSource;
import com.epubreader.drag.MyAbsoluteLayout;
import com.epubreader.menu.menuAnimationHelper;
import com.epubreader.textselection.WebTextSelectionJSInterface;
import com.epubreader.textselectionoverlay.ActionItem;
import com.epubreader.textselectionoverlay.QuickAction;
import com.epubreader.textselectionoverlay.QuickAction.OnDismissListener;
public class CustomWebView extends WebView implements WebTextSelectionJSInterface,
OnTouchListener , OnLongClickListener, OnDismissListener, DragListener{
/** The logging tag. */
private static final String TAG = "CustomWebView";
/** Context. */
protected Context ctx;
/** The context menu. */
private QuickAction mContextMenu;
/** The drag layer for selection. */
private DragLayer mSelectionDragLayer;
/** The drag controller for selection. */
private DragController mDragController;
/** The start selection handle. */
private ImageView mStartSelectionHandle;
/** the end selection handle. */
private ImageView mEndSelectionHandle;
/** The selection bounds. */
private Rect mSelectionBounds = null;
/** The previously selected region. */
protected Region lastSelectedRegion = null;
/** The selected range. */
protected String selectedRange = "";
/** The selected text. */
protected String selectedText = "";
/** Javascript interface for catching text selection. */
/** Selection mode flag. */
protected boolean inSelectionMode = false;
/** Flag to stop from showing context menu twice. */
protected boolean contextMenuVisible = false;
/** The current content width. */
protected int contentWidth = 0;
/** Identifier for the selection start handle. */
private final int SELECTION_START_HANDLE = 0;
/** Identifier for the selection end handle. */
private final int SELECTION_END_HANDLE = 1;
/** Last touched selection handle. */
private int mLastTouchedSelectionHandle = -1;
/** Variables for Left & Right Menu ***/
private View menuView;
private LinearLayout toiLay;
private menuAnimationHelper _menuAnimationHelper;
private TocTranslateAnimation _tocTranslateAnimation;
private CustomWebView _customWebView;
public CustomWebView(Context context) {
super(context);
this.ctx = context;
this.setup(context);
}
public CustomWebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.ctx = context;
this.setup(context);
}
public CustomWebView(Context context, AttributeSet attrs) {
super(context, attrs);
this.ctx = context;
this.setup(context);
}
//*****************************************************
//*
//* Touch Listeners
//*
//*****************************************************
private boolean mScrolling = false;
private float mScrollDiffY = 0;
private float mLastTouchY = 0;
private float mScrollDiffX = 0;
private float mLastTouchX = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
float xPoint = getDensityIndependentValue(event.getX(), ctx) / getDensityIndependentValue(this.getScale(), ctx);
float yPoint = getDensityIndependentValue(event.getY(), ctx) / getDensityIndependentValue(this.getScale(), ctx);
// TODO: Need to update this to use this.getScale() as a factor.
//Log.d(TAG, "onTouch " + xPoint + " , " + yPoint);
closeMenu();
if(event.getAction() == MotionEvent.ACTION_DOWN){
final String startTouchUrl = String.format("javascript:android.selection.startTouch(%f, %f);",
xPoint, yPoint);
mLastTouchX = xPoint;
mLastTouchY = yPoint;
((Activity)this.ctx).runOnUiThread(new Runnable() {
#Override
public void run() {
loadUrl(startTouchUrl);
}
});
// This two line clones the onLongClick()
longClickHandler.removeCallbacks(longClickRunnable);
longClickHandler.postDelayed(longClickRunnable,300);
}
else if(event.getAction() == MotionEvent.ACTION_UP){
// Check for scrolling flag
if(!mScrolling){
this.endSelectionMode();
}
// This line clones the onLongClick()
longClickHandler.removeCallbacks(longClickRunnable);
mScrollDiffX = 0;
mScrollDiffY = 0;
mScrolling = false;
}else if(event.getAction() == MotionEvent.ACTION_MOVE){
mScrollDiffX += (xPoint - mLastTouchX);
mScrollDiffY += (yPoint - mLastTouchY);
mLastTouchX = xPoint;
mLastTouchY = yPoint;
// Only account for legitimate movement.
if(Math.abs(mScrollDiffX) > 10 || Math.abs(mScrollDiffY) > 10){
mScrolling = true;
}
// This line clones the onLongClick()
longClickHandler.removeCallbacks(longClickRunnable);
}
// If this is in selection mode, then nothing else should handle this touch
return false;
}
/**
* Pass References of Left & Right Menu
*/
public void initMenu(LinearLayout _toiLay,View _menuView,menuAnimationHelper menuAnimationHelper,
TocTranslateAnimation tocTranslateAnimation){
toiLay = _toiLay;
menuView = _menuView;
_menuAnimationHelper = menuAnimationHelper;
_tocTranslateAnimation = tocTranslateAnimation;
}
private void closeMenu(){
if(_menuAnimationHelper != null && _menuAnimationHelper.isMenuOpenBool){
_menuAnimationHelper.close(menuView);
_menuAnimationHelper.isMenuOpenBool = false;
}
if(_tocTranslateAnimation != null && _tocTranslateAnimation.isTocListOpenBool){
_tocTranslateAnimation.close(toiLay);
_tocTranslateAnimation.isTocListOpenBool = false;
}
}
public void removeOverlay(){
Log.d("JsHandler", "in java removeOverlay" + mScrolling);
this.endSelectionMode();
mScrollDiffX = 0;
mScrollDiffY = 0;
mScrolling = false;
}
#Override
public boolean onLongClick(View v){
Log.d(TAG, "from webView onLongClick ");
mScrolling = true;
((Activity)this.ctx).runOnUiThread(new Runnable() {
#Override
public void run() {
loadUrl("javascript:android.selection.longTouch()");
}
});
Toast.makeText(ctx, "Long click is clicked ", Toast.LENGTH_LONG).show();
// Don't let the webview handle it
return true;
}
//*****************************************************
//*
//* Setup
//*
//*****************************************************
ContextMenu.ContextMenuInfo contextMenuInfo;
/**
* Setups up the web view.
* #param context
*/
protected void setup(Context context){
// On Touch Listener
this.setOnTouchListener(this);
this.setClickable(false);
this.setLongClickable(true);
this.setOnLongClickListener(this);
contextMenuInfo = this.getContextMenuInfo();
// Webview setup
this.getSettings().setJavaScriptEnabled(true);
this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
// Create the selection handles
createSelectionLayer(context);
// Set to the empty region
Region region = new Region();
region.setEmpty();
_customWebView = this;
this.lastSelectedRegion = region;
}
/**
* To clone OnLongClick Listener because its not responding for version 4.1
*/
public Runnable longClickRunnable = new Runnable() {
public void run() {
longClickHandler.sendEmptyMessage(0);
}
};
public Handler longClickHandler = new Handler(){
public void handleMessage(Message m){
_customWebView.loadUrl("javascript:android.selection.longTouch();");
mScrolling = true;
}
};
public WebTextSelectionJSInterface getTextSelectionJsInterface(){
return this;
}
//*****************************************************
//*
//* Selection Layer Handling
//*
//*****************************************************
/**
* Creates the selection layer.
*
* #param context
*/
protected void createSelectionLayer(Context context){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mSelectionDragLayer = (DragLayer) inflater.inflate(R.layout.selection_drag_layer, null);
// Make sure it's filling parent
this.mDragController = new DragController(context);
this.mDragController.setDragListener(this);
this.mDragController.addDropTarget(mSelectionDragLayer);
this.mSelectionDragLayer.setDragController(mDragController);
this.mStartSelectionHandle = (ImageView) this.mSelectionDragLayer.findViewById(R.id.startHandle);
this.mStartSelectionHandle.setTag(new Integer(SELECTION_START_HANDLE));
this.mEndSelectionHandle = (ImageView) this.mSelectionDragLayer.findViewById(R.id.endHandle);
this.mEndSelectionHandle.setTag(new Integer(SELECTION_END_HANDLE));
OnTouchListener handleTouchListener = new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
boolean handledHere = false;
final int action = event.getAction();
// Down event starts drag for handle.
if (action == MotionEvent.ACTION_DOWN) {
handledHere = startDrag (v);
mLastTouchedSelectionHandle = (Integer) v.getTag();
}
return handledHere;
}
};
this.mStartSelectionHandle.setOnTouchListener(handleTouchListener);
this.mEndSelectionHandle.setOnTouchListener(handleTouchListener);
}
/**
* Starts selection mode on the UI thread
*/
private Handler startSelectionModeHandler = new Handler(){
public void handleMessage(Message m){
if(mSelectionBounds == null)
return;
addView(mSelectionDragLayer);
drawSelectionHandles();
int contentHeight = (int) Math.ceil(getDensityDependentValue(getContentHeight(), ctx));
// Update Layout Params
ViewGroup.LayoutParams layerParams = mSelectionDragLayer.getLayoutParams();
layerParams.height = contentHeight;
layerParams.width = contentWidth;
mSelectionDragLayer.setLayoutParams(layerParams);
}
};
/**
* Starts selection mode.
*
* #param selectionBounds
*/
public void startSelectionMode(){
this.startSelectionModeHandler.sendEmptyMessage(0);
}
// Ends selection mode on the UI thread
private Handler endSelectionModeHandler = new Handler(){
public void handleMessage(Message m){
//Log.d("TableContentsWithDisplay", "in endSelectionModeHandler");
removeView(mSelectionDragLayer);
if(getParent() != null && mContextMenu != null && contextMenuVisible){
// This will throw an error if the webview is being redrawn.
// No error handling needed, just need to stop the crash.
try{
mContextMenu.dismiss();
}
catch(Exception e){
}
}
mSelectionBounds = null;
mLastTouchedSelectionHandle = -1;
try {
((Activity)ctx).runOnUiThread(new Runnable() {
#Override
public void run() {
loadUrl("javascript: android.selection.clearSelection();");
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
};
/**
* Ends selection mode.
*/
public void endSelectionMode(){
this.endSelectionModeHandler.sendEmptyMessage(0);
}
/**
* Calls the handler for drawing the selection handles.
*/
private void drawSelectionHandles(){
this.drawSelectionHandlesHandler.sendEmptyMessage(0);
}
/**
* Handler for drawing the selection handles on the UI thread.
*/
private Handler drawSelectionHandlesHandler = new Handler(){
public void handleMessage(Message m){
MyAbsoluteLayout.LayoutParams startParams = (com.epubreader.drag.MyAbsoluteLayout.LayoutParams) mStartSelectionHandle.getLayoutParams();
startParams.x = (int) (mSelectionBounds.left - mStartSelectionHandle.getDrawable().getIntrinsicWidth());
startParams.y = (int) (mSelectionBounds.top - mStartSelectionHandle.getDrawable().getIntrinsicHeight());
// Stay on screen.
startParams.x = (startParams.x < 0) ? 0 : startParams.x;
startParams.y = (startParams.y < 0) ? 0 : startParams.y;
mStartSelectionHandle.setLayoutParams(startParams);
MyAbsoluteLayout.LayoutParams endParams = (com.epubreader.drag.MyAbsoluteLayout.LayoutParams) mEndSelectionHandle.getLayoutParams();
endParams.x = (int) mSelectionBounds.right;
endParams.y = (int) mSelectionBounds.bottom;
endParams.x = (endParams.x < 0) ? 0 : endParams.x;
endParams.y = (endParams.y < 0) ? 0 : endParams.y;
mEndSelectionHandle.setLayoutParams(endParams);
}
};
/**
* Checks to see if this view is in selection mode.
* #return
*/
public boolean isInSelectionMode(){
return this.mSelectionDragLayer.getParent() != null;
}
//*****************************************************
//*
//* DragListener Methods
//*
//*****************************************************
/**
* Start dragging a view.
*
*/
private boolean startDrag (View v)
{
// Let the DragController initiate a drag-drop sequence.
// I use the dragInfo to pass along the object being dragged.
// I'm not sure how the Launcher designers do this.
Object dragInfo = v;
mDragController.startDrag (v, mSelectionDragLayer, dragInfo, DragController.DRAG_ACTION_MOVE);
return true;
}
#Override
public void onDragStart(DragSource source, Object info, int dragAction) {
// TODO Auto-generated method stub
}
#Override#SuppressWarnings("deprecation")
public void onDragEnd() {
// TODO Auto-generated method stub
MyAbsoluteLayout.LayoutParams startHandleParams = (MyAbsoluteLayout.LayoutParams) this.mStartSelectionHandle.getLayoutParams();
MyAbsoluteLayout.LayoutParams endHandleParams = (MyAbsoluteLayout.LayoutParams) this.mEndSelectionHandle.getLayoutParams();
float scale = getDensityIndependentValue(this.getScale(), ctx);
float startX = startHandleParams.x - this.getScrollX();
float startY = startHandleParams.y - this.getScrollY();
float endX = endHandleParams.x - this.getScrollX();
float endY = endHandleParams.y - this.getScrollY();
startX = getDensityIndependentValue(startX, ctx) / scale;
startY = getDensityIndependentValue(startY, ctx) / scale;
endX = getDensityIndependentValue(endX, ctx) / scale;
endY = getDensityIndependentValue(endY, ctx) / scale;
if(mLastTouchedSelectionHandle == SELECTION_START_HANDLE && startX > 0 && startY > 0){
final String saveStartString = String.format("javascript: android.selection.setStartPos(%f, %f);", startX, startY);
((Activity)ctx).runOnUiThread(new Runnable() {
#Override
public void run() {
loadUrl(saveStartString);
}
});
}
if(mLastTouchedSelectionHandle == SELECTION_END_HANDLE && endX > 0 && endY > 0){
final String saveEndString = String.format("javascript: android.selection.setEndPos(%f, %f);", endX, endY);
((Activity)ctx).runOnUiThread(new Runnable() {
#Override
public void run() {
loadUrl(saveEndString);
}
});
}
}
//*****************************************************
//*
//* Context Menu Creation
//*
//*****************************************************
/**
* Shows the context menu using the given region as an anchor point.
* #param region
*/
private void showContextMenu(Rect displayRect){
// Don't show this twice
if(this.contextMenuVisible){
return;
}
// Don't use empty rect
//if(displayRect.isEmpty()){
if(displayRect.right <= displayRect.left){
return;
}
//Copy action item
ActionItem buttonOne = new ActionItem();
buttonOne.setTitle("HighLight");
buttonOne.setActionId(1);
//buttonOne.setIcon(getResources().getDrawable(R.drawable.menu_search));
//Highlight action item
ActionItem buttonTwo = new ActionItem();
buttonTwo.setTitle("Note");
buttonTwo.setActionId(2);
//buttonTwo.setIcon(getResources().getDrawable(R.drawable.menu_info));
ActionItem buttonThree = new ActionItem();
buttonThree.setTitle("Help");
buttonThree.setActionId(3);
//buttonThree.setIcon(getResources().getDrawable(R.drawable.menu_eraser));
// The action menu
mContextMenu = new QuickAction(this.getContext());
mContextMenu.setOnDismissListener(this);
// Add buttons
mContextMenu.addActionItem(buttonOne);
mContextMenu.addActionItem(buttonTwo);
mContextMenu.addActionItem(buttonThree);
//setup the action item click listener
mContextMenu.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
#Override
public void onItemClick(QuickAction source, int pos,
int actionId) {
if (actionId == 1) {
callHighLight();
}
else if (actionId == 2) {
callNote();
}
else if (actionId == 3) {
// Do Button 3 stuff
Log.i(TAG, "Hit Button 3");
}
contextMenuVisible = false;
}
});
this.contextMenuVisible = true;
mContextMenu.show(this, displayRect);
}
private void callHighLight(){
((Activity)this.ctx).runOnUiThread(new Runnable() {
#Override
public void run() {
loadUrl("javascript:init_txt_selection_event()");
loadUrl("javascript:highlightme_("+0+")");
}
});
}
private void callNote(){
((Activity)this.ctx).runOnUiThread(new Runnable() {
#Override
public void run() {
loadUrl("javascript:init_txt_selection_event()");
loadUrl("javascript:fnGetUserAddedNote('1')");
}
});
}
//*****************************************************
//*
//* OnDismiss Listener
//*
//*****************************************************
/**
* Clears the selection when the context menu is dismissed.
*/
public void onDismiss(){
//clearSelection();
this.contextMenuVisible = false;
}
//*****************************************************
//*
//* Text Selection Javascript Interface Listener
//*
//*****************************************************
/**
* The user has started dragging the selection handles.
*/
public void tsjiStartSelectionMode(){
this.startSelectionMode();
}
/**
* The user has stopped dragging the selection handles.
*/
public void tsjiEndSelectionMode(){
this.endSelectionMode();
}
/**
* The selection has changed
* #param range
* #param text
* #param handleBounds
* #param menuBounds
* #param showHighlight
* #param showUnHighlight
*/#SuppressWarnings("deprecation")
public void tsjiSelectionChanged(String range, String text, String handleBounds, String menuBounds){
try {
//Log.d(TAG, "tsjiSelectionChanged :- handleBounds " + handleBounds);
JSONObject selectionBoundsObject = new JSONObject(handleBounds);
float scale = getDensityIndependentValue(this.getScale(), ctx);
Rect handleRect = new Rect();
handleRect.left = (int) (getDensityDependentValue(selectionBoundsObject.getInt("left"), getContext()) * scale);
handleRect.top = (int) (getDensityDependentValue(selectionBoundsObject.getInt("top"), getContext()) * scale);
handleRect.right = (int) (getDensityDependentValue(selectionBoundsObject.getInt("right"), getContext()) * scale);
handleRect.bottom = (int) (getDensityDependentValue(selectionBoundsObject.getInt("bottom"), getContext()) * scale);
this.mSelectionBounds = handleRect;
this.selectedRange = range;
this.selectedText = text;
JSONObject menuBoundsObject = new JSONObject(menuBounds);
Rect displayRect = new Rect();
displayRect.left = (int) (getDensityDependentValue(menuBoundsObject.getInt("left"), getContext()) * scale);
displayRect.top = (int) (getDensityDependentValue(menuBoundsObject.getInt("top") - 25, getContext()) * scale);
displayRect.right = (int) (getDensityDependentValue(menuBoundsObject.getInt("right"), getContext()) * scale);
displayRect.bottom = (int) (getDensityDependentValue(menuBoundsObject.getInt("bottom") + 25, getContext()) * scale);
if(!this.isInSelectionMode()){
this.startSelectionMode();
}
// This will send the menu rect
this.showContextMenu(displayRect);
drawSelectionHandles();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Receives the content width for the page.
*/
public void tsjiSetContentWidth(float contentWidth){
this.contentWidth = (int) this.getDensityDependentValue(contentWidth, ctx);
}
//*****************************************************
//*
//* Density Conversion
//*
//*****************************************************
/**
* Returns the density dependent value of the given float
* #param val
* #param ctx
* #return
*/
public float getDensityDependentValue(float val, Context ctx){
// Get display from context
Display display = ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
// Calculate min bound based on metrics
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
return val * (metrics.densityDpi / 160f);
}
/**
* Returns the density independent value of the given float
* #param val
* #param ctx
* #return
*/
public float getDensityIndependentValue(float val, Context ctx){
// Get display from context
Display display = ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
// Calculate min bound based on metrics
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
return val / (metrics.densityDpi / 160f);
}
}
Thanks In Advance!
I realize this is an old question, but there is not an accepted answer, and none of the provided answers have many votes.
I have achieved what you are trying to accomplish by creating a custom action mode callback. This allows the creation of a custom contextual action bar (CAB) when (in the case of a WebView) a user long-clicks the view. NOTE: This only works in 4.0+ and one piece only works in 4.4.
Create a new Android XML file containing the layout for your custom menu. Here is mine (context_menu.xml) as an example:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/copy"
android:icon="#drawable/ic_action_copy"
android:showAsAction="always" <!-- Forces this button to be shown -->
android:title="#string/copy">
</item>
<item
android:id="#+id/button2"
android:icon="#drawable/menu_button2icon"
android:showAsAction="ifRoom" <!-- Show if there is room on the screen-->
android:title="#string/button2">
</item>
<!-- Add as many more items as you want.
Note that if you use "ifRoom", an overflow menu will populate
to hold the action items that did not fit in the action bar. -->
</menu>
Now that the menu is defined, create a callback for it:
public class CustomWebView extends WebView {
private ActionMode.Callback mActionModeCallback;
private class CustomActionModeCallback implements ActionMode.Callback {
// Called when the action mode is created; startActionMode() was called
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return true;
}
// Called each time the action mode is shown.
// Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// Note: This is called every time the selection handlebars move.
return false; // Return false if nothing is done
}
// Called when the user selects a contextual menu item
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.copy:
// Do some stuff for this button
mode.finish(); // Action picked, so close the CAB
return true;
case R.id.button2:
// Do some stuff for this button
mode.finish();
return true;
// Create a case for every item
...
default:
mode.finish();
return false;
}
}
// Called when the user exits the action mode
#Override
public void onDestroyActionMode(ActionMode mode) {
// This will clear the selection highlight and handlebars.
// However, it only works in 4.4; I am still investigating
// how to reliably clear the selection in 4.3 and earlier
clearFocus();
}
}
Once those pieces are in place, override the startActionMode method so that the callback will actually occur on a long-click:
public class CustomWebView extends WebView {
#Override
public ActionMode startActionMode(Callback callback) {
ViewParent parent = getParent();
if (parent == null) {
return null;
}
mActionModeCallback = new CustomActionModeCallback();
return parent.startActionModeForChild(this, mActionModeCallback);
}
}
Now you have a custom menu that will be appear and populate when a user long-clicks your WebView. For reference, I found this information from an Android Developer tutorial and modified the suggestion from this answer.
One final note: This technique overrides the native copy/paste menu for selected text. If you want to maintain that functionality, you will need to implement it yourself. (That is why my first button is 'copy'.) If you need that, refer to this Google tutorial for more information and the proper way to implement it.
Use could the setOnTouchListener() for long/short long press. and return true so that nothing happens thereby overriding the default text selection feature.
I have been able to resolve this. I was also facing this issue and could not find any solution on the web.
So, if you set up a LongClick listener, the Webview would stop showing selection at all. After delving deep into the Webview code, I found that it was calling WebView's method startRunMode and passing an instance of SelectActionCallbackMode class.
I simply extended the Webview class and overrided the startRunMode method like this:
public ActionMode startActionMode(ActionMode.Callback callback)
{
actionModeCallback = new CustomizedSelectActionModeCallback();
return super.startActionMode(actionModeCallback);
}
This forced the Webview to display my Callback instead of displaying Webview's default one. This ensured that selection worked as smoothly as before and my CAB was displayed each time selection was made. Only caveat was that I had to write code to dismiss the CAB myself.
Tested on 4.1, 4.2 and 4.3 devices.
Hope this helps.
I could suggest a workaround for this.
You could use setOnTouchListener and then implement the long press yourself.
onTouch --
case MotionEvent.ACTION_DOWN:
mHanlder.removeCallbacks(startActionBar);
mHandler.postDelayed(startActionBar,1000);
This way you could achieve the same aciton.
some reason the KeyEvent down & up doesn't work in API LEVEL 16+ (Android 4.1+ JELLY_BEAN). It doesn't fire the WebView's loadUrl. So I had to replace the dispatchKeyEvent with dispatchTouchEvent. Here's the code:
...
MotionEvent touchDown = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, touchX, touchY, 0);
webView.dispatchTouchEvent(touchDown);
touchDown.recycle();
MotionEvent touchUp = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, touchX, touchY, 0);
webView.dispatchTouchEvent(touchUp);
touchUp.recycle();
String url = mUrl;
...
try it..
For disabling your text selection from webview try this,
webView.setWebChromeClient(new WebChromeClient(){
[.... other overrides....]
// #Override
// https://bugzilla.wikimedia.org/show_bug.cgi?id=31484
// If you DO NOT want to start selection by long click,
// the remove this function
// (All this is undocumented stuff...)
public void onSelectionStart(WebView view) {
// By default we cancel the selection again, thus disabling
// text selection unless the chrome client supports it.
// view.notifySelectDialogDismissed();
}
});
You might also try overriding View.performLongClick(), which is responsible for calling View.onLongPress(). You could also try going up to the parent View's long press events. Or all the way up to the Window.Callback for your activity (via Activity.getWindow().get/setCallback()).
I'm wondering whether there are other ways for the standard selection context menu to appear besides the long-press event, for example maybe with a trackball or hardware keyboard.
in case someone is trying to simply remove the default text selection, I had the same issue on a Samsung Galaxy Tab on Android 4.1.2 and ended up writing my own WebView:
public class CustomWebView extends WebView {
public CustomWebView(Context context) {
super(context);
this.setUp(context);
}
public CustomWebView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setUp(context);
}
public CustomWebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setUp(context);
}
private void setUp(Context context) {
this.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return true;
}
});
this.setLongClickable(false);
}
#Override
public boolean performLongClick() {
return true;
}
}
and referring it in my xml:
<com...CustomWebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
Use setOnTouchListener() implement long press

Image(s) placement over a image in Android Saving memory

I'm placing ImageView's in a RelativeLayout. I'm setting them with LayoutParams and using setMargins() to set the location of each picture. The max number of Images that will be placed on top of the first one will only reach 8. Their are 5 diffident Images and 8 positions on the screen where they can be placed. I would like to create the Images as their corresponding buttons are pressed and to be able to set that Image into the RelativeLayout and display the change. I would like a way to clear all the Images off the screen except for the main/ background ImageView. I don't like to populate 8 X 5 = 40 Images and then hide them all then change their view to Visible when i need them to show. I need something that will populate as need be but able to destory or remove when I clear it out.
Thanks,
Zelda
aButton.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
noteNumber++;
if(noteNumber <= 8){
note n = new note(getBaseContext());
n.setNoteNumber(noteNumber);
n.setHeight(85);
images.add(n); //ArrayList()
}
populate();
}
});
}
public void populate(){
//if(noteNumber < 9){
for(note a : images){
//note a = images.get(noteNumber-1); //images is of type ArrayList<ImageView>()
if(a != null && a.getMasterImage() != null){
int number = a.getNoteNumber();
imageParams.setMargins(25+45*number, a.getHeight(), 20, 360);
frame.addView(a.getMasterImage(),imageParams);
}
}
}
}
public class note {
private int noteNumber;
private int height;
private ImageView masterImage;
public note(Context c){
masterImage = new ImageView(c);
masterImage.setImageResource(R.raw.zelda);
this.noteNumber = 1;
height = 0;
}
/**
* #return the masterImage
*/
public ImageView getMasterImage() {
return masterImage;
}
/**
* #param masterImage the masterImage to set
*/
public void setMasterImage(ImageView masterImage) {
this.masterImage = masterImage;
}
/**
* #return the noteNumber
*/
public int getNoteNumber() {
return noteNumber;
}
/**
* #param noteNumber the noteNumber to set
*/
public void setNoteNumber(int noteNumber) {
this.noteNumber = noteNumber;
}
/**
* #return the height
*/
public int getHeight() {
return height;
}
/**
* #param height the height to set
*/
public void setHeight(int height) {
this.height = height;
}
}

Live Wallpaper Tutorial

I am trying to do the following from a live wallpaper tutorial I found here.
/**
* Do the actual drawing stuff
*/
private void doDraw(Canvas canvas) {
Bitmap b = BitmapFactory.decodeResource(context.getResources(), IMAGES[current]);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(b, 0, 0, null);
Log.d(TAG, "Drawing finished.");
}
/**
* Update the animation, sprites or whatever.
* If there is nothing to animate set the wait
* attribute of the thread to true
*/
private void updatePhysics() {
// if nothing was updated :
// this.wait = true;
if(previousTime - System.currentTimeMillis() >= 41) { //24 FPS
current = current < IMAGES.length ? current++ : 0;
}
Log.d(TAG, "Updated physics.");
}
But it doesn't seem to work. What am I doing wrong. The "Drawing finished." and "Updated physics." messages are getting printed. But I see the first image only. I'm testing it on the emulator.
Any help would be appreciated. Thanks
I have worked out a simple sample live wallpaper where the color shift over time. Maybe you can use this as a starting point:
package com.cmwmobile.android.samples;
import android.graphics.Canvas;
import android.os.Handler;
import android.service.wallpaper.WallpaperService;
import android.view.SurfaceHolder;
/**
* The SampleLiveWallpaperService class is responsible for showing the
* animation and is an interface to android.
* #author Casper Wakkers - www.cmwmobile.com
*/
public class SampleLiveWallpaperService extends WallpaperService {
private Handler handler = null;
/**
* Inner class representing the actual implementation of the
* Live Wallpaper {#link Engine}.
*/
private class SampleLiveWallpaperEngine extends Engine {
private boolean visible = false;
private int[] colors = {0, 0, 0} ;
/**
* Runnable implementation for the actual work.
*/
private final Runnable runnableSomething = new Runnable() {
/**
* {#inheritDoc}
*/
public void run() {
drawSomething();
}
};
/**
* The drawSomething method is responsible for drawing the animation.
*/
private void drawSomething() {
final SurfaceHolder holder = getSurfaceHolder();
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
if (canvas != null) {
canvas.drawARGB(200, colors[0], colors[1], colors[2]);
}
updateColors(colors);
}
finally {
if (canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
// Reschedule the next redraw.
handler.removeCallbacks(runnableSomething);
if (visible) {
// Play around with the delay for an optimal result.
handler.postDelayed(runnableSomething, 25);
}
}
/**
* Method updateColors updates the colors by increasing the value
* per RGB. The values are reset to zero if the maximum value is
* reached.
* #param colors to be updated.
*/
private void updateColors(int[] colors) {
if (colors[0] < 255) {
colors[0]++;
}
else {
if (colors[1] < 255) {
colors[1]++;
}
else {
if (colors[2] < 255) {
colors[2]++;
}
else {
colors[0] = 0;
colors[1] = 0;
colors[2] = 0;
}
}
}
}
/**
* {#inheritDoc}
*/
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(runnableSomething);
}
/**
* {#inheritDoc}
*/
public void onVisibilityChanged(boolean visible) {
super.onVisibilityChanged(visible);
this.visible = visible;
if (visible) {
drawSomething();
}
else {
handler.removeCallbacks(runnableSomething);
}
}
}
/**
* Constructor. Creates the {#link Handler}.
*/
public SampleLiveWallpaperService() {
handler = new Handler();
}
/**
* {#inheritDoc}
*/
public Engine onCreateEngine() {
return new SampleLiveWallpaperEngine();
}
}
I created a quick tutorial on my employers blog about using SVG in a Live Wallpaper, check it out if you like.
Part 1 http://blog.infrared5.com/2012/03/android-live-wallpaper/
Part 2 http://blog.infrared5.com/2012/03/android-live-wallpaper-part-2/

Categories

Resources