I'm trying to recreate the game 2048.
When I'm clicking on the button "New Game", I start a new intent with the PlayActivity. The button starts the activity, but when the view shows, the grid layout is not visible...
The view is a textview and then the GridLayout (which is custom, because I have to populate it with custom tiles)...
The code:
PlayActivity.java
public class PlayActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
}
}
activity_play.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent">
<TextView
android:id="#+id/txtScore"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/score"
android:background="#color/dark_grey"/>
<com.charlotteerpels.oefening1.Board
android:id="#+id/board"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.charlotteerpels.oefening1.Board>
</LinearLayout>
Board.java
public class Board extends GridLayout {
Card[][] cardBoard;
private int cardHeight;
private int cardWidth;
public void initBoard(Context context) {
this.setColumnCount(4);
this.setRowCount(4);
this.cardBoard = new Card[4][4];
calculateCardSpecs(context);
populateBoard();
}
private void calculateCardSpecs(Context context) {
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
this.cardWidth = width/4;
this.cardHeight = this.cardWidth;
}
private void populateBoard() {
int tilesWithNumber = 0;
Random random = new Random();
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
Card card = new Card(getContext());
if(random.nextInt(2) == 0) {
if(tilesWithNumber<2) {
card.setTextVisible();
tilesWithNumber++;
}
}
cardBoard[i][j] = card;
}
}
addCardsToView();
}
private void addCardsToView() {
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
Card card = cardBoard[i][j];
addView(card, cardWidth, cardHeight);
}
}
}
public Board(Context context) {
super(context);
initBoard(context);
}
public Board(Context context, AttributeSet attrs) {
super(context, attrs);
initBoard(context);
}
public Board(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initBoard(context);
}
}
Card.java
public class Card extends FrameLayout {
Random randomGenerator;
private int number;
Resources res = getResources();
private TextView lblNumber;
public void setNumber(int number) {
this.number = number;
}
public int getNumber() {
return this.number;
}
private void initCard(Context context) {
lblNumber = new TextView(context);
lblNumber.setBackgroundColor(res.getColor(R.color.light_brown));
randomGenerator = new Random();
int r = randomGenerator.nextInt(2);
if(r == 0)
this.number = 2;
else
this.number = 4;
}
public void setTextVisible() {
lblNumber.setText(String.valueOf(number));
}
public Card(Context context) {
super(context);
initCard(context);
}
public Card(Context context, AttributeSet attrs) {
super(context, attrs);
initCard(context);
}
public Card(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initCard(context);
}
}
Does anyone have an idea of what I'm doing wrong?
Thanks in advance!
EDIT: RobVoisey found the answer, I created the TextView lblNumber in the class Card, but I didn't added it to the Card...
So in the class Card in the method initCard, I added after the if/else the textView lblNumber to the Card layout:
private void initCard(Context context) {
lblNumber = new TextView(context);
lblNumber.setBackgroundColor(res.getColor(R.color.light_brown));
randomGenerator = new Random();
int r = randomGenerator.nextInt(2);
if(r == 0)
this.number = 2;
else
this.number = 4;
addView(lblNumber);
}
Related
I'm using androidx.emoji.widget.EmojiEditText. I want to force user to enter only emojis here. And limit him to max 3 emojis. How can I do something like this? I tried to use external emoji keyboard that cancels the soft keyboard and shows up but didn't work properly.
<androidx.emoji.widget.EmojiEditText
android:id="#+id/etEmoji"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_margin="10dp"
android:hint="Enter Emoji"
android:inputType="textShortMessage"
android:background="#android:color/transparent"/>
Below class will only allow Emojis and symbols.
public class CustomEditText extends EditText {
public CustomEditText(Context context) {
super(context);
init();
}
public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setFilters(new InputFilter[]{new EmojiIncludeFilter()});
}
private class EmojiIncludeFilter implements InputFilter {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
int type = Character.getType(source.charAt(i));
if (type != Character.SURROGATE && type != Character.OTHER_SYMBOL) {
// Other then emoji value will be blank
return "";
}
}
return null;
}
}
}
My custom view (which is a button) seems to be reinitialized when I change tab and come back to the one where my custom view is.
Before changing tab (when I launch the app):
After changing:
Find below the code of my custom view (without custom public methods):
public class ButtonView extends RelativeLayout {
private RelativeLayout mRelativeContainer;
private TextView mTextViewButton;
private ImageView mImageViewArrow;
private DiagonalLayout mDiagonalLayout;
private RelativeLayout mRelativeLayoutDiagonalColor;
private int mDirection;
private String mText;
private float mTextSize;
private int mTextColor;
private int mButtonColor;
private int mObliqueColor;
public ButtonView(Context context) {
super(context);
customLabel(context, null);
init(context);
}
public ButtonView(Context context, AttributeSet attrs) {
super(context, attrs);
customLabel(context, attrs);
init(context);
}
public ButtonView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
customLabel(context, attrs);
init(context);
}
private void init(Context context) {
switch (mDirection) {
case DIRECTION_RIGHT:
inflate(context, R.layout.button_view_right, this);
break;
case DIRECTION_LEFT:
inflate(context, R.layout.button_view_left, this);
break;
}
mRelativeContainer = findViewById(R.id.container);
mTextViewButton = findViewById(R.id.text);
mImageViewArrow = findViewById(R.id.arrow);
mDiagonalLayout = findViewById(R.id.diagonal);
mRelativeLayoutDiagonalColor = findViewById(R.id.diagonal_color);
mRelativeContainer.setBackgroundResource(R.drawable.bg_button_view);
setText(mText);
setTextSize(mTextSize);
setTextColor(mTextColor);
setButtonColor(mButtonColor);
setObliqueColor(mObliqueColor);
}
private void customLabel(Context context, AttributeSet attrs) {
TypedArray typedArray = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.ButtonView,
0, 0);
try {
mDirection = typedArray.getInt(R.styleable.ButtonView_direction, DIRECTION_RIGHT);
mText = typedArray.getString(R.styleable.ButtonView_text);
mTextSize = typedArray.getDimensionPixelSize(R.styleable.ButtonView_text_size, 52);
mTextColor = typedArray.getColor(R.styleable.ButtonView_text_color, getResources().getColor(android.R.color.white));
mButtonColor = typedArray.getColor(R.styleable.ButtonView_button_color, getResources().getColor(R.color.blue));
mObliqueColor = typedArray.getColor(R.styleable.ButtonView_oblique_color, getResources().getColor(R.color.dark_blue));
} finally {
typedArray.recycle();
}
}
private int getPercent(int i, int percent) {
return i * percent / 100;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int marginTopBottom = getPercent(mTextViewButton.getMeasuredHeight(), 50);
int marginStartEnd = getPercent(mTextViewButton.getMeasuredHeight(), 70);
LinearLayout.LayoutParams textViewButtonParams = (LinearLayout.LayoutParams) mTextViewButton.getLayoutParams();
textViewButtonParams.setMargins(
marginStartEnd, marginTopBottom,
marginStartEnd, marginTopBottom);
mTextViewButton.setLayoutParams(textViewButtonParams);
/***************************************************************/
((LinearLayout.LayoutParams) mImageViewArrow.getLayoutParams()).width = getPercent(mTextViewButton.getMeasuredHeight(), 60);
((LinearLayout.LayoutParams) mImageViewArrow.getLayoutParams()).height = getPercent(mTextViewButton.getMeasuredHeight(), 60);
switch (mDirection) {
case DIRECTION_RIGHT:
((LinearLayout.LayoutParams) mImageViewArrow.getLayoutParams()).setMargins(0, 0, marginStartEnd, 0);
mDiagonalLayout.getLayoutParams().width = getMeasuredWidth();
mDiagonalLayout.getLayoutParams().height = getPercent(mTextViewButton.getMeasuredHeight(), 35);
((RelativeLayout.LayoutParams) mDiagonalLayout.getLayoutParams()).setMargins(
0,
marginTopBottom * 2 + mTextViewButton.getMeasuredHeight() - mDiagonalLayout.getLayoutParams().height,
0,
0);
break;
case DIRECTION_LEFT:
((LinearLayout.LayoutParams) mImageViewArrow.getLayoutParams()).setMargins(marginStartEnd, 0, 0, 0);
mDiagonalLayout.getLayoutParams().width = getPercent(mTextViewButton.getMeasuredHeight(), 60) * 4;
mDiagonalLayout.getLayoutParams().height = getPercent(mTextViewButton.getMeasuredHeight(), 35);
((RelativeLayout.LayoutParams) mDiagonalLayout.getLayoutParams()).setMargins(
0,
marginTopBottom * 2 + mTextViewButton.getMeasuredHeight() - mDiagonalLayout.getLayoutParams().height,
0,
0);
break;
}
}
}
I have no idea of what happens and I didn't find any proper answers so far.
I am using PagerSlidingTabStrip in an Android project.
When I swipe through the tabs, it is working correctly.
However, when I click on a tab, the tab does not change.
Here is the activity XML:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<au.edu.me.meandroidapplication.view.thirdparty.PagerSlidingTabStrip
android:id="#+id/progress_pager_tab_strip"
android:layout_width="match_parent"
android:layout_height="48dip"
app:pstsShouldExpand="true"
app:pstsIndicatorColor="#color/meTabIndicator"
app:pstsDividerColor="#color/meTabSeparator"
android:background="#color/meTabBackground" />
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/progressViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="au.edu.me.meandroidapplication.view.activity.MyProgressActivity" />
</RelativeLayout>
Here is my code in onCreate():
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_progress);
this.viewPager = (ViewPager)this.findViewById(R.id.progressViewPager);
this.pagerAdapter = new MyProgressFragmentPagerAdapter(this.getSupportFragmentManager());
this.viewPager.setAdapter(this.pagerAdapter);
PagerSlidingTabStrip pagerTabStrip = (PagerSlidingTabStrip)this.findViewById(R.id.progress_pager_tab_strip);
pagerTabStrip.setViewPager(this.viewPager);
pagerTabStrip.setTextColorResource(R.color.meTabText);
}
Any advice on how to click the buttons to also change the tabs would be greatly appreciated!
Edit: yes the importing is from this project and not any other one. here is the code for PagerSlidingTabStrip
package au.edu.me.meandroidapplication.view.thirdparty;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.Locale;
import au.edu.me.meandroidapplication.R;
public class PagerSlidingTabStrip extends HorizontalScrollView {
public interface IconTabProvider {
public int getPageIconResId(int position);
}
// #formatter:off
private static final int[] ATTRS = new int[] {
android.R.attr.textSize,
android.R.attr.textColor
};
// #formatter:on
private LinearLayout.LayoutParams defaultTabLayoutParams;
private LinearLayout.LayoutParams expandedTabLayoutParams;
private final PageListener pageListener = new PageListener();
public OnPageChangeListener delegatePageListener;
private LinearLayout tabsContainer;
private ViewPager pager;
private int tabCount;
private int currentPosition = 0;
private float currentPositionOffset = 0f;
private Paint rectPaint;
private Paint dividerPaint;
private int indicatorColor = 0xFF666666;
private int underlineColor = 0x1A000000;
private int dividerColor = 0x1A000000;
private boolean shouldExpand = false;
private boolean textAllCaps = true;
private int scrollOffset = 52;
private int indicatorHeight = 8;
private int underlineHeight = 2;
private int dividerPadding = 12;
private int tabPadding = 24;
private int dividerWidth = 1;
private int tabTextSize = 12;
private int tabTextColor = 0xFF666666;
private Typeface tabTypeface = null;
private int tabTypefaceStyle = Typeface.BOLD;
private int lastScrollX = 0;
private int tabBackgroundResId = -1; // ### REMOVED
private Locale locale;
public PagerSlidingTabStrip(Context context) {
this(context, null);
}
public PagerSlidingTabStrip(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public PagerSlidingTabStrip(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFillViewport(true);
setWillNotDraw(false);
tabsContainer = new LinearLayout(context);
tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
addView(tabsContainer);
DisplayMetrics dm = getResources().getDisplayMetrics();
scrollOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm);
indicatorHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm);
underlineHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm);
dividerPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm);
tabPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm);
dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm);
tabTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm);
// get system attrs (android:textSize and android:textColor)
TypedArray a = context.obtainStyledAttributes(attrs, ATTRS);
tabTextSize = a.getDimensionPixelSize(0, tabTextSize);
tabTextColor = a.getColor(1, tabTextColor);
a.recycle();
// get custom attrs
a = context.obtainStyledAttributes(attrs, R.styleable.PagerSlidingTabStrip);
indicatorColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsIndicatorColor, indicatorColor);
underlineColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsUnderlineColor, underlineColor);
dividerColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsDividerColor, dividerColor);
indicatorHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsIndicatorHeight, indicatorHeight);
underlineHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsUnderlineHeight, underlineHeight);
dividerPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsDividerPadding, dividerPadding);
tabPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsTabPaddingLeftRight, tabPadding);
tabBackgroundResId = a.getResourceId(R.styleable.PagerSlidingTabStrip_pstsTabBackground, tabBackgroundResId);
shouldExpand = a.getBoolean(R.styleable.PagerSlidingTabStrip_pstsShouldExpand, shouldExpand);
scrollOffset = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsScrollOffset, scrollOffset);
textAllCaps = a.getBoolean(R.styleable.PagerSlidingTabStrip_pstsTextAllCaps, textAllCaps);
a.recycle();
rectPaint = new Paint();
rectPaint.setAntiAlias(true);
rectPaint.setStyle(Style.FILL);
dividerPaint = new Paint();
dividerPaint.setAntiAlias(true);
dividerPaint.setStrokeWidth(dividerWidth);
defaultTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
expandedTabLayoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f);
if (locale == null) {
locale = getResources().getConfiguration().locale;
}
}
public void setViewPager(ViewPager pager) {
this.pager = pager;
if (pager.getAdapter() == null) {
throw new IllegalStateException("ViewPager does not have adapter instance.");
}
pager.setOnPageChangeListener(pageListener);
notifyDataSetChanged();
}
public void setOnPageChangeListener(OnPageChangeListener listener) {
this.delegatePageListener = listener;
}
public void notifyDataSetChanged() {
tabsContainer.removeAllViews();
tabCount = pager.getAdapter().getCount();
for (int i = 0; i < tabCount; i++) {
if (pager.getAdapter() instanceof IconTabProvider) {
addIconTab(i, ((IconTabProvider) pager.getAdapter()).getPageIconResId(i));
} else {
addTextTab(i, pager.getAdapter().getPageTitle(i).toString());
}
}
updateTabStyles();
getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
currentPosition = pager.getCurrentItem();
scrollToChild(currentPosition, 0);
}
});
}
private void addTextTab(final int position, String title) {
TextView tab = new TextView(getContext());
tab.setText(title);
tab.setGravity(Gravity.CENTER);
tab.setSingleLine();
addTab(position, tab);
}
private void addIconTab(final int position, int resId) {
ImageButton tab = new ImageButton(getContext());
tab.setImageResource(resId);
addTab(position, tab);
}
private void addTab(final int position, View tab) {
tab.setFocusable(true);
tab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pager.setCurrentItem(position);
}
});
tab.setPadding(tabPadding, 0, tabPadding, 0);
tabsContainer.addView(tab, position, shouldExpand ? expandedTabLayoutParams : defaultTabLayoutParams);
}
private void updateTabStyles() {
for (int i = 0; i < tabCount; i++) {
View v = tabsContainer.getChildAt(i);
// v.setBackgroundResource(tabBackgroundResId); // ### removed
if (v instanceof TextView) {
TextView tab = (TextView) v;
tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize);
tab.setTypeface(tabTypeface, tabTypefaceStyle);
tab.setTextColor(tabTextColor);
// setAllCaps() is only available from API 14, so the upper case is made manually if we are on a
// pre-ICS-build
if (textAllCaps) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
tab.setAllCaps(true);
} else {
tab.setText(tab.getText().toString().toUpperCase(locale));
}
}
}
}
}
private void scrollToChild(int position, int offset) {
if (tabCount == 0) {
return;
}
int newScrollX = tabsContainer.getChildAt(position).getLeft() + offset;
if (position > 0 || offset > 0) {
newScrollX -= scrollOffset;
}
if (newScrollX != lastScrollX) {
lastScrollX = newScrollX;
scrollTo(newScrollX, 0);
}
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isInEditMode() || tabCount == 0) {
return;
}
final int height = getHeight();
// draw indicator line
rectPaint.setColor(indicatorColor);
// default: line below current tab
View currentTab = tabsContainer.getChildAt(currentPosition);
float lineLeft = currentTab.getLeft();
float lineRight = currentTab.getRight();
// if there is an offset, start interpolating left and right coordinates between current and next tab
if (currentPositionOffset > 0f && currentPosition < tabCount - 1) {
View nextTab = tabsContainer.getChildAt(currentPosition + 1);
final float nextTabLeft = nextTab.getLeft();
final float nextTabRight = nextTab.getRight();
lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft);
lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight);
}
canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint);
// draw underline
rectPaint.setColor(underlineColor);
canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint);
// draw divider
dividerPaint.setColor(dividerColor);
for (int i = 0; i < tabCount - 1; i++) {
View tab = tabsContainer.getChildAt(i);
canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(), height - dividerPadding, dividerPaint);
}
}
private class PageListener implements OnPageChangeListener {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
currentPosition = position;
currentPositionOffset = positionOffset;
scrollToChild(position, (int) (positionOffset * tabsContainer.getChildAt(position).getWidth()));
invalidate();
if (delegatePageListener != null) {
delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
#Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
scrollToChild(pager.getCurrentItem(), 0);
}
if (delegatePageListener != null) {
delegatePageListener.onPageScrollStateChanged(state);
}
}
#Override
public void onPageSelected(int position) {
if (delegatePageListener != null) {
delegatePageListener.onPageSelected(position);
}
}
}
public void setIndicatorColor(int indicatorColor) {
this.indicatorColor = indicatorColor;
invalidate();
}
public void setIndicatorColorResource(int resId) {
this.indicatorColor = getResources().getColor(resId);
invalidate();
}
public int getIndicatorColor() {
return this.indicatorColor;
}
public void setIndicatorHeight(int indicatorLineHeightPx) {
this.indicatorHeight = indicatorLineHeightPx;
invalidate();
}
public int getIndicatorHeight() {
return indicatorHeight;
}
public void setUnderlineColor(int underlineColor) {
this.underlineColor = underlineColor;
invalidate();
}
public void setUnderlineColorResource(int resId) {
this.underlineColor = getResources().getColor(resId);
invalidate();
}
public int getUnderlineColor() {
return underlineColor;
}
public void setDividerColor(int dividerColor) {
this.dividerColor = dividerColor;
invalidate();
}
public void setDividerColorResource(int resId) {
this.dividerColor = getResources().getColor(resId);
invalidate();
}
public int getDividerColor() {
return dividerColor;
}
public void setUnderlineHeight(int underlineHeightPx) {
this.underlineHeight = underlineHeightPx;
invalidate();
}
public int getUnderlineHeight() {
return underlineHeight;
}
public void setDividerPadding(int dividerPaddingPx) {
this.dividerPadding = dividerPaddingPx;
invalidate();
}
public int getDividerPadding() {
return dividerPadding;
}
public void setScrollOffset(int scrollOffsetPx) {
this.scrollOffset = scrollOffsetPx;
invalidate();
}
public int getScrollOffset() {
return scrollOffset;
}
public void setShouldExpand(boolean shouldExpand) {
this.shouldExpand = shouldExpand;
requestLayout();
}
public boolean getShouldExpand() {
return shouldExpand;
}
public boolean isTextAllCaps() {
return textAllCaps;
}
public void setAllCaps(boolean textAllCaps) {
this.textAllCaps = textAllCaps;
}
public void setTextSize(int textSizePx) {
this.tabTextSize = textSizePx;
updateTabStyles();
}
public int getTextSize() {
return tabTextSize;
}
public void setTextColor(int textColor) {
this.tabTextColor = textColor;
updateTabStyles();
}
public void setTextColorResource(int resId) {
this.tabTextColor = getResources().getColor(resId);
updateTabStyles();
}
public int getTextColor() {
return tabTextColor;
}
public void setTypeface(Typeface typeface, int style) {
this.tabTypeface = typeface;
this.tabTypefaceStyle = style;
updateTabStyles();
}
public void setTabBackground(int resId) {
this.tabBackgroundResId = resId;
}
public int getTabBackground() {
return tabBackgroundResId;
}
public void setTabPaddingLeftRight(int paddingPx) {
this.tabPadding = paddingPx;
updateTabStyles();
}
public int getTabPaddingLeftRight() {
return tabPadding;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
currentPosition = savedState.currentPosition;
requestLayout();
}
#Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState savedState = new SavedState(superState);
savedState.currentPosition = currentPosition;
return savedState;
}
static class SavedState extends BaseSavedState {
int currentPosition;
public SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
currentPosition = in.readInt();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(currentPosition);
}
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
#Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
#Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
I am trying to allow the user of my app to paint (with their finger) over a VideoView object.
I have had little success.
In my current attempt, I have tried to put a SurfaceView over a VideoView though I have reached a number of issues: When I open a navigation drawer, the drawings, appear OVER the navigation drawer interface; and the drawings seem to blink on an actual device ( they flash).
This is just my attempt, I am sure there is a better way of allowing the user to paint.
<VideoView
android:id="#+id/videoplayer"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</VideoView>
<com.example.example.VideoOverlay
android:id="#+id/videooverlay"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
Here is the VideoOverlay Class
public class VideoOverlay extends SurfaceView implements Runnable {
Thread thread = null;
SurfaceHolder surfaceHolder;
volatile boolean running = false;
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Random random;
public void onResumeMySurfaceView(){
running = true;
thread = new Thread(this);
thread.start();
}
public void onPauseMySurfaceView(){
boolean retry = true;
running = false;
while(retry){
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public VideoOverlay(Context context)
{
super(context);
surfaceHolder = getHolder();
random = new Random();
this.setZOrderMediaOverlay(true);
this.setZOrderOnTop(true);
surfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
}
public VideoOverlay(Context context, AttributeSet attrs)
{
super(context, attrs);
surfaceHolder = getHolder();
random = new Random();
this.setZOrderMediaOverlay(true);
this.setZOrderOnTop(true);
surfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
}
public VideoOverlay(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
surfaceHolder = getHolder();
random = new Random();
this.setZOrderMediaOverlay(true);
this.setZOrderOnTop(true);
surfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
}
// Other stuff
#Override
public void run() {
// TODO Auto-generated method stub
while(running){
if(surfaceHolder.getSurface().isValid()){
Canvas canvas = surfaceHolder.lockCanvas();
//... actual drawing on canvas
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
int w = canvas.getWidth();
int h = canvas.getHeight();
int x = random.nextInt(w-1);
int y = random.nextInt(h-1);
int r = random.nextInt(255);
int g = random.nextInt(255);
int b = random.nextInt(255);
paint.setColor(0xff000000 + (r << 16) + (g << 8) + b);
canvas.drawPoint(x, y, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
Any help would be great!
How to create a bounce ScrollView in Android like iPhone?
Add effect bounce to scrollview in android
Step 1: Create new file BounceScrollView in package com.base.view
public class BounceScrollView extends ScrollView
{
private static final int MAX_Y_OVERSCROLL_DISTANCE = 200;
private Context mContext;
private int mMaxYOverscrollDistance;
public BounceScrollView(Context context)
{
super(context);
mContext = context;
initBounceScrollView();
}
public BounceScrollView(Context context, AttributeSet attrs)
{
super(context, attrs);
mContext = context;
initBounceScrollView();
}
public BounceScrollView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
mContext = context;
initBounceScrollView();
}
private void initBounceScrollView()
{
//get the density of the screen and do some maths with it on the max overscroll distance
//variable so that you get similar behaviors no matter what the screen size
final DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
final float density = metrics.density;
mMaxYOverscrollDistance = (int) (density * MAX_Y_OVERSCROLL_DISTANCE);
}
#Override
protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent)
{
//This is where the magic happens, we have replaced the incoming maxOverScrollY with our own custom variable mMaxYOverscrollDistance;
return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, mMaxYOverscrollDistance, isTouchEvent);
}
}
Step 2: At your layout, please change
<ScrollView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
to
<com.base.view.BounceScrollView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
I have improved version of this answer: https://stackoverflow.com/a/13391248/3256989 .
So my version is (example for HorizontalScrollView):
public class HorizontalOverScrollView extends HorizontalScrollView {
private static final int WIDTH_DEVIDER_OVERSCROLL_DISTANCE = 3;
private TimeInterpolator mInterpolator;
private int mMaxOverscrollDistance;
private int mAnimTime;
private long mStartTime;
/**
* Instantiates {#link HorizontalOverScrollView} object.
*/
public HorizontalOverScrollView(final Context context) {
super(context);
init();
}
/**
* Instantiates {#link HorizontalOverScrollView} object.
*/
public HorizontalOverScrollView(final Context context, final AttributeSet attrs) {
super(context, attrs);
init();
}
/**
* Instantiates {#link HorizontalOverScrollView} object.
*/
public HorizontalOverScrollView(final Context context, final AttributeSet attrs, final int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
final int widthPixels = getContext().getResources().getDisplayMetrics().widthPixels;
mMaxOverscrollDistance = widthPixels / WIDTH_DEVIDER_OVERSCROLL_DISTANCE;
mAnimTime = getContext().getResources().getInteger(android.R.integer.config_mediumAnimTime);
mInterpolator = new DecelerateInterpolator();
}
#Override
protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
int overScrollDistance = mMaxOverscrollDistance;
if (isTouchEvent) {
mStartTime = AnimationUtils.currentAnimationTimeMillis();
} else {
final long elapsedTime = AnimationUtils.currentAnimationTimeMillis() - mStartTime;
float interpolation = mInterpolator.getInterpolation((float) elapsedTime / mAnimTime);
interpolation = interpolation > 1 ? 1 : interpolation;
overScrollDistance -= overScrollDistance * interpolation;
overScrollDistance = overScrollDistance < 0 ? 0 : overScrollDistance;
}
return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, overScrollDistance, maxOverScrollY, isTouchEvent);
}
}
It's called overscroll in Android.
See http://developer.android.com/reference/android/widget/OverScroller.html and
(for example) http://developer.android.com/reference/android/widget/ListView.html#setOverscrollFooter(android.graphics.drawable.Drawable)
It's only available from API level 9 onward.
However, Samsung devices do seem to support overscroll natively in Android 2.2
Just use OverScrollDecoratorHelper
ScrollView scrollView = (ScrollView) findViewById(R.id.scroll_view);
OverScrollDecoratorHelper.setUpOverScroll(scrollView);
HorizontalScrollView horizontalScrollView = (HorizontalScrollView) findViewById(R.id.horizontal_scroll_view);
OverScrollDecoratorHelper.setUpOverScroll(horizontalScrollView);
https://github.com/EverythingMe/overscroll-decor