Hiii
i have to create circular menu after R & D i got the following output which is display in image 1 but i want to give effect like image 2 i will put it my code here so you can check it
My current Output image 1 in this button and text display horizontally i want to convert this to arc effect both button and text like below image 2
i want to make this buttons like this image
MainActivity.java
public class MainActivity extends MenuActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override public void createButtons() {
for(int i = 0 ; i < 3 ; i++) {
RotativeButton button = new RotativeButton(this);
if(i==0)
{
button.setBackgroundResource(R.drawable.green);
//button.setBackgroundColor(Color.GREEN);
button.setText("Insurance Green");
button.setPosition(i);
button.setLabel("OPTION "+(i+1));
button.setLayoutParams(new LinearLayout.LayoutParams(100, 100));
}
if(i==1)
{
button.setBackgroundResource(R.drawable.red);
//button.setBackgroundColor(Color.RED);
button.setText("Insurance Red");
button.setPosition(i);
button.setLabel("OPTION "+(i+1));
button.setLayoutParams(new LinearLayout.LayoutParams(100, 100));
}
if(i==2)
{
button.setBackgroundResource(R.drawable.yellow);
//button.setBackgroundColor(Color.YELLOW);
button.setText("Insurance Yellow");
button.setPosition(i);
button.setLabel("OPTION "+(i+1));
button.setLayoutParams(new LinearLayout.LayoutParams(100, 100));
}
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra("id", String.valueOf(i+1));
button.setIntent(intent);
mButtonList.add(button);
}
}
}
MenuActivity.java
public abstract class MenuActivity extends Activity {
protected List<RotativeButton> mButtonList = new ArrayList<RotativeButton>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.common_view);
// RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.mainView);
LinearLayout mainLayout=(LinearLayout)findViewById(R.id.mainView);
getLayoutInflater().inflate(R.layout.menu, mainLayout, true);
final RotativeMenuView customView = (RotativeMenuView) findViewById(R.id.rotativeMenuView);
final Button okBtn = (Button) customView.findViewById(R.id.okBtn);
customView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
public void onGlobalLayout()
{
if(okBtn.getVisibility()==View.VISIBLE)
{
customView.addButtons(mButtonList);
customView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
createButtons();
}
protected abstract void createButtons();
}
RotativeButton.java
public class RotativeButton extends Button {
private int position;
private Intent intent;
private String label;
public RotativeButton(Context context) {
super(context);
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public Intent getIntent() {
return intent;
}
public void setIntent(Intent intent) {
this.intent = intent;
}
}
RotativeMenuView.java
public class RotativeMenuView extends RelativeLayout
{
private List<RotativeButton> _buttonList;
private HashMap<Integer, Point > _pointForPosition = new HashMap<Integer, Point>();
private HashMap<Integer, RectF > _rectForPosition = new HashMap<Integer, RectF>();
private TextView titleTv;
public RotativeMenuView(Context context) {
super(context);
}
public RotativeMenuView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public RotativeMenuView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
public void addButtons(List<RotativeButton> buttonList) {
final Button okBtn = (Button) findViewById(R.id.okBtn);
titleTv = (TextView) findViewById(R.id.labelTv);
okBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
RotativeButton activeButton = getActiveButton();
Intent i = activeButton.getIntent();
getContext().startActivity(i);
}
});
_buttonList = buttonList;
int numberOfButtons = buttonList.size();
final double angle = 360 / numberOfButtons;
int okWidth = okBtn.getMeasuredWidth();
int okHeight = okBtn.getMeasuredHeight();
Log.e("OK_WIDTH", String.valueOf(okWidth));
Log.e("OK_HEIGHT", String.valueOf(okHeight));
int okLeft = okBtn.getLeft();
int okTop = okBtn.getTop();
Log.e("okLeft", String.valueOf(okLeft));
Log.e("okTop", String.valueOf(okTop));
int distance = okWidth;
Log.e("distance", String.valueOf(distance));
final int[] point = new int[2];
okBtn.getLocationInWindow(point);
for (int i = 0; i < numberOfButtons; i++) {
RotativeButton rotativeButton = buttonList.get(i);
int position = rotativeButton.getPosition();
int buttonHeight = rotativeButton.getBackground()
.getIntrinsicHeight();
int buttonWidth = rotativeButton.getBackground()
.getIntrinsicWidth();
int diffHeight = (okHeight / 2) - (buttonHeight / 2);
int diffWidth = (okWidth / 2) - (buttonWidth / 2);
float newAngle = (float) angle * position;
Point nextPoint = nextPosition(okTop + diffHeight, okLeft
+ diffWidth, newAngle, distance);
int newLeft = nextPoint.x;
int newTop = nextPoint.y;
final RectF okRect = new RectF(point[0] - newLeft
- okBtn.getWidth() + diffWidth, point[1] - newTop
- okBtn.getHeight() + diffHeight, (point[0] - newLeft)
+ okBtn.getWidth() + diffWidth, (point[1] - newTop)
+ okBtn.getHeight() + diffHeight);
rotativeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final RotativeButton clickedButton = (RotativeButton) v;
int position = clickedButton.getPosition();
if (position == 0) {
return;
}
int total = _buttonList.size();
final int clickedPosition = total - position;
double angle = 360 / total;
titleTv.setVisibility(INVISIBLE);
for (int i = 0; i < total; i++) {
final RotativeButton currentButton = _buttonList.get(i);
position = currentButton.getPosition();
RectF rectF = _rectForPosition.get(position);
float startAngle = (float) angle * position;
Path aPath = new Path();
aPath.addArc(rectF, startAngle, (float) angle
* clickedPosition);
Animation anim = new PathAnimation(aPath);
anim.setDuration(500);
anim.setAnimationListener(new AnimationListener() {
public void onAnimationStart(Animation animation) {
currentButton.setClickable(false);
okBtn.setClickable(false);
}
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
public void onAnimationEnd(Animation animation) {
currentButton.setClickable(true);
okBtn.setClickable(true);
updatePosition(currentButton, clickedPosition);
currentButton.clearAnimation();
}
});
anim.setFillBefore(true);
currentButton.startAnimation(anim);
}
}
});
LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.topMargin = newTop;
params.leftMargin = newLeft;
addView(rotativeButton, params);
if (position == 0) {
applyLabel(rotativeButton.getLabel());
}
_pointForPosition.put(position, nextPoint);
_rectForPosition.put(position, okRect);
}
}
public void updatePosition(final RotativeButton currentButton, int diffPosition){
int total = _buttonList.size();
int currentPosition = currentButton.getPosition();
int newPosition = currentPosition + diffPosition;
if(newPosition >= total ){
newPosition -= total;
}
currentButton.setPosition(newPosition);
Point pointForPosition = _pointForPosition.get(newPosition);
int newLeft = pointForPosition.x;
int newTop = pointForPosition.y;
Log.d("CustomView", "Button: "+ currentButton.getPosition()+ "("+currentButton.getLabel()+") , New Left:" +newLeft+" top: "+ newTop);
currentButton.layout(newLeft, newTop,
newLeft + currentButton.getMeasuredWidth(), newTop + currentButton.getMeasuredHeight());
Log.d("CustomView", "Moving from:" +currentPosition+" to: "+currentButton.getPosition() + "code: " +currentButton.getLabel());
if (newPosition == 0) {
applyLabel(currentButton.getLabel());
}
}
protected void applyLabel( String label) {
titleTv.setText(label.toUpperCase());
titleTv.setVisibility(VISIBLE);
}
private Point nextPosition(int okTop, int okLeft, double angle, int distance) {
int x = okLeft + (int) (distance*Math.cos(Math.toRadians(angle)));
int y = okTop + (int) (distance*Math.sin(Math.toRadians(angle)));
Log.e("X", String.valueOf(x));
Log.e("Y", String.valueOf(y));
Point p = new Point();
p.set(x, y);
return p;
}
private RotativeButton getActiveButton()
{
for (RotativeButton aButton : _buttonList)
{
int position = aButton.getPosition();
if(position == 0)
{
return aButton;
}
}
return null;
}
}
PathAnimation.java
public class PathAnimation extends Animation {
private PathMeasure measure;
private float[] pos = new float[2];
public PathAnimation(Path path) {
measure = new PathMeasure(path, false);
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t){
measure.getPosTan(measure.getLength() * interpolatedTime, pos,null);
t.getMatrix().setTranslate(pos[0], pos[1]);
}
}
Related
I am making a custom edittext to enter mobile numbers. Here is the code
public class PinEntryEditText extends android.support.v7.widget.AppCompatEditText {
private static final String XML_NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android";
protected String mMask = null;
protected StringBuilder mMaskChars = null;
protected String mSingleCharHint = null;
protected int mAnimatedType = 0;
protected float mSpace = 24; //24 dp by default, space between the lines
protected float mCharSize;
protected float mNumChars = 4;
protected float mTextBottomPadding = 8; //8dp by default, height of the text from our lines
protected int mMaxLength = 4;
protected RectF[] mLineCoords;
protected float[] mCharBottom;
protected Paint mCharPaint;
protected Paint mLastCharPaint;
protected Paint mSingleCharPaint;
protected Drawable mPinBackground;
protected Rect mTextHeight = new Rect();
protected boolean mIsDigitSquare = false;
protected View.OnClickListener mClickListener;
protected OnPinEnteredListener mOnPinEnteredListener = null;
protected float mLineStroke = 1; //1dp by default
protected float mLineStrokeSelected = 2; //2dp by default
protected Paint mLinesPaint;
protected boolean mAnimate = false;
protected boolean mHasError = false;
protected ColorStateList mOriginalTextColors;
protected int[][] mStates = new int[][]{
new int[]{android.R.attr.state_selected}, // selected
new int[]{android.R.attr.state_active}, // error
new int[]{android.R.attr.state_focused}, // focused
new int[]{-android.R.attr.state_focused}, // unfocused
};
protected int[] mColors = new int[]{
Color.GREEN,
Color.RED,
Color.BLACK,
Color.GRAY
};
protected ColorStateList mColorStates = new ColorStateList(mStates, mColors);
public PinEntryEditText(Context context) {
super(context);
}
public PinEntryEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public PinEntryEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// this(context, attrs, android.R.attr.editTextStyle);
init(context, attrs);
}
public void setMaxLength(final int maxLength) {
mMaxLength = maxLength;
mNumChars = maxLength;
setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
setText(null);
invalidate();
}
private void init(Context context, AttributeSet attrs) {
float multi = context.getResources().getDisplayMetrics().density;
mLineStroke = multi * mLineStroke;
mLineStrokeSelected = multi * mLineStrokeSelected;
mSpace = multi * mSpace; //convert to pixels for our density
mTextBottomPadding = multi * mTextBottomPadding; //convert to pixels for our density
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.PinEntryEditText, 0, 0);
try {
TypedValue outValue = new TypedValue();
ta.getValue(R.styleable.PinEntryEditText_pinAnimationType, outValue);
mAnimatedType = outValue.data;
mMask = ta.getString(R.styleable.PinEntryEditText_pinCharacterMask);
mSingleCharHint = ta.getString(R.styleable.PinEntryEditText_pinRepeatedHint);
mLineStroke = ta.getDimension(R.styleable.PinEntryEditText_pinLineStroke, mLineStroke);
mLineStrokeSelected = ta.getDimension(R.styleable.PinEntryEditText_pinLineStrokeSelected, mLineStrokeSelected);
mSpace = ta.getDimension(R.styleable.PinEntryEditText_pinCharacterSpacing, mSpace);
mTextBottomPadding = ta.getDimension(R.styleable.PinEntryEditText_pinTextBottomPadding, mTextBottomPadding);
mIsDigitSquare = ta.getBoolean(R.styleable.PinEntryEditText_pinBackgroundIsSquare, mIsDigitSquare);
mPinBackground = ta.getDrawable(R.styleable.PinEntryEditText_pinBackgroundDrawable);
ColorStateList colors = ta.getColorStateList(R.styleable.PinEntryEditText_pinLineColors);
if (colors != null) {
mColorStates = colors;
}
} finally {
ta.recycle();
}
mCharPaint = new Paint(getPaint());
mLastCharPaint = new Paint(getPaint());
mSingleCharPaint = new Paint(getPaint());
mLinesPaint = new Paint(getPaint());
mLinesPaint.setStrokeWidth(mLineStroke);
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.colorControlActivated,
outValue, true);
int colorSelected = outValue.data;
mColors[0] = colorSelected;
int colorFocused = isInEditMode() ? Color.GRAY : ContextCompat.getColor(context, R.color.pin_normal);
mColors[1] = colorFocused;
int colorUnfocused = isInEditMode() ? Color.GRAY : ContextCompat.getColor(context, R.color.pin_normal);
mColors[2] = colorUnfocused;
setBackgroundResource(0);
mMaxLength = attrs.getAttributeIntValue(XML_NAMESPACE_ANDROID, "maxLength", 4);
mNumChars = mMaxLength;
//Disable copy paste
super.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public void onDestroyActionMode(ActionMode mode) {
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
});
// When tapped, move cursor to end of text.
super.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setSelection(getText().length());
if (mClickListener != null) {
mClickListener.onClick(v);
}
}
});
super.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
setSelection(getText().length());
return true;
}
});
//If input type is password and no mask is set, use a default mask
if ((getInputType() & InputType.TYPE_TEXT_VARIATION_PASSWORD) == InputType.TYPE_TEXT_VARIATION_PASSWORD && TextUtils.isEmpty(mMask)) {
mMask = "\u25CF";
} else if ((getInputType() & InputType.TYPE_NUMBER_VARIATION_PASSWORD) == InputType.TYPE_NUMBER_VARIATION_PASSWORD && TextUtils.isEmpty(mMask)) {
mMask = "\u25CF";
}
if (!TextUtils.isEmpty(mMask)) {
mMaskChars = getMaskChars();
}
//Height of the characters, used if there is a background drawable
getPaint().getTextBounds("|", 0, 1, mTextHeight);
mAnimate = mAnimatedType > -1;
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mOriginalTextColors = getTextColors();
if (mOriginalTextColors != null) {
mLastCharPaint.setColor(mOriginalTextColors.getDefaultColor());
mCharPaint.setColor(mOriginalTextColors.getDefaultColor());
mSingleCharPaint.setColor(getCurrentHintTextColor());
}
int availableWidth = getWidth() - ViewCompat.getPaddingEnd(this) - ViewCompat.getPaddingStart(this);
if (mSpace < 0) {
mCharSize = (availableWidth / (mNumChars * 2 - 1));
} else {
mCharSize = (availableWidth - (mSpace * (mNumChars - 1))) / mNumChars;
}
mLineCoords = new RectF[(int) mNumChars];
mCharBottom = new float[(int) mNumChars];
int startX;
int bottom = getHeight() - getPaddingBottom();
int rtlFlag;
final boolean isLayoutRtl = TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == ViewCompat.LAYOUT_DIRECTION_RTL;
if (isLayoutRtl) {
rtlFlag = -1;
startX = (int) (getWidth() - ViewCompat.getPaddingStart(this) - mCharSize);
} else {
rtlFlag = 1;
startX = ViewCompat.getPaddingStart(this);
}
for (int i = 0; i < mNumChars; i++) {
mLineCoords[i] = new RectF(startX, bottom, startX + mCharSize, bottom);
if (mPinBackground != null) {
if (mIsDigitSquare) {
mLineCoords[i].top = getPaddingTop();
mLineCoords[i].right = startX + mLineCoords[i].height();
} else {
mLineCoords[i].top -= mTextHeight.height() + mTextBottomPadding * 2;
}
}
if (mSpace < 0) {
startX += rtlFlag * mCharSize * 2;
} else {
startX += rtlFlag * (mCharSize + mSpace);
}
mCharBottom[i] = mLineCoords[i].bottom - mTextBottomPadding;
}
}
#Override
public void setOnClickListener(View.OnClickListener l) {
mClickListener = l;
}
#Override
public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) {
throw new RuntimeException("setCustomSelectionActionModeCallback() not supported.");
}
#Override
protected void onDraw(Canvas canvas) {
//super.onDraw(canvas);
CharSequence text = getFullText();
int textLength = text.length();
float[] textWidths = new float[textLength];
getPaint().getTextWidths(text, 0, textLength, textWidths);
float hintWidth = 0;
if (mSingleCharHint != null) {
float[] hintWidths = new float[mSingleCharHint.length()];
getPaint().getTextWidths(mSingleCharHint, hintWidths);
for (float i : hintWidths) {
hintWidth += i;
}
}
for (int i = 0; i < mNumChars; i++) {
//If a background for the pin characters is specified, it should be behind the characters.
if (mPinBackground != null) {
updateDrawableState(i < textLength, i == textLength);
mPinBackground.setBounds((int) mLineCoords[i].left, (int) mLineCoords[i].top, (int) mLineCoords[i].right, (int) mLineCoords[i].bottom);
mPinBackground.draw(canvas);
}
float middle = mLineCoords[i].left + mCharSize / 2;
if (textLength > i) {
if (!mAnimate || i != textLength - 1) {
canvas.drawText(text, i, i + 1, middle - textWidths[i] / 2, mCharBottom[i], mCharPaint);
} else {
canvas.drawText(text, i, i + 1, middle - textWidths[i] / 2, mCharBottom[i], mLastCharPaint);
}
} else if (mSingleCharHint != null) {
canvas.drawText(mSingleCharHint, middle - hintWidth / 2, mCharBottom[i], mSingleCharPaint);
}
//The lines should be in front of the text (because that's how I want it).
if (mPinBackground == null) {
updateColorForLines(i <= textLength);
canvas.drawLine(mLineCoords[i].left, mLineCoords[i].top, mLineCoords[i].right, mLineCoords[i].bottom, mLinesPaint);
}
}
}
private CharSequence getFullText() {
if (mMask == null) {
return getText();
} else {
return getMaskChars();
}
}
private StringBuilder getMaskChars() {
if (mMaskChars == null) {
mMaskChars = new StringBuilder();
}
int textLength = getText().length();
while (mMaskChars.length() != textLength) {
if (mMaskChars.length() < textLength) {
mMaskChars.append(mMask);
} else {
mMaskChars.deleteCharAt(mMaskChars.length() - 1);
}
}
return mMaskChars;
}
private int getColorForState(int... states) {
return mColorStates.getColorForState(states, Color.GRAY);
}
/**
* #param hasTextOrIsNext Is the color for a character that has been typed or is
* the next character to be typed?
*/
protected void updateColorForLines(boolean hasTextOrIsNext) {
if (mHasError) {
mLinesPaint.setColor(getColorForState(android.R.attr.state_active));
} else if (isFocused()) {
mLinesPaint.setStrokeWidth(mLineStrokeSelected);
mLinesPaint.setColor(getColorForState(android.R.attr.state_focused));
if (hasTextOrIsNext) {
mLinesPaint.setColor(getColorForState(android.R.attr.state_selected));
}
} else {
mLinesPaint.setStrokeWidth(mLineStroke);
mLinesPaint.setColor(getColorForState(-android.R.attr.state_focused));
}
}
protected void updateDrawableState(boolean hasText, boolean isNext) {
if (mHasError) {
mPinBackground.setState(new int[]{android.R.attr.state_active});
} else if (isFocused()) {
mPinBackground.setState(new int[]{android.R.attr.state_focused});
if (isNext) {
mPinBackground.setState(new int[]{android.R.attr.state_focused, android.R.attr.state_selected});
} else if (hasText) {
mPinBackground.setState(new int[]{android.R.attr.state_focused, android.R.attr.state_checked});
}
} else {
mPinBackground.setState(new int[]{-android.R.attr.state_focused});
}
}
public void setError(boolean hasError) {
mHasError = hasError;
}
public boolean isError() {
return mHasError;
}
/**
* Request focus on this PinEntryEditText
*/
public void focus() {
requestFocus();
// Show keyboard
InputMethodManager inputMethodManager = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(this, 0);
}
#Override
protected void onTextChanged(CharSequence text, final int start, int lengthBefore, final int lengthAfter) {
setError(false);
if (mLineCoords == null || !mAnimate) {
if (mOnPinEnteredListener != null && text.length() == mMaxLength) {
mOnPinEnteredListener.onPinEntered(text);
}
return;
}
if (mAnimatedType == -1) {
invalidate();
return;
}
if (lengthAfter > lengthBefore) {
if (mAnimatedType == 0) {
animatePopIn();
} else {
animateBottomUp(text, start);
}
}
}
private void animatePopIn() {
ValueAnimator va = ValueAnimator.ofFloat(1, getPaint().getTextSize());
va.setDuration(200);
va.setInterpolator(new OvershootInterpolator());
va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
mLastCharPaint.setTextSize((Float) animation.getAnimatedValue());
PinEntryEditText.this.invalidate();
}
});
if (getText().length() == mMaxLength && mOnPinEnteredListener != null) {
va.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
mOnPinEnteredListener.onPinEntered(getText());
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
va.start();
}
private void animateBottomUp(CharSequence text, final int start) {
mCharBottom[start] = mLineCoords[start].bottom - mTextBottomPadding;
ValueAnimator animUp = ValueAnimator.ofFloat(mCharBottom[start] + getPaint().getTextSize(), mCharBottom[start]);
animUp.setDuration(300);
animUp.setInterpolator(new OvershootInterpolator());
animUp.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
Float value = (Float) animation.getAnimatedValue();
mCharBottom[start] = value;
PinEntryEditText.this.invalidate();
}
});
mLastCharPaint.setAlpha(255);
ValueAnimator animAlpha = ValueAnimator.ofInt(0, 255);
animAlpha.setDuration(300);
animAlpha.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
Integer value = (Integer) animation.getAnimatedValue();
mLastCharPaint.setAlpha(value);
}
});
AnimatorSet set = new AnimatorSet();
if (text.length() == mMaxLength && mOnPinEnteredListener != null) {
set.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
mOnPinEnteredListener.onPinEntered(getText());
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
set.playTogether(animUp, animAlpha);
set.start();
}
public void setAnimateText(boolean animate) {
mAnimate = animate;
}
public void setOnPinEnteredListener(OnPinEnteredListener l) {
mOnPinEnteredListener = l;
}
public interface OnPinEnteredListener {
void onPinEntered(CharSequence str);
}
}
Following is the xml
<com.cartoon.customLayout.PinEntryEditText
android:id="#+id/et_activity_mobile_pinEntryEditText"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="#null"
android:cursorVisible="true"
android:digits="1234567890"
android:focusable="true"
android:imeOptions="actionDone"
android:inputType="number|phone"
android:maxLength="10"
android:textColor="#android:color/white"
android:textIsSelectable="true"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.40"
app:pinAnimationType="fromBottom"
app:pinBackgroundDrawable="#drawable/bg_pin"
app:pinCharacterSpacing="4dp" />
Suppose the user enters his mobile number and the second digit entered is wrong then the problem is, he/she has to erase the entered characters leading to the second character for a change.
I went through the following posts but they are of no help
Custom EditText is not showing keyboard on focus
Custom Android pin code entry widget
https://github.com/ChaosLeong/PinView
Setting focusable, clickable or focusableInTouchMode does not work. Tried both in XML and code.
The below library does solve my problem but it has some other problem for which I have raised an issue
https://github.com/mukeshsolanki/android-otpview-pinview
Issue: https://github.com/mukeshsolanki/android-otpview-pinview/issues/26
Of course I could take 10 edittext and achieve the result which I want but that is not the right way and I will resort to that option in case I am not able to find the right solution to this one.
The answer is in your java code. As mentioned in the comment just remove this from the init() method.
// When tapped, move cursor to end of text.
super.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setSelection(getText().length());
if (mClickListener != null) {
mClickListener.onClick(v);
}
}
});
Please make the following changes:
In your PinEntryEditText class:
// When tapped, move cursor to end of text.
super.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//setSelection(getText().length());
if (mClickListener != null) {
mClickListener.onClick(v);
}
}
});
I think setSelection(getText().length()); was setting selection to the end of the EditText no matter where the click even occured.
And in your XML, do these: android:cursorVisible="true" and android:textIsSelectable="true"
How to enable zoom for listView for my app?I have found solution here: https://github.com/matrixxun/PullToZoomInListView but I get error: Unexpected cast to PullToZoomListView: layout tag was listView!
listView = (PullToZoomListView)findViewById(R.id.usb_list);
USBProductID.class
public class USBProductID extends AppCompatActivity
{
PullToZoomListView listView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.usbproductid);
//ListView listView = (ListView) findViewById(R.id.usb_list);
listView = (PullToZoomListView)findViewById(R.id.usb_list);
ViewGroup headerView = (ViewGroup)getLayoutInflater().inflate(R.layout.header,listView,false);
listView.addHeaderView(headerView);
String[] items = getResources().getStringArray(R.array.list_items);
ListAdapter adapter = new ListAdapter(this,R.layout.rowlayout,R.id.textcompany,items);
listView.setAdapter(adapter);
}
}
ListAdapter.class
public class ListAdapter extends ArrayAdapter<String>
{
int vg;
String[] item_list;
Context context;
public ListAdapter(Context context, int vg, int id, String[] item_list)
{
super(context, vg, id, item_list);
this.context = context;
this.item_list = item_list;
this.vg = vg;
}
// Hold views of the ListView to improve its scrolling performance
static class ViewHolder
{
public TextView txtmanufacturer;
public TextView txtvendorid;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View rowView = convertView;
if(rowView == null)
{
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(vg,parent,false);
ViewHolder holder = new ViewHolder();
holder.txtmanufacturer = (TextView)rowView.findViewById(R.id.textcompany);
holder.txtvendorid = (TextView)rowView.findViewById(R.id.textvendorid);
rowView.setTag(holder);
}
String[] items = item_list[position].split("_");
ViewHolder holder = (ViewHolder)rowView.getTag();
holder.txtmanufacturer.setText(items[0]);
holder.txtvendorid.setText(items[1]);
return rowView;
}
}
PullToZoomListView.class
public class PullToZoomListView extends ListView implements
AbsListView.OnScrollListener {
private static final int INVALID_VALUE = -1;
private static final String TAG = "PullToZoomListView";
private static final Interpolator sInterpolator = new Interpolator() {
public float getInterpolation(float paramAnonymousFloat) {
float f = paramAnonymousFloat - 1.0F;
return 1.0F + f * (f * (f * (f * f)));
}
};
int mActivePointerId = -1;
private FrameLayout mHeaderContainer;
private int mHeaderHeight;
private ImageView mHeaderImage;
float mLastMotionY = -1.0F;
float mLastScale = -1.0F;
float mMaxScale = -1.0F;
private OnScrollListener mOnScrollListener;
private ScalingRunnalable mScalingRunnalable;
private int mScreenHeight;
private ImageView mShadow;
public PullToZoomListView(Context paramContext) {
super(paramContext);
init(paramContext);
}
public PullToZoomListView(Context paramContext,
AttributeSet paramAttributeSet) {
super(paramContext, paramAttributeSet);
init(paramContext);
}
public PullToZoomListView(Context paramContext,
AttributeSet paramAttributeSet, int paramInt) {
super(paramContext, paramAttributeSet, paramInt);
init(paramContext);
}
private void endScraling() {
if (this.mHeaderContainer.getBottom() >= this.mHeaderHeight)
Log.d("mmm", "endScraling");
this.mScalingRunnalable.startAnimation(200L);
}
private void init(Context paramContext) {
DisplayMetrics localDisplayMetrics = new DisplayMetrics();
((Activity) paramContext).getWindowManager().getDefaultDisplay()
.getMetrics(localDisplayMetrics);
this.mScreenHeight = localDisplayMetrics.heightPixels;
this.mHeaderContainer = new FrameLayout(paramContext);
this.mHeaderImage = new ImageView(paramContext);
int i = localDisplayMetrics.widthPixels;
setHeaderViewSize(i, (int) (9.0F * (i / 16.0F)));
this.mShadow = new ImageView(paramContext);
FrameLayout.LayoutParams localLayoutParams = new FrameLayout.LayoutParams(
-1, -2);
localLayoutParams.gravity = 80;
this.mShadow.setLayoutParams(localLayoutParams);
this.mHeaderContainer.addView(this.mHeaderImage);
this.mHeaderContainer.addView(this.mShadow);
addHeaderView(this.mHeaderContainer);
this.mScalingRunnalable = new ScalingRunnalable();
super.setOnScrollListener(this);
}
private void onSecondaryPointerUp(MotionEvent paramMotionEvent) {
int i = (paramMotionEvent.getAction()) >> 8;
if (paramMotionEvent.getPointerId(i) == this.mActivePointerId)
if (i != 0) {
int j = 1;
this.mLastMotionY = paramMotionEvent.getY(0);
this.mActivePointerId = paramMotionEvent.getPointerId(0);
return;
}
}
private void reset() {
this.mActivePointerId = -1;
this.mLastMotionY = -1.0F;
this.mMaxScale = -1.0F;
this.mLastScale = -1.0F;
}
public ImageView getHeaderView() {
return this.mHeaderImage;
}
public boolean onInterceptTouchEvent(MotionEvent paramMotionEvent) {
return super.onInterceptTouchEvent(paramMotionEvent);
}
protected void onLayout(boolean paramBoolean, int paramInt1, int paramInt2,
int paramInt3, int paramInt4) {
super.onLayout(paramBoolean, paramInt1, paramInt2, paramInt3, paramInt4);
if (this.mHeaderHeight == 0)
this.mHeaderHeight = this.mHeaderContainer.getHeight();
}
#Override
public void onScroll(AbsListView paramAbsListView, int paramInt1,
int paramInt2, int paramInt3) {
Log.d("mmm", "onScroll");
float f = this.mHeaderHeight - this.mHeaderContainer.getBottom();
Log.d("mmm", "f|" + f);
if ((f > 0.0F) && (f < this.mHeaderHeight)) {
Log.d("mmm", "1");
int i = (int) (0.65D * f);
this.mHeaderImage.scrollTo(0, -i);
} else if (this.mHeaderImage.getScrollY() != 0) {
Log.d("mmm", "2");
this.mHeaderImage.scrollTo(0, 0);
}
if (this.mOnScrollListener != null) {
this.mOnScrollListener.onScroll(paramAbsListView, paramInt1,
paramInt2, paramInt3);
}
}
public void onScrollStateChanged(AbsListView paramAbsListView, int paramInt) {
if (this.mOnScrollListener != null)
this.mOnScrollListener.onScrollStateChanged(paramAbsListView,
paramInt);
}
public boolean onTouchEvent(MotionEvent paramMotionEvent) {
Log.d("mmm", "" + (0xFF & paramMotionEvent.getAction()));
switch (0xFF & paramMotionEvent.getAction()) {
case 4:
case 0:
if (!this.mScalingRunnalable.mIsFinished) {
this.mScalingRunnalable.abortAnimation();
}
this.mLastMotionY = paramMotionEvent.getY();
this.mActivePointerId = paramMotionEvent.getPointerId(0);
this.mMaxScale = (this.mScreenHeight / this.mHeaderHeight);
this.mLastScale = (this.mHeaderContainer.getBottom() / this.mHeaderHeight);
break;
case 2:
Log.d("mmm", "mActivePointerId" + mActivePointerId);
int j = paramMotionEvent.findPointerIndex(this.mActivePointerId);
if (j == -1) {
Log.e("PullToZoomListView", "Invalid pointerId="
+ this.mActivePointerId + " in onTouchEvent");
} else {
if (this.mLastMotionY == -1.0F)
this.mLastMotionY = paramMotionEvent.getY(j);
if (this.mHeaderContainer.getBottom() >= this.mHeaderHeight) {
ViewGroup.LayoutParams localLayoutParams = this.mHeaderContainer
.getLayoutParams();
float f = ((paramMotionEvent.getY(j) - this.mLastMotionY + this.mHeaderContainer
.getBottom()) / this.mHeaderHeight - this.mLastScale)
/ 2.0F + this.mLastScale;
if ((this.mLastScale <= 1.0D) && (f < this.mLastScale)) {
localLayoutParams.height = this.mHeaderHeight;
this.mHeaderContainer
.setLayoutParams(localLayoutParams);
return super.onTouchEvent(paramMotionEvent);
}
this.mLastScale = Math.min(Math.max(f, 1.0F),
this.mMaxScale);
localLayoutParams.height = ((int) (this.mHeaderHeight * this.mLastScale));
if (localLayoutParams.height < this.mScreenHeight)
this.mHeaderContainer
.setLayoutParams(localLayoutParams);
this.mLastMotionY = paramMotionEvent.getY(j);
return true;
}
this.mLastMotionY = paramMotionEvent.getY(j);
}
break;
case 1:
reset();
endScraling();
break;
case 3:
int i = paramMotionEvent.getActionIndex();
this.mLastMotionY = paramMotionEvent.getY(i);
this.mActivePointerId = paramMotionEvent.getPointerId(i);
break;
case 5:
onSecondaryPointerUp(paramMotionEvent);
this.mLastMotionY = paramMotionEvent.getY(paramMotionEvent
.findPointerIndex(this.mActivePointerId));
break;
case 6:
}
return super.onTouchEvent(paramMotionEvent);
}
public void setHeaderViewSize(int paramInt1, int paramInt2) {
Object localObject = this.mHeaderContainer.getLayoutParams();
if (localObject == null)
localObject = new LayoutParams(paramInt1, paramInt2);
((ViewGroup.LayoutParams) localObject).width = paramInt1;
((ViewGroup.LayoutParams) localObject).height = paramInt2;
this.mHeaderContainer
.setLayoutParams((ViewGroup.LayoutParams) localObject);
this.mHeaderHeight = paramInt2;
}
public void setOnScrollListener(
OnScrollListener paramOnScrollListener) {
this.mOnScrollListener = paramOnScrollListener;
}
public void setShadow(int paramInt) {
this.mShadow.setBackgroundResource(paramInt);
}
class ScalingRunnalable implements Runnable {
long mDuration;
boolean mIsFinished = true;
float mScale;
long mStartTime;
ScalingRunnalable() {
}
public void abortAnimation() {
this.mIsFinished = true;
}
public boolean isFinished() {
return this.mIsFinished;
}
public void run() {
float f2;
ViewGroup.LayoutParams localLayoutParams;
if ((!this.mIsFinished) && (this.mScale > 1.0D)) {
float f1 = ((float) SystemClock.currentThreadTimeMillis() - (float) this.mStartTime)
/ (float) this.mDuration;
f2 = this.mScale - (this.mScale - 1.0F)
* PullToZoomListView.sInterpolator.getInterpolation(f1);
localLayoutParams = PullToZoomListView.this.mHeaderContainer
.getLayoutParams();
if (f2 > 1.0F) {
Log.d("mmm", "f2>1.0");
localLayoutParams.height = PullToZoomListView.this.mHeaderHeight;
;
localLayoutParams.height = ((int) (f2 * PullToZoomListView.this.mHeaderHeight));
PullToZoomListView.this.mHeaderContainer
.setLayoutParams(localLayoutParams);
PullToZoomListView.this.post(this);
return;
}
this.mIsFinished = true;
}
}
public void startAnimation(long paramLong) {
this.mStartTime = SystemClock.currentThreadTimeMillis();
this.mDuration = paramLong;
this.mScale = ((float) (PullToZoomListView.this.mHeaderContainer
.getBottom()) / PullToZoomListView.this.mHeaderHeight);
this.mIsFinished = false;
PullToZoomListView.this.post(this);
}
}
}
usbproductid.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/usb_list"/>
<TextView
android:text="USB Vendor IDs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_marginTop="18dp"
android:textSize="18sp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Use this :
<PullToZoomListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/usb_list"/>
in you activity
mZoomView.setAdapter(adapter);
mZoomView.getHeaderView().setImageResource(R.drawable.dsf);
mZoomView.getHeaderView().setScaleType(ImageView.ScaleType.CENTER_CROP);
I am using a floating action button in my activity. I have created a related layout with a black opacity background. I want it to appear when the floating action button is clicked. The relative layout will appear behind the action button to make it look prominent.
Here is my xml layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fab="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.paaltao.activity.HomeActivity">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<it.neokree.materialtabs.MaterialTabHost
android:id="#+id/materialTabHost"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_below="#+id/app_bar"
app:accentColor="#color/greenMaterial"
app:hasIcons="true"
app:primaryColor="#color/primaryColor"
app:textColor="#color/white" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/materialTabHost" />
<RelativeLayout
android:id="#+id/white_opacity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/materialTabHost"
android:background="#color/black80"
android:visibility="gone" />
<com.paaltao.classes.FloatingActionsMenu
android:id="#+id/multiple_actions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_gravity="end"
fab:fab_addButtonColorPressed="#color/white_pressed"
fab:fab_addButtonPlusIconColor="#color/white"
fab:fab_labelStyle="#style/menu_labels_style"
app:fab_addButtonColorNormal="#color/primaryColor">
<com.paaltao.classes.FloatingActionButton
android:id="#+id/action_b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fab:fab_colorNormal="#color/white"
fab:fab_colorPressed="#color/white_pressed"
fab:fab_title="Action B" />
</com.paaltao.classes.FloatingActionsMenu>
</RelativeLayout>
I am basically trying to set visibility of the relative layout to View.VISIBLE in the floating action menu class which extends a view group. Now I am getting null pointer exception when I am setting the visibility as View.VISIBLE in the button's onClick event.
Here is my Java Code :
package com.paaltao.classes;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.ColorRes;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.paaltao.R;
import java.util.zip.Inflater;
public class FloatingActionsMenu extends ViewGroup {
public static final int EXPAND_UP = 0;
public static final int EXPAND_DOWN = 1;
public static final int EXPAND_LEFT = 2;
public static final int EXPAND_RIGHT = 3;
private static final int ANIMATION_DURATION = 300;
private static final float COLLAPSED_PLUS_ROTATION = 0f;
private static final float EXPANDED_PLUS_ROTATION = 90f + 45f;
private int mAddButtonPlusColor;
private int mAddButtonColorNormal;
private int mAddButtonColorPressed;
private int mAddButtonSize;
private boolean mAddButtonStrokeVisible;
private int mExpandDirection;
private int mButtonSpacing;
private int mLabelsMargin;
private int mLabelsVerticalOffset;
private boolean mExpanded;
private AnimatorSet mExpandAnimation = new AnimatorSet().setDuration(ANIMATION_DURATION);
private AnimatorSet mCollapseAnimation = new AnimatorSet().setDuration(ANIMATION_DURATION);
private AddFloatingActionButton mAddButton;
private RotatingDrawable mRotatingDrawable;
private int mMaxButtonWidth;
private int mMaxButtonHeight;
private int mLabelsStyle;
private int mButtonsCount;
private OnFloatingActionsMenuUpdateListener mListener;
private RelativeLayout whiteOverlay;
public interface OnFloatingActionsMenuUpdateListener {
void onMenuExpanded();
void onMenuCollapsed();
}
public FloatingActionsMenu(Context context) {
this(context, null);
}
public FloatingActionsMenu(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public FloatingActionsMenu(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(Context context, AttributeSet attributeSet) {
mButtonSpacing = (int) (getResources().getDimension(R.dimen.fab_actions_spacing) - getResources().getDimension(R.dimen.fab_shadow_radius) - getResources().getDimension(R.dimen.fab_shadow_offset));
mLabelsMargin = getResources().getDimensionPixelSize(R.dimen.fab_labels_margin);
mLabelsVerticalOffset = getResources().getDimensionPixelSize(R.dimen.fab_shadow_offset);
TypedArray attr = context.obtainStyledAttributes(attributeSet, R.styleable.FloatingActionsMenu, 0, 0);
mAddButtonPlusColor = attr.getColor(R.styleable.FloatingActionsMenu_fab_addButtonPlusIconColor, getColor(android.R.color.white));
mAddButtonColorNormal = attr.getColor(R.styleable.FloatingActionsMenu_fab_addButtonColorNormal, getColor(android.R.color.holo_blue_dark));
mAddButtonColorPressed = attr.getColor(R.styleable.FloatingActionsMenu_fab_addButtonColorPressed, getColor(android.R.color.holo_blue_light));
mAddButtonSize = attr.getInt(R.styleable.FloatingActionsMenu_fab_addButtonSize, FloatingActionButton.SIZE_NORMAL);
mAddButtonStrokeVisible = attr.getBoolean(R.styleable.FloatingActionsMenu_fab_addButtonStrokeVisible, true);
mExpandDirection = attr.getInt(R.styleable.FloatingActionsMenu_fab_expandDirection, EXPAND_UP);
mLabelsStyle = attr.getResourceId(R.styleable.FloatingActionsMenu_fab_labelStyle, 0);
attr.recycle();
if (mLabelsStyle != 0 && expandsHorizontally()) {
throw new IllegalStateException("Action labels in horizontal expand orientation is not supported.");
}
createAddButton(context);
}
public void setOnFloatingActionsMenuUpdateListener(OnFloatingActionsMenuUpdateListener listener) {
mListener = listener;
}
private boolean expandsHorizontally() {
return mExpandDirection == EXPAND_LEFT || mExpandDirection == EXPAND_RIGHT;
}
private static class RotatingDrawable extends LayerDrawable {
public RotatingDrawable(Drawable drawable) {
super(new Drawable[] { drawable });
}
private float mRotation;
#SuppressWarnings("UnusedDeclaration")
public float getRotation() {
return mRotation;
}
#SuppressWarnings("UnusedDeclaration")
public void setRotation(float rotation) {
mRotation = rotation;
invalidateSelf();
}
#Override
public void draw(Canvas canvas) {
canvas.save();
canvas.rotate(mRotation, getBounds().centerX(), getBounds().centerY());
super.draw(canvas);
canvas.restore();
}
}
private void createAddButton(Context context) {
mAddButton = new AddFloatingActionButton(context) {
#Override
void updateBackground() {
mPlusColor = mAddButtonPlusColor;
mColorNormal = mAddButtonColorNormal;
mColorPressed = mAddButtonColorPressed;
mStrokeVisible = mAddButtonStrokeVisible;
super.updateBackground();
}
#Override
Drawable getIconDrawable() {
final RotatingDrawable rotatingDrawable = new RotatingDrawable(super.getIconDrawable());
mRotatingDrawable = rotatingDrawable;
final OvershootInterpolator interpolator = new OvershootInterpolator();
final ObjectAnimator collapseAnimator = ObjectAnimator.ofFloat(rotatingDrawable, "rotation", EXPANDED_PLUS_ROTATION, COLLAPSED_PLUS_ROTATION);
final ObjectAnimator expandAnimator = ObjectAnimator.ofFloat(rotatingDrawable, "rotation", COLLAPSED_PLUS_ROTATION, EXPANDED_PLUS_ROTATION);
collapseAnimator.setInterpolator(interpolator);
expandAnimator.setInterpolator(interpolator);
mExpandAnimation.play(expandAnimator);
mCollapseAnimation.play(collapseAnimator);
return rotatingDrawable;
}
};
mAddButton.setId(R.id.fab_expand_menu_button);
mAddButton.setSize(mAddButtonSize);
mAddButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
toggle();
// updateBackground();
}
});
addView(mAddButton, super.generateDefaultLayoutParams());
}
// public void updateBackground(){
// whiteOverlay = (RelativeLayout)findViewById(R.id.white_opacity);
// whiteOverlay.setVisibility(View.VISIBLE);
// }
public void addButton(FloatingActionButton button) {
addView(button, mButtonsCount - 1);
mButtonsCount++;
if (mLabelsStyle != 0) {
createLabels();
}
}
public void removeButton(FloatingActionButton button) {
removeView(button.getLabelView());
removeView(button);
mButtonsCount--;
}
private int getColor(#ColorRes int id) {
return getResources().getColor(id);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
measureChildren(widthMeasureSpec, heightMeasureSpec);
int width = 0;
int height = 0;
mMaxButtonWidth = 0;
mMaxButtonHeight = 0;
int maxLabelWidth = 0;
for (int i = 0; i < mButtonsCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
switch (mExpandDirection) {
case EXPAND_UP:
case EXPAND_DOWN:
mMaxButtonWidth = Math.max(mMaxButtonWidth, child.getMeasuredWidth());
height += child.getMeasuredHeight();
break;
case EXPAND_LEFT:
case EXPAND_RIGHT:
width += child.getMeasuredWidth();
mMaxButtonHeight = Math.max(mMaxButtonHeight, child.getMeasuredHeight());
break;
}
if (!expandsHorizontally()) {
TextView label = (TextView) child.getTag(R.id.fab_label);
if (label != null) {
maxLabelWidth = Math.max(maxLabelWidth, label.getMeasuredWidth());
}
}
}
if (!expandsHorizontally()) {
width = mMaxButtonWidth + (maxLabelWidth > 0 ? maxLabelWidth + mLabelsMargin : 0);
} else {
height = mMaxButtonHeight;
}
switch (mExpandDirection) {
case EXPAND_UP:
case EXPAND_DOWN:
height += mButtonSpacing * (getChildCount() - 1);
height = adjustForOvershoot(height);
break;
case EXPAND_LEFT:
case EXPAND_RIGHT:
width += mButtonSpacing * (getChildCount() - 1);
width = adjustForOvershoot(width);
break;
}
setMeasuredDimension(width, height);
}
private int adjustForOvershoot(int dimension) {
return dimension * 12 / 10;
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
switch (mExpandDirection) {
case EXPAND_UP:
case EXPAND_DOWN:
boolean expandUp = mExpandDirection == EXPAND_UP;
int addButtonY = expandUp ? b - t - mAddButton.getMeasuredHeight() : 0;
// Ensure mAddButton is centered on the line where the buttons should be
int addButtonLeft = r - l - mMaxButtonWidth + (mMaxButtonWidth - mAddButton.getMeasuredWidth()) / 2;
mAddButton.layout(addButtonLeft, addButtonY, addButtonLeft + mAddButton.getMeasuredWidth(), addButtonY + mAddButton.getMeasuredHeight());
int labelsRight = r - l - mMaxButtonWidth - mLabelsMargin;
int nextY = expandUp ?
addButtonY - mButtonSpacing :
addButtonY + mAddButton.getMeasuredHeight() + mButtonSpacing;
for (int i = mButtonsCount - 1; i >= 0; i--) {
final View child = getChildAt(i);
if (child == mAddButton || child.getVisibility() == GONE) continue;
int childX = addButtonLeft + (mAddButton.getMeasuredWidth() - child.getMeasuredWidth()) / 2;
int childY = expandUp ? nextY - child.getMeasuredHeight() : nextY;
child.layout(childX, childY, childX + child.getMeasuredWidth(), childY + child.getMeasuredHeight());
float collapsedTranslation = addButtonY - childY;
float expandedTranslation = 0f;
child.setTranslationY(mExpanded ? expandedTranslation : collapsedTranslation);
child.setAlpha(mExpanded ? 1f : 0f);
LayoutParams params = (LayoutParams) child.getLayoutParams();
params.mCollapseDir.setFloatValues(expandedTranslation, collapsedTranslation);
params.mExpandDir.setFloatValues(collapsedTranslation, expandedTranslation);
params.setAnimationsTarget(child);
View label = (View) child.getTag(R.id.fab_label);
if (label != null) {
int labelLeft = labelsRight - label.getMeasuredWidth();
int labelTop = childY - mLabelsVerticalOffset + (child.getMeasuredHeight() - label.getMeasuredHeight()) / 2;
label.layout(labelLeft, labelTop, labelsRight, labelTop + label.getMeasuredHeight());
label.setTranslationY(mExpanded ? expandedTranslation : collapsedTranslation);
label.setAlpha(mExpanded ? 1f : 0f);
LayoutParams labelParams = (LayoutParams) label.getLayoutParams();
labelParams.mCollapseDir.setFloatValues(expandedTranslation, collapsedTranslation);
labelParams.mExpandDir.setFloatValues(collapsedTranslation, expandedTranslation);
labelParams.setAnimationsTarget(label);
}
nextY = expandUp ?
childY - mButtonSpacing :
childY + child.getMeasuredHeight() + mButtonSpacing;
}
break;
case EXPAND_LEFT:
case EXPAND_RIGHT:
boolean expandLeft = mExpandDirection == EXPAND_LEFT;
int addButtonX = expandLeft ? r - l - mAddButton.getMeasuredWidth() : 0;
// Ensure mAddButton is centered on the line where the buttons should be
int addButtonTop = b - t - mMaxButtonHeight + (mMaxButtonHeight - mAddButton.getMeasuredHeight()) / 2;
mAddButton.layout(addButtonX, addButtonTop, addButtonX + mAddButton.getMeasuredWidth(), addButtonTop + mAddButton.getMeasuredHeight());
int nextX = expandLeft ?
addButtonX - mButtonSpacing :
addButtonX + mAddButton.getMeasuredWidth() + mButtonSpacing;
for (int i = mButtonsCount - 1; i >= 0; i--) {
final View child = getChildAt(i);
if (child == mAddButton || child.getVisibility() == GONE) continue;
int childX = expandLeft ? nextX - child.getMeasuredWidth() : nextX;
int childY = addButtonTop + (mAddButton.getMeasuredHeight() - child.getMeasuredHeight()) / 2;
child.layout(childX, childY, childX + child.getMeasuredWidth(), childY + child.getMeasuredHeight());
float collapsedTranslation = addButtonX - childX;
float expandedTranslation = 0f;
child.setTranslationX(mExpanded ? expandedTranslation : collapsedTranslation);
child.setAlpha(mExpanded ? 1f : 0f);
LayoutParams params = (LayoutParams) child.getLayoutParams();
params.mCollapseDir.setFloatValues(expandedTranslation, collapsedTranslation);
params.mExpandDir.setFloatValues(collapsedTranslation, expandedTranslation);
params.setAnimationsTarget(child);
nextX = expandLeft ?
childX - mButtonSpacing :
childX + child.getMeasuredWidth() + mButtonSpacing;
}
break;
}
}
#Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(super.generateDefaultLayoutParams());
}
#Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(super.generateLayoutParams(attrs));
}
#Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(super.generateLayoutParams(p));
}
#Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return super.checkLayoutParams(p);
}
private static Interpolator sExpandInterpolator = new OvershootInterpolator();
private static Interpolator sCollapseInterpolator = new DecelerateInterpolator(3f);
private static Interpolator sAlphaExpandInterpolator = new DecelerateInterpolator();
private class LayoutParams extends ViewGroup.LayoutParams {
private ObjectAnimator mExpandDir = new ObjectAnimator();
private ObjectAnimator mExpandAlpha = new ObjectAnimator();
private ObjectAnimator mCollapseDir = new ObjectAnimator();
private ObjectAnimator mCollapseAlpha = new ObjectAnimator();
private boolean animationsSetToPlay;
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
mExpandDir.setInterpolator(sExpandInterpolator);
mExpandAlpha.setInterpolator(sAlphaExpandInterpolator);
mCollapseDir.setInterpolator(sCollapseInterpolator);
mCollapseAlpha.setInterpolator(sCollapseInterpolator);
mCollapseAlpha.setProperty(View.ALPHA);
mCollapseAlpha.setFloatValues(1f, 0f);
mExpandAlpha.setProperty(View.ALPHA);
mExpandAlpha.setFloatValues(0f, 1f);
switch (mExpandDirection) {
case EXPAND_UP:
case EXPAND_DOWN:
mCollapseDir.setProperty(View.TRANSLATION_Y);
mExpandDir.setProperty(View.TRANSLATION_Y);
break;
case EXPAND_LEFT:
case EXPAND_RIGHT:
mCollapseDir.setProperty(View.TRANSLATION_X);
mExpandDir.setProperty(View.TRANSLATION_X);
break;
}
}
public void setAnimationsTarget(View view) {
mCollapseAlpha.setTarget(view);
mCollapseDir.setTarget(view);
mExpandAlpha.setTarget(view);
mExpandDir.setTarget(view);
// Now that the animations have targets, set them to be played
if (!animationsSetToPlay) {
mCollapseAnimation.play(mCollapseAlpha);
mCollapseAnimation.play(mCollapseDir);
mExpandAnimation.play(mExpandAlpha);
mExpandAnimation.play(mExpandDir);
animationsSetToPlay = true;
}
}
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
bringChildToFront(mAddButton);
mButtonsCount = getChildCount();
if (mLabelsStyle != 0) {
createLabels();
}
}
private void createLabels() {
Context context = new ContextThemeWrapper(getContext(), mLabelsStyle);
for (int i = 0; i < mButtonsCount; i++) {
FloatingActionButton button = (FloatingActionButton) getChildAt(i);
String title = button.getTitle();
if (button == mAddButton || title == null ||
button.getTag(R.id.fab_label) != null) continue;
TextView label = new TextView(context);
label.setText(button.getTitle());
addView(label);
button.setTag(R.id.fab_label, label);
}
}
public void collapse() {
if (mExpanded) {
mExpanded = false;
mCollapseAnimation.start();
mExpandAnimation.cancel();
if (mListener != null) {
mListener.onMenuCollapsed();
}
}
}
public void toggle() {
if (mExpanded) {
collapse();
} else {
expand();
}
}
public void expand() {
if (!mExpanded) {
mExpanded = true;
mCollapseAnimation.cancel();
mExpandAnimation.start();
if (mListener != null) {
mListener.onMenuExpanded();
}
}
}
public boolean isExpanded() {
return mExpanded;
}
#Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState savedState = new SavedState(superState);
savedState.mExpanded = mExpanded;
return savedState;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
if (state instanceof SavedState) {
SavedState savedState = (SavedState) state;
mExpanded = savedState.mExpanded;
if (mRotatingDrawable != null) {
mRotatingDrawable.setRotation(mExpanded ? EXPANDED_PLUS_ROTATION : COLLAPSED_PLUS_ROTATION);
}
super.onRestoreInstanceState(savedState.getSuperState());
} else {
super.onRestoreInstanceState(state);
}
}
public static class SavedState extends BaseSavedState {
public boolean mExpanded;
public SavedState(Parcelable parcel) {
super(parcel);
}
private SavedState(Parcel in) {
super(in);
mExpanded = in.readInt() == 1;
}
#Override
public void writeToParcel(#NonNull Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(mExpanded ? 1 : 0);
}
public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
#Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
#Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
Please Help.
If I understand correctly, the code causing the problem is the one commented, otherwise this line :
whiteOverlay.setVisibility(View.VISIBLE);
You are trying to access your RelativeLayout (R.id.white_opacity) through your FloatingActionsMenu view :
whiteOverlay = (RelativeLayout)findViewById(R.id.white_opacity);
But R.id.white_opacity is a member of your HomeActivity view.
So it's normal that this line returns a null pointer since it doesn't have any member named like this.
Try do find a way to access your HomeActivity view and then call "findViewById()" on it.
If "context" is indeed this HomeActivity, then pass the argument to the updateBackground() method (or set context as a class member) and try somthing like that :
whiteOverlay = ((Activity)context).findViewById(R.id.white_opacity);
Regards.
In details, I am looking for an example exactly like below image. I got a good example in this link https://github.com/woozzu/IndexableListView. Its works fine as my requirement.But problem when i implementing to my project it is showing error in list view. below is my code plz help me. i am new to this topic. Thank you in advance!
looking for:
here is my code below plz say my mistake..
MainActivity .java
public class MainActivity extends Activity implements SearchView.OnQueryTextListener,SearchView.OnCloseListener {
private ListView listView;
private SearchView search;
EfficientAdapter objectAdapter;
EfficientAdapter2 objectAdapter1;
int textlength=0;
private CheckBox checkStat, checkRoutine, checkTat;
private GestureDetector mGestureDetector;
private ArrayList<CountriesList> elements;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homempleb);
Log.i("scan"," txtScanResult ");
//Arrays.sort(CountriesList.name);
ActionItem nextItem = new ActionItem();
final QuickAction quickAction = new QuickAction(this, QuickAction.VERTICAL);
quickAction.addActionItem(nextItem);
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
#Override
public void onDismiss() {
Toast.makeText(getApplicationContext(), "Dismissed", Toast.LENGTH_SHORT).show();
}
});
search = (SearchView) findViewById(R.id.searchView1);
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
}
});
checkStat = (CheckBox) findViewById(R.id.checkBoxStat);
checkRoutine = (CheckBox) findViewById(R.id.checkBoxRoutine);
checkTat = (CheckBox) findViewById(R.id.checkBoxTat);
checkStat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkStat.setChecked(true);
Toast.makeText(MainActivity.this, "STAT", Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkRoutine.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkRoutine.setChecked(true);
Toast.makeText(MainActivity.this, "ROUTINE", Toast.LENGTH_SHORT).show();
checkStat.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkTat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkTat.setChecked(true);
Toast.makeText(MainActivity.this, "TAT Effeciency", Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkStat.setChecked(false);
}
}
});
listView = (ListView) findViewById(R.id.homelistView);
listView.setTextFilterEnabled(true);
listView.setFastScrollEnabled(true);
objectAdapter = new EfficientAdapter(this, elements );
listView.setAdapter(objectAdapter);
Button refreshButton= (Button)findViewById(R.id.refreshButton);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
objectAdapter1 = new EfficientAdapter2(MainActivity.this);
// objectAdapter = new EfficientAdapter(MainActivity.this);// adapter with new data
listView.setAdapter(objectAdapter1);
Log.i("notifyDataSetChanged", "data updated");
objectAdapter1.notifyDataSetChanged();
}
});
}
#Override
public boolean onClose() {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
EfficientAdapter.java
public class EfficientAdapter extends BaseAdapter implements SectionIndexer {
private AlphabetIndexer alphaIndexer;
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context, ArrayList<CountriesList> elements) {
mInflater = LayoutInflater.from(context);
this.context=context;
}
public int getCount() {
return CountriesList.name.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.homemplebrowview, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.name);
holder.text2 = (TextView) convertView
.findViewById(R.id.mrn);
holder.text3 = (TextView) convertView
.findViewById(R.id.date);
holder.text4 = (TextView) convertView
.findViewById(R.id.age);
holder.text5 = (TextView) convertView
.findViewById(R.id.gender);
holder.text6 = (TextView) convertView
.findViewById(R.id.wardno);
holder.text7 = (TextView) convertView
.findViewById(R.id.roomno);
holder.text8 = (TextView) convertView
.findViewById(R.id.bedno);
holder.btnList = (Button)convertView.findViewById(R.id.listbutton);
// holder.btnList.setOnClickListener(this);
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent next=new Intent(context, SeviceDetails.class);
context.startActivity(next);
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text1.setText(CountriesList.name[position]);
holder.text2.setText(CountriesList.mrn[position]);
holder.text3.setText(CountriesList.actualstart[position]);
holder.text4.setText(CountriesList.age[position]);
holder.text5.setText(CountriesList.gender[position]);
holder.text6.setText(CountriesList.wardNo[position]);
holder.text7.setText(CountriesList.roomNo[position]);
holder.text8.setText(CountriesList.bedNo[position]);
return convertView;
}
static class ViewHolder {
public Button btnList;
public TextView text8;
public TextView text7;
public TextView text6;
public TextView text5;
public TextView text4;
public TextView text1;
public TextView text2;
public TextView text3;
}
#Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
#Override
public int getPositionForSection(int section) {
// If there is no item for current section, previous section will be selected
for (int i = section; i >= 0; i--) {
for (int j = 0; j < getCount(); j++) {
if (i == 0) {
// For numeric section
for (int k = 0; k <= 9; k++) {
// if (StringMatcher.match(String.valueOf(getItem(j).charAt(0)), String.valueOf(k)))
return j;
}
} else {
// if (StringMatcher.match(String.valueOf(getItem(j).charAt(0)), String.valueOf(mSections.charAt(i))))
return j;
}
}
}
return 0;
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
String[] sections = new String[mSections.length()];
for (int i = 0; i < mSections.length(); i++)
sections[i] = String.valueOf(mSections.charAt(i));
return sections;
}
}
IndexableListView.java
public class IndexableListView extends ListView {
private boolean mIsFastScrollEnabled = false;
private IndexScroller mScroller = null;
private GestureDetector mGestureDetector = null;
public IndexableListView(Context context) {
super(context);
}
public IndexableListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public IndexableListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public boolean isFastScrollEnabled() {
return mIsFastScrollEnabled;
}
#Override
public void setFastScrollEnabled(boolean enabled) {
mIsFastScrollEnabled = enabled;
if (mIsFastScrollEnabled) {
if (mScroller == null)
mScroller = new IndexScroller(getContext(), this);
} else {
if (mScroller != null) {
mScroller.hide();
mScroller = null;
}
}
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
// Overlay index bar
if (mScroller != null)
mScroller.draw(canvas);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
// Intercept ListView's touch event
if (mScroller != null && mScroller.onTouchEvent(ev))
return true;
if (mGestureDetector == null) {
mGestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
// If fling happens, index bar shows
mScroller.show();
return super.onFling(e1, e2, velocityX, velocityY);
}
});
}
mGestureDetector.onTouchEvent(ev);
return super.onTouchEvent(ev);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
#Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
if (mScroller != null)
mScroller.setAdapter(adapter);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mScroller != null)
mScroller.onSizeChanged(w, h, oldw, oldh);
}
}
StringMatcher.java
public class StringMatcher {
public static boolean match(String value, String keyword) {
if (value == null || keyword == null)
return false;
if (keyword.length() > value.length())
return false;
int i = 0, j = 0;
do {
if (isKorean(value.charAt(i)) && isInitialSound(keyword.charAt(j))) {
} else {
if (keyword.charAt(j) == value.charAt(i)) {
i++;
j++;
} else if (j > 0)
break;
else
i++;
}
} while (i < value.length() && j < keyword.length());
return (j == keyword.length())? true : false;
}
private static boolean isKorean(char c) {
return false;
}
private static boolean isInitialSound(char c) {
return false;
}
}
IndexScroller.java
public class IndexScroller {
private static final int STATE_HIDDEN = 0;
private static final int STATE_SHOWING = 1;
private static final int STATE_SHOWN = 2;
private static final int STATE_HIDING = 3;
public IndexScroller(Context context, ListView lv) {
mDensity = context.getResources().getDisplayMetrics().density;
mScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
mListView = lv;
setAdapter(mListView.getAdapter());
mIndexbarWidth = 20 * mDensity;
mIndexbarMargin = 10 * mDensity;
mPreviewPadding = 5 * mDensity;
}
public void draw(Canvas canvas) {
if (mState == STATE_HIDDEN)
return;
// mAlphaRate determines the rate of opacity
Paint indexbarPaint = new Paint();
indexbarPaint.setColor(Color.BLACK);
indexbarPaint.setAlpha((int) (64 * mAlphaRate));
indexbarPaint.setAntiAlias(true);
canvas.drawRoundRect(mIndexbarRect, 5 * mDensity, 5 * mDensity, indexbarPaint);
if (mSections != null && mSections.length > 0) {
// Preview is shown when mCurrentSection is set
if (mCurrentSection >= 0) {
Paint previewPaint = new Paint();
previewPaint.setColor(Color.BLACK);
previewPaint.setAlpha(96);
previewPaint.setAntiAlias(true);
previewPaint.setShadowLayer(3, 0, 0, Color.argb(64, 0, 0, 0));
Paint previewTextPaint = new Paint();
previewTextPaint.setColor(Color.WHITE);
previewTextPaint.setAntiAlias(true);
previewTextPaint.setTextSize(50 * mScaledDensity);
float previewTextWidth = previewTextPaint.measureText(mSections[mCurrentSection]);
float previewSize = 2 * mPreviewPadding + previewTextPaint.descent() - previewTextPaint.ascent();
RectF previewRect = new RectF((mListViewWidth - previewSize) / 2
, (mListViewHeight - previewSize) / 2
, (mListViewWidth - previewSize) / 2 + previewSize
, (mListViewHeight - previewSize) / 2 + previewSize);
canvas.drawRoundRect(previewRect, 5 * mDensity, 5 * mDensity, previewPaint);
canvas.drawText(mSections[mCurrentSection], previewRect.left + (previewSize - previewTextWidth) / 2 - 1
, previewRect.top + mPreviewPadding - previewTextPaint.ascent() + 1, previewTextPaint);
}
Paint indexPaint = new Paint();
indexPaint.setColor(Color.WHITE);
indexPaint.setAlpha((int) (255 * mAlphaRate));
indexPaint.setAntiAlias(true);
indexPaint.setTextSize(12 * mScaledDensity);
float sectionHeight = (mIndexbarRect.height() - 2 * mIndexbarMargin) / mSections.length;
float paddingTop = (sectionHeight - (indexPaint.descent() - indexPaint.ascent())) / 2;
for (int i = 0; i < mSections.length; i++) {
float paddingLeft = (mIndexbarWidth - indexPaint.measureText(mSections[i])) / 2;
canvas.drawText(mSections[i], mIndexbarRect.left + paddingLeft
, mIndexbarRect.top + mIndexbarMargin + sectionHeight * i + paddingTop - indexPaint.ascent(), indexPaint);
}
}
}
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
// If down event occurs inside index bar region, start indexing
if (mState != STATE_HIDDEN && contains(ev.getX(), ev.getY())) {
setState(STATE_SHOWN);
// It demonstrates that the motion event started from index bar
mIsIndexing = true;
// Determine which section the point is in, and move the list to that section
mCurrentSection = getSectionByPoint(ev.getY());
mListView.setSelection(mIndexer.getPositionForSection(mCurrentSection));
return true;
}
break;
case MotionEvent.ACTION_MOVE:
if (mIsIndexing) {
// If this event moves inside index bar
if (contains(ev.getX(), ev.getY())) {
// Determine which section the point is in, and move the list to that section
mCurrentSection = getSectionByPoint(ev.getY());
mListView.setSelection(mIndexer.getPositionForSection(mCurrentSection));
}
return true;
}
break;
case MotionEvent.ACTION_UP:
if (mIsIndexing) {
mIsIndexing = false;
mCurrentSection = -1;
}
if (mState == STATE_SHOWN)
setState(STATE_HIDING);
break;
}
return false;
}
public void onSizeChanged(int w, int h, int oldw, int oldh) {
mListViewWidth = w;
mListViewHeight = h;
mIndexbarRect = new RectF(w - mIndexbarMargin - mIndexbarWidth
, mIndexbarMargin
, w - mIndexbarMargin
, h - mIndexbarMargin);
}
public void show() {
if (mState == STATE_HIDDEN)
setState(STATE_SHOWING);
else if (mState == STATE_HIDING)
setState(STATE_HIDING);
}
public void hide() {
if (mState == STATE_SHOWN)
setState(STATE_HIDING);
}
public void setAdapter(Adapter adapter) {
if (adapter instanceof SectionIndexer) {
mIndexer = (SectionIndexer) adapter;
mSections = (String[]) mIndexer.getSections();
}
}
private void setState(int state) {
if (state < STATE_HIDDEN || state > STATE_HIDING)
return;
mState = state;
switch (mState) {
case STATE_HIDDEN:
// Cancel any fade effect
mHandler.removeMessages(0);
break;
case STATE_SHOWING:
// Start to fade in
mAlphaRate = 0;
fade(0);
break;
case STATE_SHOWN:
// Cancel any fade effect
mHandler.removeMessages(0);
break;
case STATE_HIDING:
// Start to fade out after three seconds
mAlphaRate = 1;
fade(3000);
break;
}
}
private boolean contains(float x, float y) {
// Determine if the point is in index bar region, which includes the right margin of the bar
return (x >= mIndexbarRect.left && y >= mIndexbarRect.top && y <= mIndexbarRect.top + mIndexbarRect.height());
}
private int getSectionByPoint(float y) {
if (mSections == null || mSections.length == 0)
return 0;
if (y < mIndexbarRect.top + mIndexbarMargin)
return 0;
if (y >= mIndexbarRect.top + mIndexbarRect.height() - mIndexbarMargin)
return mSections.length - 1;
return (int) ((y - mIndexbarRect.top - mIndexbarMargin) / ((mIndexbarRect.height() - 2 * mIndexbarMargin) / mSections.length));
}
private void fade(long delay) {
mHandler.removeMessages(0);
mHandler.sendEmptyMessageAtTime(0, SystemClock.uptimeMillis() + delay);
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (mState) {
case STATE_SHOWING:
// Fade in effect
mAlphaRate += (1 - mAlphaRate) * 0.2;
if (mAlphaRate > 0.9) {
mAlphaRate = 1;
setState(STATE_SHOWN);
}
mListView.invalidate();
fade(10);
break;
case STATE_SHOWN:
// If no action, hide automatically
setState(STATE_HIDING);
break;
case STATE_HIDING:
// Fade out effect
mAlphaRate -= mAlphaRate * 0.2;
if (mAlphaRate < 0.1) {
mAlphaRate = 0;
setState(STATE_HIDDEN);
}
mListView.invalidate();
fade(10);
break;
}
}
};
}
if i add this it works code in mainactivity
listView = (ListView) findViewById(R.id.homelistView);
your are using a custom ListView class, com.woozzu.android.widget.IndexableListView
You have to replace your "ListView " in layout file to a "com.woozzu.android.widget.IndexableListView"
Change your Layout to:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:background="#ff3344"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#ffffff"
android:layout_alignTop="#+id/scrollView1"
android:layout_toRightOf="#+id/scrollView1" >
<com.woozzu.android.widget.IndexableListView
android:id="#+id/homelistView"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</com.woozzu.android.widget.IndexableListView>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
The solution Suggested by #Anis is the only working solution I found. In addition to that, If you want Click listeners to components on your List View Items, you have to update the Code as mentioned here, https://github.com/denley/IndexableListView/commit/18210a54487ba079bb332fafec709e2de26883db
I am using view pager indicator and i have sucessfully implemented it but My problem is that my swipe is very slow.Any help regarding this will be appreciated.
My indicator activity:
public class ViewPagerIndicatorActivity extends FragmentActivity {
static PagerAdapter mPagerAdapter;
static ViewPager mViewPager;
static ViewPagerIndicator mIndicator;
static int position,position1;
static String PositionTitle;
static String addposition;
ProgressDialog dialog;
public Context _context=this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create our custom adapter to supply pages to the viewpager.
try{
mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setAdapter(mPagerAdapter);
// Start at a custom position
RelativeLayout firsthead=(RelativeLayout)findViewById(R.id.firsthead);
firsthead.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent ii=new Intent(getApplicationContext(),WebviewNew.class);
startActivity(ii);
}
});
mViewPager.setCurrentItem(0);
mIndicator = (ViewPagerIndicator)findViewById(R.id.indicator);
mViewPager.setOnPageChangeListener(mIndicator);
}catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
mViewPager.setAdapter(null);
super.onDestroy();
}
class OnIndicatorClickListener implements ViewPagerIndicator.OnClickListener{
#Override
public void onCurrentClicked(View v) {
Toast.makeText(ViewPagerIndicatorActivity.this, "Hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onNextClicked(View v) {
mViewPager.setCurrentItem(Math.min(mPagerAdapter.getCount() - 1, mIndicator.getCurrentPosition() + 1));
}
#Override
public void onPreviousClicked(View v) {
mViewPager.setCurrentItem(Math.max(0, mIndicator.getCurrentPosition() - 1));
}
}
class PagerAdapter extends FragmentPagerAdapter implements ViewPagerIndicator.PageInfoProvider{
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
Fragment f = new Fragment();
if(pos==0)
{
f=LayoutOne.newInstance(_context);
}
if(pos==1)
{
f=LayoutTwo.newInstance(_context);
}
if(pos==2)
{
f=Layoutthree.newInstance(_context);
}
if(pos==3)
{
f=Layoutfour.newInstance(_context);
}
return f;
}
#Override
public int getCount() {
return list2.length;
}
#Override
public String getTitle(int pos){
PositionTitle=list2[pos];
return PositionTitle;
}
}
public static class ItemFragment extends ListFragment{
String[] l1;
static ItemFragment newInstance1(String[] date) {
ItemFragment f = new ItemFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putStringArray("date", date);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
this.l1=list2;
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.date_fragment, container, false);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
public static final String[] list2 = new String[]{"Catagories","Latest","Most Downloaded","Top Rated"};
private class StartTaskP extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(ViewPagerIndicatorActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String hello = null;
try
{} catch (Exception e)
{
e.printStackTrace();
}
return hello;
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
try{
mIndicator.init(0, mPagerAdapter.getCount(), mPagerAdapter);
Resources res = getResources();
System.out.println("test11");
Drawable prev = res.getDrawable(R.drawable.indicator_prev_arrow);
Drawable next = res.getDrawable(R.drawable.indicator_next_arrow);
mIndicator.setFocusedTextColor(new int[]{78, 103, 0});
mIndicator.setUnfocusedTextColor(new int[]{255,255,255});
//mIndicator.setFocusedTextColor(R.drawable.navigationtextcurrent);
// Set images for previous and next arrows.
mIndicator.setArrows(prev, next);
mIndicator.setOnClickListener(new OnIndicatorClickListener());
}
catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
dialog.dismiss();
}
}
and my ViewPagerIndicator:
public class ViewPagerIndicator extends RelativeLayout implements OnPageChangeListener {
private static final int PADDING = 10;
int i=0;
TextView mPrevious;
TextView mCurrent;
TextView mNext;
static int mCurItem;
int mRestoreCurItem = -1;
Intent ii= new Intent();
Context mContext;
static int PresentPosition1;
static String textCarrier;
LinearLayout mPreviousGroup;
LinearLayout mNextGroup;
int mArrowPadding;
int mSize;
ImageView mCurrentIndicator;
ImageView mPrevArrow;
ImageView mNextArrow;
static PageInfoProvider mPageInfoProvider;
int[] mFocusedTextColor;
int[] mUnfocusedTextColor;
OnClickListener mOnClickHandler;
public interface PageInfoProvider{
String getTitle(int pos);
}
public interface OnClickListener{
void onNextClicked(View v);
void onPreviousClicked(View v);
void onCurrentClicked(View v);
}
public void setOnClickListener(OnClickListener handler){
this.mOnClickHandler = handler;
mPreviousGroup.setOnClickListener(new OnPreviousClickedListener());
mCurrent.setOnClickListener(new OnCurrentClickedListener());
mNextGroup.setOnClickListener(new OnNextClickedListener());
}
public int getCurrentPosition(){
return mCurItem;
}
public void setPageInfoProvider(PageInfoProvider pageInfoProvider){
this.mPageInfoProvider = pageInfoProvider;
}
public void setFocusedTextColor(int[] col){
System.arraycopy(col, 0, mFocusedTextColor, 0, 3);
updateColor(0);
}
public void setUnfocusedTextColor(int[] col){
System.arraycopy(col, 0, mUnfocusedTextColor, 0, 3);
mNext.setTextColor(Color.argb(160, col[0], col[1], col[2]));
mPrevious.setTextColor(Color.argb(160, col[0], col[1], col[2]));
updateColor(0);
}
#Override
protected Parcelable onSaveInstanceState() {
Parcelable state = super.onSaveInstanceState();
Bundle b = new Bundle();
b.putInt("current", this.mCurItem);
b.putParcelable("viewstate", state);
return b;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(((Bundle)state).getParcelable("viewstate"));
mCurItem = ((Bundle)state).getInt("current", mCurItem);
this.setText(mCurItem - 1);
this.updateArrows(mCurItem);
this.invalidate();
}
/**
* Initialization
*
* #param startPos The initially selected element in the ViewPager
* #param size Total amount of elements in the ViewPager
* #param pageInfoProvider Interface that returns page titles
*/
public void init(int startPos, int size, PageInfoProvider pageInfoProvider){
setPageInfoProvider(pageInfoProvider);
this.mSize = size;
setText(startPos - 1);
mCurItem = startPos;
}
public ViewPagerIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
addContent();
}
public ViewPagerIndicator(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
addContent();
}
public ViewPagerIndicator(Context context) {
super(context);
addContent();
}
/**
* Add drawables for arrows
*
* #param prev Left pointing arrow
* #param next Right pointing arrow
*/
public void setArrows(Drawable prev, Drawable next){
this.mPrevArrow = new ImageView(getContext());
//this.mPrevArrow.setImageDrawable(prev);
this.mPrevArrow.setVisibility(View.INVISIBLE);
this.mNextArrow = new ImageView(getContext());
//this.mNextArrow.setImageDrawable(next);
LinearLayout.LayoutParams arrowLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//arrowLayoutParams.gravity = Gravity.CENTER;
mPreviousGroup.removeAllViews();
mPreviousGroup.addView(mPrevArrow, arrowLayoutParams);
mPreviousGroup.addView(mPrevious, arrowLayoutParams);
mPrevious.setPadding(PADDING, 0, 0, 0);
mNext.setPadding(0, 0, PADDING, 0);
mArrowPadding = PADDING + prev.getIntrinsicWidth();
mNextGroup.addView(mNextArrow, arrowLayoutParams);
updateArrows(mCurItem);
}
/**
* Create all views, build the layout
*/
private void addContent(){
mFocusedTextColor = new int[]{244, 240, 211};
mUnfocusedTextColor = new int[]{160,131,21};
// Text views
// set font
mPrevious = new TextView(getContext());
mCurrent = new TextView(getContext());
mNext = new TextView(getContext());
RelativeLayout.LayoutParams previousParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
previousParams.addRule(RelativeLayout.ALIGN_LEFT);
previousParams.leftMargin=-28;
previousParams.topMargin=10;
RelativeLayout.LayoutParams currentParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
currentParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
currentParams.topMargin=10;
RelativeLayout.LayoutParams nextParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
nextParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
nextParams.rightMargin=-40;
nextParams.topMargin=10;
// Groups holding text and arrows
mPreviousGroup = new LinearLayout(getContext());
mPreviousGroup.setOrientation(LinearLayout.HORIZONTAL);
mNextGroup = new LinearLayout(getContext());
mNextGroup.setOrientation(LinearLayout.HORIZONTAL);
mPreviousGroup.addView(mPrevious, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mNextGroup.addView(mNext, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addView(mPreviousGroup, previousParams);
addView(mCurrent, currentParams);
addView(mNextGroup, nextParams);
mPrevious.setSingleLine();
mCurrent.setSingleLine();
mNext.setSingleLine();
mPrevious.setText("previous");
mCurrent.setText("current");
mNext.setText("next");
try{
Typeface tf=Typeface.createFromAsset(getContext().getAssets(), "fonts/trebuc.otf");
mPrevious.setTypeface(tf);
mCurrent.setTypeface(tf);
mNext.setTypeface(tf);
}catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
mPrevious.setClickable(false);
mNext.setClickable(false);
mCurrent.setClickable(true);
mPreviousGroup.setClickable(true);
mNextGroup.setClickable(true);
// Set colors
mNext.setTextColor(Color.argb(255, mUnfocusedTextColor[0], mUnfocusedTextColor[1], mUnfocusedTextColor[2]));
mPrevious.setTextColor(Color.argb(255, mUnfocusedTextColor[0], mUnfocusedTextColor[1], mUnfocusedTextColor[2]));
updateColor(0);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
positionOffsetPixels = adjustOffset(positionOffsetPixels);
position = updatePosition(position, positionOffsetPixels);
setText(position - 1);
/*System.out.println("PageScrolled:"+(position-1));
System.out.println("PageScrollednew:"+PresentPosition);
*/updateColor(positionOffsetPixels-1);
updateArrows(position);
//updatePositions(positionOffsetPixels);
updatePositions(position);
mCurItem = position;
Bundle ii=new Bundle();
//ii.putExtra("mcurItem", mCurItem);
ii.putInt("key", mCurItem);
}
void updatePositions(int positionOffsetPixels){
int textWidth = mCurrent.getWidth() - mCurrent.getPaddingLeft() - mCurrent.getPaddingRight();
int maxOffset = this.getWidth() / 2 - textWidth / 2 - mArrowPadding;
if(positionOffsetPixels > 0){
maxOffset %= this.getPaddingLeft();
int offset = Math.min(positionOffsetPixels, maxOffset);
mCurrent.setPadding(0, 0, 2 * offset, 0);
}else{
maxOffset -= this.getPaddingRight();
int offset = Math.max(positionOffsetPixels, -maxOffset);
mCurrent.setPadding(-2 * offset, 0, 0, 0);
}
}
void updateArrows(int position){
if(mPrevArrow != null){
mPrevArrow.setVisibility(position == 0 ? View.INVISIBLE : View.VISIBLE);
mNextArrow.setVisibility(position == mSize - 1 ? View.INVISIBLE : View.VISIBLE);
}
}
int updatePosition(int givenPosition, int offset){
int pos;
if(offset < 0){
pos = givenPosition + 1;
}else{
pos = givenPosition;
}
return pos;
}
/**
* Fade "currently showing" color depending on it's position
*
* #param offset
*/
void updateColor(int offset){
offset = Math.abs(offset);
// Initial condition: offset is always 0, this.getWidth is also 0! 0/0 = NaN
int width = this.getWidth();
float fraction = width == 0 ? 0 : offset / ((float)width / 4.0f);
fraction = Math.min(1, fraction);
int r = (int)(mUnfocusedTextColor[0] * fraction + mFocusedTextColor[0] * (1 - fraction));
int g = (int)(mUnfocusedTextColor[1] * fraction + mFocusedTextColor[1] * (1 - fraction));
int b = (int)(mUnfocusedTextColor[2] * fraction + mFocusedTextColor[2] * (1 - fraction));
mCurrent.setTextColor(Color.argb(255, r, g, b));
}
/**
* Update text depending on it's position
*
* #param prevPos
*/
void setText(int prevPos){
PresentPosition1=prevPos;
if(prevPos < 0){
mPrevious.setText("");
}else{
mPrevious.setText(mPageInfoProvider.getTitle(prevPos));
}
mCurrent.setText(mPageInfoProvider.getTitle(prevPos + 1));
PresentPosition1=prevPos;
//System.out.println("present text"+mPageInfoProvider.getTitle(prevPos + 1));
if(prevPos + 2 == this.mSize){
mNext.setText("");
}else{
mNext.setText(mPageInfoProvider.getTitle(prevPos + 2));
}
}
// Original:
// 244, 245, 0, 1, 2
// New:
// -2, -1, 0, 1, 2
int adjustOffset(int positionOffsetPixels){
// Move offset half width
positionOffsetPixels += this.getWidth() / 2;
// Clamp to width
positionOffsetPixels %= this.getWidth();
// Center around zero
positionOffsetPixels -= this.getWidth() / 2;
return positionOffsetPixels;
}
#Override
public void onPageSelected(int position) {
// Reset padding when the page is finally selected (May not be necessary)
mCurrent.setPadding(0, 0, 0, 0);
}
class OnPreviousClickedListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
if(mOnClickHandler != null){
mOnClickHandler.onPreviousClicked(ViewPagerIndicator.this);
}
}
}
class OnCurrentClickedListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
if(mOnClickHandler != null){
mOnClickHandler.onCurrentClicked(ViewPagerIndicator.this);
}
}
}
class OnNextClickedListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
if(mOnClickHandler != null){
mOnClickHandler.onNextClicked(ViewPagerIndicator.this);
}
}
}
}