I am currently following this answer. As from this answer, it shows that the pixel/grid will be checked if it has been touched. However, I would like to check a grid as a start point and have controls/button at the mainactivity to move the start point around. For example, if user clicks on move forward button, the start point will move forward, checking the new grid and setting the previous point as white. Now i am getting nullpointerexception upon the checkedCell[column][row] in the moveForward() method
So, here is my code:
public class PixelGridView extends View {
private int numColumns, numRows;
private int cellWidth, cellHeight;
private Paint blackPaint = new Paint();
private boolean[][] cellChecked;
public PixelGridView(Context context)
{
this(context, null);
}
public PixelGridView(Context context, AttributeSet attrs)
{
super(context, attrs);
blackPaint.setStyle(Paint.Style.FILL_AND_STROKE);
}
public void setNumColumns(int numColumns)
{
this.numColumns = numColumns;
calculateDimensions();
}
public int getNumColumns()
{
return numColumns;
}
public void setNumRows(int numRows)
{
this.numRows = numRows;
calculateDimensions();
}
public int getNumRows()
{
return numRows;
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
calculateDimensions();
}
private void calculateDimensions()
{
if (numColumns == 0 || numRows == 0)
return;
cellWidth = getWidth() / numColumns;
cellHeight = getHeight() / numRows;
cellChecked = new boolean[numColumns][numRows];
invalidate();
}
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
if (numColumns == 0 || numRows == 0)
return;
int width = getWidth();
int height = getHeight();
for (int i = 0; i < numColumns; i++)
{
for (int j = 0; j < numRows; j++)
{
if (cellChecked[i][j])
{
canvas.drawRect(i * cellWidth, j * cellHeight, (i + 1) * cellWidth, (j + 1) * cellHeight, blackPaint);
}
}
}
for (int i = 1; i < numColumns; i++)
{
canvas.drawLine(i * cellWidth, 0, i * cellWidth, height, blackPaint);
}
for (int i = 1; i < numRows; i++)
{
canvas.drawLine(0, i * cellHeight, width, i * cellHeight, blackPaint);
}
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
if (event.getAction() != MotionEvent.ACTION_DOWN)
return true;
int column = (int)(event.getX() / cellWidth);
int row = (int)(event.getY() / cellHeight);
cellChecked[column][row] = !cellChecked[column][row];
invalidate();
return true;
}
public void moveForward() {
//set column and row to be checked at [1][1] upon button click on mainactivity
int column = 1;
int row = 1;
cellChecked[column][row] = !cellChecked[column][row];
invalidate();
}
}
and here is my activity to call the moveForward() method
public class MainActivity extends Activity {
PixelGridView pgv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pgv = new PixelGridView(this);
pgv.setNumColumns(20);
pgv.setNumRows(15);
}
public void onBtnForwardPressed(View view) {
pgv.moveForward();
}
}
and here's the log:
05-10 00:36:33.388: E/AndroidRuntime(8414): Caused by: java.lang.NullPointerException
05-10 00:36:33.388: E/AndroidRuntime(8414): at com.test.PixelGridView.moveForward(PixelGridView.java:131)
05-10 00:36:33.388: E/AndroidRuntime(8414): at com.test.MainActivity.onBtnForwardPressed(MainActivity.java:281)
moveForward() method to move robot:
if (currentAngle == 0) {
for (int i = 0; i < numColumns; i++) {
for (int j = 0; j < numRows; j++) {
if (cellChecked[i][j]) {
column1 = i;
row1 = j;
}
}
}
cellChecked[column1][row1] = !cellChecked[column1][row1];
cellChecked[column1+1][row1] = !cellChecked[column1+1][row1];
invalidate();
}
The PixelGridView object you're creating with new isn't in the Activity's layout, as you've not added it. If you've defined a PixelGridView in the activity_main layout, then you should assign it to pgv using the findViewById() method. If you meant to create it programmatically, then you should add it to the Activity's layout using the addContentView() method.
Related
Currently I'm developing a pattern lock application and in that application I extend pattern View from Viewgroup, it means it can display pattern lock View and I am using drawable png image to display pattern View.
So, actually I want to change that pattern lock png image dynamically when user selects that image in another GridView and display it on the pattern View.
Basically, I want to change only pattern lock theme.
Main screenshote of lockscreen
Here this is my pattern lock view xml
<com.v1.sensoft.halloweenlock.utils.Lock9View
android:id="#+id/lock_9_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:nodeSrc="#mipmap/ppo"
app:nodeOnSrc="#mipmap/ppn"
android:layout_gravity="center"
app:lineColor="#FFCC00"
app:lineWidth="8dp" />
In that xml app:nodeSrc="#mipmap/ppo" app:nodeOnSrc="#mipmap/ppn"is the image to display on pattern lock.
This is my pattern lock view
public class Lock9View extends ViewGroup {
private Paint paint;
private Bitmap bitmap;
private Canvas canvas;
private List<Pair<NodeView, NodeView>> lineList;
private NodeView currentNode;
private StringBuilder pwdSb;
private CallBack callBack;
private Drawable nodeSrc;
private Drawable nodeOnSrc;
public Lock9View(Context context) {
this(context, null);
}
public Lock9View(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public Lock9View(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public Lock9View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr); // TODO api 21
initFromAttributes(attrs, defStyleAttr);
}
private void initFromAttributes(AttributeSet attrs, int defStyleAttr) {
final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.Lock9View, defStyleAttr, 0);
nodeSrc = a.getDrawable(R.styleable.Lock9View_nodeSrc);
nodeOnSrc = a.getDrawable(R.styleable.Lock9View_nodeOnSrc);
int lineColor = Color.argb(0, 0, 0, 0);
lineColor = a.getColor(R.styleable.Lock9View_lineColor, lineColor);
float lineWidth = 20.0f;
lineWidth = a.getDimension(R.styleable.Lock9View_lineWidth, lineWidth);
a.recycle();
paint = new Paint(Paint.DITHER_FLAG);
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(lineWidth);
paint.setColor(lineColor);
paint.setAntiAlias(true);
DisplayMetrics dm = getResources().getDisplayMetrics();
bitmap = Bitmap.createBitmap(dm.widthPixels, dm.widthPixels, Bitmap.Config.ARGB_8888);
canvas = new Canvas();
canvas.setBitmap(bitmap);
for (int n = 0; n < 9; n++) {
NodeView node = new NodeView(getContext(), n + 1);
addView(node);
}
lineList = new ArrayList<Pair<NodeView,NodeView>>();
pwdSb = new StringBuilder();
setWillNotDraw(false);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(widthMeasureSpec, widthMeasureSpec);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (!changed) {
return;
}
int width = right - left;
int nodeWidth = width / 3;
int nodePadding = nodeWidth / 6;
for (int n = 0; n < 9; n++) {
NodeView node = (NodeView) getChildAt(n);
int row = n / 3;
int col = n % 3;
int l = col * nodeWidth + nodePadding;
int t = row * nodeWidth + nodePadding;
int r = col * nodeWidth + nodeWidth - nodePadding;
int b = row * nodeWidth + nodeWidth - nodePadding;
node.layout(l, t, r, b);
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(bitmap, 0, 0, null);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
NodeView nodeAt = getNodeAt(event.getX(), event.getY());
if (nodeAt == null && currentNode == null) {
return true;
} else {
clearScreenAndDrawList();
if (currentNode == null) {
currentNode = nodeAt;
currentNode.setHighLighted(true);
pwdSb.append(currentNode.getNum());
}
else if (nodeAt == null || nodeAt.isHighLighted()) {
canvas.drawLine(currentNode.getCenterX(), currentNode.getCenterY(), event.getX(), event.getY(), paint);
} else {
canvas.drawLine(currentNode.getCenterX(), currentNode.getCenterY(), nodeAt.getCenterX(), nodeAt.getCenterY(), paint);
nodeAt.setHighLighted(true);
Pair<NodeView, NodeView> pair = new Pair<NodeView, NodeView>(currentNode, nodeAt);
lineList.add(pair);
currentNode = nodeAt;
pwdSb.append(currentNode.getNum());
}
invalidate();
}
return true;
case MotionEvent.ACTION_UP:
if (pwdSb.length() <= 0) {
return super.onTouchEvent(event);
}
if (callBack != null) {
callBack.onFinish(pwdSb.toString());
pwdSb.setLength(0);
}
currentNode = null;
lineList.clear();
clearScreenAndDrawList();
for (int n = 0; n < getChildCount(); n++) {
NodeView node = (NodeView) getChildAt(n);
node.setHighLighted(false);
}
invalidate();
return true;
}
return super.onTouchEvent(event);
}
private void clearScreenAndDrawList() {
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
for (Pair<NodeView, NodeView> pair : lineList) {
canvas.drawLine(pair.first.getCenterX(), pair.first.getCenterY(), pair.second.getCenterX(), pair.second.getCenterY(), paint);
}
}
private NodeView getNodeAt(float x, float y) {
for (int n = 0; n < getChildCount(); n++) {
NodeView node = (NodeView) getChildAt(n);
if (!(x >= node.getLeft() && x < node.getRight())) {
continue;
}
if (!(y >= node.getTop() && y < node.getBottom())) {
continue;
}
return node;
}
return null;
}
public void setCallBack(CallBack callBack) {
this.callBack = callBack;
}
public class NodeView extends View {
private int num;
private boolean highLighted;
private NodeView(Context context) {
super(context);
}
public NodeView(Context context, int num) {
this(context);
this.num = num;
highLighted = false;
if (nodeSrc == null) {
setBackgroundResource(0);
} else {
setBackgroundDrawable(nodeSrc);
}
}
public boolean isHighLighted() {
return highLighted;
}
public void setHighLighted(boolean highLighted) {
this.highLighted = highLighted;
if (highLighted) {
if (nodeOnSrc == null) {
setBackgroundResource(0);
} else {
setBackgroundDrawable(nodeOnSrc);
}
} else {
if (nodeSrc == null) {
setBackgroundResource(0);
} else {
setBackgroundDrawable(nodeSrc);
}
}
}
public int getCenterX() {
return (getLeft() + getRight()) / 2;
}
public int getCenterY() {
return (getTop() + getBottom()) / 2;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
public interface CallBack {
public void onFinish(String password);
}
Activity
prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
lock9View = (Lock9View) findViewById(R.id.lock_9_view);
lock9View.setCallBack(new Lock9View.CallBack() {
public int counter = 0;
public int buttCounter = 0;
#Override
public void onFinish(String password) {
PATTERN_KEY = prefs.getString("Pattern", "invalid");
Log.i("Counter","..."+counter);
if (PATTERN_KEY.equals("invalid")) {
Toast.makeText(MainActivity.this, "Options --> Create new Pattern", Toast.LENGTH_LONG).show();
} else {
if (password.equals(PATTERN_KEY)) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
} else {
invalidPattern();
Toast.makeText(MainActivity.this, "Please try again..." +failedCount, Toast.LENGTH_LONG).show();
}
}
}
});
}
So,if anyone know please give some idea of that.
I need something like TabLayout with scrolling and selecting central tab with corresponding ViewPager performance attached to it.
I've tried solve this problem by writing next code but it seems quite glitchy. I'm sure there is other way to solve this problem.
public class CenteredTabLayout extends TabLayout {
public ViewPager mViewPager;
private int currentWidthOffset = 0;
private int index = 0;
private int totalElementsNumber;
private ArrayList<Integer> elementsWidth = new ArrayList<>();
private volatile int state = 2;
public CenteredTabLayout(Context context) {
super(context);
}
public CenteredTabLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CenteredTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
public void addTab(#NonNull Tab tab) {
getElementsWidth();
super.addTab(tab);
}
#Override
public void removeTab(Tab tab) {
getElementsWidth();
super.removeTab(tab);
}
private void getElementsWidth() {
elementsWidth.clear();
totalElementsNumber = ((ViewGroup)getChildAt(0)).getChildCount();
//Log.i(ScrollableTabsActivityCustom1.TAG, "totalElementsNumber = " + totalElementsNumber);
for(int i = 0; i < totalElementsNumber; i++) {
elementsWidth.add(((ViewGroup)getChildAt(0)).getChildAt(i).getWidth());
//Log.i(ScrollableTabsActivityCustom1.TAG, "elementsWidth.get(i) = " + elementsWidth.get(i));
}
}
CountDownTimer mCountDownTimer = new CountDownTimer(500, 500) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
Log.i(ScrollableTabsActivityCustom1.TAG, "finished");
View tab = ((ViewGroup)getChildAt(0)).getChildAt(index);
scrollTo(currentWidthOffset , 0);
}
};
private void startTimer(final int currentState) {
if(currentState != state) {
new Thread(new Runnable() {
#Override
public void run() {
state = currentState;
try {
Thread.sleep(500);
} catch (InterruptedException pE) {
pE.printStackTrace();
}
mViewPager.setCurrentItem(index);
state = 2;
}
}).start();
}
}
#Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
getElementsWidth();
int difference = l - oldl;
int currentWidthOffsetSave = currentWidthOffset;
if(state != 1 && difference > 0 && l > (currentWidthOffset + elementsWidth.get(checkIndex(index)) / 2)) {
do {
currentWidthOffset += elementsWidth.get(checkIndex(index));
index++;
index = checkIndex(index);
mViewPager.setCurrentItem(index);
View tab = ((ViewGroup)getChildAt(0)).getChildAt(index);
scrollTo(currentWidthOffset, 0);
} while(currentWidthOffsetSave + difference > currentWidthOffset + elementsWidth.get(checkIndex(index)) / 2);
if(difference > 10) {
startTimer(0);
}
}
if(state != 0 && difference < 0 && l < (currentWidthOffset - elementsWidth.get(checkIndex(index - 1)) / 2)) {
do {
index--;
index = checkIndex(index);
currentWidthOffset -= elementsWidth.get(index);
mViewPager.setCurrentItem(index);
scrollTo(currentWidthOffset, 0);
} while(currentWidthOffsetSave - difference < currentWidthOffset - elementsWidth.get(checkIndex(index)) / 2);
if(difference < 10) {
startTimer(1);
}
}
mCountDownTimer.cancel();
mCountDownTimer.start();
}
private int checkIndex(int index) {
if(index < 0) {
index = 0;
}
if(index > totalElementsNumber - 1) {
index = totalElementsNumber - 1;
}
return index;
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
View firstTab = ((ViewGroup)getChildAt(0)).getChildAt(0);
View lastTab = ((ViewGroup)getChildAt(0)).getChildAt(((ViewGroup)getChildAt(0)).getChildCount() - 1);
ViewCompat.setPaddingRelative(getChildAt(0), (getWidth() / 2) - (firstTab.getWidth() / 2), 0, (getWidth() / 2) - (lastTab.getWidth() / 2) , 0);
}
}
I want to achieve this layout. Table can have different number of rows, but once this number is set, it wouldn't change. Also, there is no need for scroll.
Well... I could do this with simple TableLayout, but it doesn't support data binding.
So I'm trying to implement custom AdapterView, but nothing is appeared in a screen.
public class MainActivity extends Activity {
String[][] data = new String[5][5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout layout = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_main, null);
setContentView(layout);
SquareTableView sqt = new SquareTableView(this);
sqt.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
sqt.setNumColumns(5);
layout.addView(sqt);
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
data[i][j] = "a";
sqt.setAdapter(new CellArrayAdapter(this, data) {
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
public class SquareTableView extends AdapterView<ListAdapter> {
private ListAdapter adapter;
private int numColumns;
public int getNumColumns() {
return numColumns;
}
public void setNumColumns(int numColumns) {
this.numColumns = numColumns;
}
public SquareTableView(Context context) {
super(context);
}
#Override
public ListAdapter getAdapter() {
return adapter;
}
#Override
public View getSelectedView() {
// TODO Auto-generated method stub
return null;
}
#Override
public void setAdapter(ListAdapter adapter) {
this.adapter = adapter;
requestLayout();
}
#Override
public void setSelection(int position) {
// TODO Auto-generated method stub
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Context context = getContext();
int orientation = context.getResources().getConfiguration().orientation;
int sideSize;
if (orientation == Configuration.ORIENTATION_PORTRAIT)
sideSize = MeasureSpec.getSize(widthMeasureSpec);
else {
sideSize = MeasureSpec.getSize(heightMeasureSpec);
}
setMeasuredDimension(sideSize, sideSize);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
for (int i = 0; i < adapter.getCount(); i++) {
int childSide = getWidth() / numColumns;
int row = i / numColumns;
int column = i % numColumns;
int leftPosition = childSide * column;
int rightPosition = leftPosition + childSide;
int topPosition = childSide * row;
int bottomPosition = topPosition + childSide;
View child = adapter.getView(i, null, this);
child.layout(leftPosition, topPosition, rightPosition, bottomPosition);
child.forceLayout();
}
}
this is my code which i follow from code.google.com this link http://code.google.com/p/android-playground/source/browse/#svn%2Ftrunk%2FSwipeyTabsSample
just tell me how do i add activites in this application? is show same activity in all tabs
public class SwipeyTabsSampleActivity extends FragmentActivity {
private static final String [] TITLES = {
"CATEGORIES",
"FEATURED",
"TOP PAID",
"TOP FREE",
"TOP GROSSING",
"TOP NEW PAID",
"TOP NEW FREE",
"TRENDING",
};
private SwipeyTabs mTabs;
private ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipeytab);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
SwipeyTabsPagerAdapter adapter = new SwipeyTabsPagerAdapter(this,
getSupportFragmentManager());
mViewPager.setAdapter(adapter);
mTabs.setAdapter(adapter);
mViewPager.setOnPageChangeListener(mTabs);
mViewPager.setCurrentItem(0);
}
private class SwipeyTabsPagerAdapter extends FragmentPagerAdapter implements
SwipeyTabsAdapter {
private final Context mContext;
public SwipeyTabsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
this.mContext = context;
}
#Override
public Fragment getItem(int position) {
return SwipeyTabFragment.newInstance(TITLES[position]);
}
#Override
public int getCount() {
return TITLES.length;
}
public TextView getTab(final int position, SwipeyTabs root) {
TextView view = (TextView) LayoutInflater.from(mContext).inflate(
R.layout.swipey_tab_indicator, root, false);
view.setText(TITLES[position]);
view.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mViewPager.setCurrentItem(position);
}
});
return view;
}
}
}
public interface SwipeyTabsAdapter {
/**
* Return the number swipey tabs. Needs to be aligned with the number of
* items in your {#link PagerAdapter}.
*
* #return
*/
int getCount();
/**
* Build {#link TextView} to diplay as a swipey tab.
*
* #param position the position of the tab
* #param root the root view
* #return
*/
TextView getTab(int position, SwipeyTabs root);
}
public class SwipeyTabs extends ViewGroup implements
OnPageChangeListener {
protected final String TAG = "SwipeyTabs";
private SwipeyTabsAdapter mAdapter;
private int mCurrentPos = -1;
// height of the bar at the bottom of the tabs
private int mBottomBarHeight = 2;
// height of the indicator for the fronted tab
private int mTabIndicatorHeight = 3;
// color for the bottom bar, fronted tab
private int mBottomBarColor = 0xff96aa39;
// text color for all other tabs
private int mTextColor = 0xff949494;
// holds the positions of the fronted tabs
private int[] mFrontedTabPos;
// holds the positions of the target position when swiping left
private int[] mLeftTabPos;
// holds the positions of the target position when swiping right
private int[] mRightTabPos;
// holds the positions of the current position on screen
private int[] mCurrentTabPos;
private Paint mCachedTabPaint;
private int mWidth = -1;
public SwipeyTabs(Context context) {
this(context, null);
}
public SwipeyTabs(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SwipeyTabs(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.SwipeyTabs, defStyle, 0);
mBottomBarColor = a.getColor(R.styleable.SwipeyTabs_bottomBarColor,
mBottomBarColor);
mBottomBarHeight = a.getDimensionPixelSize(
R.styleable.SwipeyTabs_bottomBarHeight, 2);
mTabIndicatorHeight = a.getDimensionPixelSize(
R.styleable.SwipeyTabs_tabIndicatorHeight, 3);
a.recycle();
init();
}
/**
* Initialize the SwipeyTabs {#link ViewGroup}
*/
private void init() {
// enable the horizontal fading edges which will be drawn by the parent
// View
setHorizontalFadingEdgeEnabled(true);
setFadingEdgeLength((int) (getResources().getDisplayMetrics().density *
35.0f + 0.5f));
setWillNotDraw(false);
mCachedTabPaint = new Paint();
mCachedTabPaint.setColor(mBottomBarColor);
}
/**
* Set the adapter.
*
* #param adapter
*/
public void setAdapter(SwipeyTabsAdapter adapter) {
if (mAdapter != null) {
// TODO: data set observer
}
mAdapter = adapter;
mCurrentPos = -1;
mFrontedTabPos = null;
mLeftTabPos = null;
mRightTabPos = null;
mCurrentTabPos = null;
// clean up our childs
removeAllViews();
if (mAdapter != null) {
final int count = mAdapter.getCount();
// add the child text views
for (int i = 0; i < count; i++) {
addView(mAdapter.getTab(i, this));
}
mCurrentPos = 0;
mFrontedTabPos = new int[count];
mLeftTabPos = new int[count];
mRightTabPos = new int[count];
mCurrentTabPos = new int[count];
mWidth = -1;
requestLayout();
}
}
/**
* Calculate the fronted, left and right positions
*
* #param forceLayout
* force the current positions to the values of the calculated
* fronted positions
*/
private void updateTabPositions(boolean forceLayout) {
if (mAdapter == null) {
return;
}
calculateTabPosition(mCurrentPos, mFrontedTabPos);
calculateTabPosition(mCurrentPos + 1, mLeftTabPos);
calculateTabPosition(mCurrentPos - 1, mRightTabPos);
updateEllipsize();
if (forceLayout) {
final int count = mAdapter.getCount();
for (int i = 0; i < count; i++) {
mCurrentTabPos[i] = mFrontedTabPos[i];
}
}
}
/**
* Calculate the position of the tabs.
*
* #param position
* the position of the fronted tab
* #param tabPositions
* the array in which to store the result
*/
private void calculateTabPosition(int position, int[] tabPositions) {
if (mAdapter == null) {
return;
}
final int count = mAdapter.getCount();
if (position >= 0 && position < count) {
final int width = getMeasuredWidth();
final View centerTab = getChildAt(position);
tabPositions[position] = width / 2 - centerTab.getMeasuredWidth()
/ 2;
for (int i = position - 1; i >= 0; i--) {
final TextView tab = (TextView) getChildAt(i);
if (i == position - 1) {
tabPositions[i] = 0 - tab.getPaddingLeft();
} else {
tabPositions[i] = 0 - tab.getMeasuredWidth() -
width;
}
tabPositions[i] = Math.min(tabPositions[i], tabPositions[i
+ 1]
- tab.getMeasuredWidth());
}
for (int i = position + 1; i < count; i++) {
final TextView tab = (TextView) getChildAt(i);
if (i == position + 1) {
tabPositions[i] = width - tab.getMeasuredWidth()
+ tab.getPaddingRight();
} else {
tabPositions[i] = width * 2;
}
final TextView prevTab = (TextView) getChildAt(i - 1);
tabPositions[i] = Math.max(tabPositions[i], tabPositions[i
- 1]
+ prevTab.getMeasuredWidth());
}
} else {
for (int i = 0; i < tabPositions.length; i++) {
tabPositions[i] = -1;
}
}
}
/**
* Update the ellipsize of the text views
*/
private void updateEllipsize() {
if (mAdapter == null) {
return;
}
final int count = mAdapter.getCount();
for (int i = 0; i < count; i++) {
TextView tab = (TextView) getChildAt(i);
if (i < mCurrentPos) {
tab.setEllipsize(null);
tab.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
} else if (i == mCurrentPos) {
tab.setEllipsize(TruncateAt.END);
tab.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
} else if (i > mCurrentPos) {
tab.setEllipsize(null);
tab.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
}
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
measureTabs(widthMeasureSpec, heightMeasureSpec);
int height = 0;
final View v = getChildAt(0);
if (v != null) {
height = v.getMeasuredHeight();
}
setMeasuredDimension(
resolveSize(getPaddingLeft() + widthSize +
getPaddingRight(),
widthMeasureSpec),
resolveSize(height + mBottomBarHeight + getPaddingTop()
+ getPaddingBottom(), heightMeasureSpec));
if (mWidth != widthSize) {
mWidth = widthSize;
updateTabPositions(true);
}
}
/**
* Measure our tab text views
*
* #param widthMeasureSpec
* #param heightMeasureSpec
*/
private void measureTabs(int widthMeasureSpec, int heightMeasureSpec) {
if (mAdapter == null) {
return;
}
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
final int maxWidth = (int) (widthSize * 0.6);
final int count = mAdapter.getCount();
for (int i = 0; i < count; i++) {
LayoutParams layoutParams = (LayoutParams) getChildAt(i)
.getLayoutParams();
final int widthSpec = MeasureSpec.makeMeasureSpec(maxWidth,
MeasureSpec.AT_MOST);
final int heightSpec = MeasureSpec.makeMeasureSpec(
layoutParams.height, MeasureSpec.EXACTLY);
getChildAt(i).measure(widthSpec, heightSpec);
}
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (mAdapter == null) {
return;
}
final int count = mAdapter.getCount();
for (int i = 0; i < count; i++) {
View v = getChildAt(i);
v.layout(mCurrentTabPos[i], this.getPaddingTop(), mCurrentTabPos[i]
+ v.getMeasuredWidth(),
this.getPaddingTop() + v.getMeasuredHeight());
}
}
#Override
protected void dispatchDraw(Canvas canvas) {
if (mCurrentPos != -1) {
// calculate the relative position of the fronted tab to set the
// alpha channel of the tab indicator
final int tabSelectedTop = getHeight() - getPaddingBottom()
- mBottomBarHeight - mTabIndicatorHeight;
final View currentTab = getChildAt(mCurrentPos);
final int centerOfTab = (mCurrentTabPos[mCurrentPos] + currentTab
.getMeasuredWidth()) -
(currentTab.getMeasuredWidth() / 2);
final int center = getWidth() / 2;
final int centerDiv3 = center / 3;
final float relativePos = 1.0f - Math.min(
Math.abs((float) (centerOfTab - center)
/ (float) (centerDiv3)), 1.0f);
mCachedTabPaint.setAlpha((int) (255 * relativePos));
canvas.drawRect(
mCurrentTabPos[mCurrentPos],
tabSelectedTop,
mCurrentTabPos[mCurrentPos] +
currentTab.getMeasuredWidth(),
tabSelectedTop + mTabIndicatorHeight,
mCachedTabPaint);
// set the correct text colors on the text views
final int count = mAdapter.getCount();
for (int i = 0; i < count; i++) {
final TextView tab = (TextView) getChildAt(i);
if (mCurrentPos == i) {
tab.setTextColor(interpolateColor(mBottomBarColor,
mTextColor, 1.0f - relativePos));
} else {
tab.setTextColor(mTextColor);
}
}
}
super.dispatchDraw(canvas);
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
// draw the bottom bar
final int bottomBarTop = getHeight() - getPaddingBottom()
- mBottomBarHeight;
mCachedTabPaint.setAlpha(0xff);
canvas.drawRect(0, bottomBarTop, getWidth(), bottomBarTop
+ mBottomBarHeight, mCachedTabPaint);
}
#Override
protected float getLeftFadingEdgeStrength() {
// forced so that we will always have the left fading edge
return 1.0f;
}
#Override
protected float getRightFadingEdgeStrength() {
// forced so that we will always have the right fading edge
return 1.0f;
}
public void onPageScrollStateChanged(int state) {
}
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
if (mAdapter == null) {
return;
}
final int count = mAdapter.getCount();
float x = 0.0f;
int dir = 0;
// detect the swipe direction
if (positionOffsetPixels != 0 && mCurrentPos == position) {
dir = -1;
x = positionOffset;
} else if (positionOffsetPixels != 0 && mCurrentPos != position) {
dir = 1;
x = 1.0f - positionOffset;
}
// update the current positions
for (int i = 0; i < count; i++) {
final float curX = mFrontedTabPos[i];
float toX = 0.0f;
if (dir < 0) {
toX = mLeftTabPos[i];
} else if (dir > 0) {
toX = mRightTabPos[i];
} else {
toX = mFrontedTabPos[i];
}
final int offsetX = (int) ((toX - curX) * x + 0.5f);
final int newX = (int) (curX + offsetX);
mCurrentTabPos[i] = newX;
}
requestLayout();
invalidate();
}
public void onPageSelected(int position) {
mCurrentPos = position;
updateTabPositions(false);
}
private int interpolateColor(final int color1, final int color2,
float fraction) {
final float alpha1 = Color.alpha(color1) / 255.0f;
final float red1 = Color.red(color1) / 255.0f;
final float green1 = Color.green(color1) / 255.0f;
final float blue1 = Color.blue(color1) / 255.0f;
final float alpha2 = Color.alpha(color2) / 255.0f;
final float red2 = Color.red(color2) / 255.0f;
final float green2 = Color.green(color2) / 255.0f;
final float blue2 = Color.blue(color2) / 255.0f;
final float deltaAlpha = alpha2 - alpha1;
final float deltaRed = red2 - red1;
final float deltaGreen = green2 - green1;
final float deltaBlue = blue2 - blue1;
float alpha = alpha1 + (deltaAlpha * fraction);
float red = red1 + (deltaRed * fraction);
float green = green1 + (deltaGreen * fraction);
float blue = blue1 + (deltaBlue * fraction);
alpha = Math.max(Math.min(alpha, 1f), 0f);
red = Math.max(Math.min(red, 1f), 0f);
green = Math.max(Math.min(green, 1f), 0f);
blue = Math.max(Math.min(blue, 1f), 0f);
return Color.argb((int) (alpha * 255.0f), (int) (red * 255.0f),
(int) (green * 255.0f), (int) (blue * 255.0f));
}
}
public class SwipeyTabFragment extends Fragment {
public static Fragment newInstance(String title) {
SwipeyTabFragment f = new SwipeyTabFragment();
Bundle args = new Bundle();
args.putString("title", title);
f.setArguments(args);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_swipeytab,
null);
final String title = getArguments().getString("title");
((TextView) root.findViewById(R.id.text)).setText(title);
return root;
}
}
just tell me how do i add activites in this application? is show same activity in all tabs
You don't. Having activities-in-tabs was deprecated well over two years ago.
A ViewPager typically uses fragments for its pages, as is demonstrated in the code you pasted above. In this sample, each page is a SwipeyTabFragment, but you are welcome to have pages be different fragment classes if you prefer. You are also welcome to not use fragments and use custom Views instead for the pages. But there is no support for putting activities as pages.
I am using a View extended from View group and the onDraw is not getting called when I call invalidate.Can any one please explain?
The code is given below
public class BarGraph extends View {
private int viewHeight;
private int viewWidth; // height and width of bar graph dynamically calculated.
private int mGraphColor; // the colour of the bar graph.
private ArrayList<Integer> mTodays; // The array list that handles the input to draw the graph.
private final int barCount = 20; // Number of bars in the bar graph...here set as 20.
/*
* The maximum action value a bar can take.
* This is calculated based on the action array
* passed to the chart.
*/
private int yMax = 0;
private Paint graphColor;
public BarGraph(Context context, int graphColor) {
super(context);
this.setWillNotDraw(false);
mGraphColor = graphColor;
setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
initializePaintObjects();
}
public BarGraph(Context context, AttributeSet attrs) {
super(context, attrs);
this.setWillNotDraw(false);
initializePaintObjects();
}
private void initializePaintObjects(){
graphColor = new Paint();
graphColor.setColor(mGraphColor);
graphColor.setStyle(Style.FILL);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(mTodays == null) // If the array list is empty.
return;
if(yMax <= 0)
return;
int left = 0;
viewHeight = getHeight();
viewWidth = getWidth();
if((viewWidth % barCount) > 0){ //adjusting the view width so that bars correctly fits in
int newWidth = (int) (Math.floor(viewWidth / barCount) * barCount);
left = (int) Math.floor(((viewWidth - newWidth)/2));
viewWidth = (int) Math.floor((viewWidth / barCount) * barCount);
}
int columnWidth = 2;
columnWidth = (int) Math.floor(viewWidth / barCount);
int xFactor = 1;
xFactor = (int) Math.ceil(columnWidth * 0.33);
int barWidth = 1;
barWidth = columnWidth - xFactor;
graphColor.setStrokeWidth(barWidth);
int j = 0;
for(int i = 0; i < mTodays.size() ; i++){
int todayValue = mTodays.get(i);
float todaysHeight;
if(todayValue == 0){
todaysHeight = (float) (viewHeight-viewHeight*(.001));
}else{
todaysHeight = getYValue(todayValue);
}
canvas.drawLine(((j*columnWidth)+xFactor + left) , viewHeight, ((j*columnWidth)+xFactor + left), todaysHeight, graphColor);
j++;
}
}
public void setData(ArrayList<Integer>todays){
mTodays = todays;
yMax = 0;
for (int val : mTodays){
yMax = yMax > val ? yMax : val;
}
invalidate();
}
private int getYValue(int item){
int percent = (item * 100)/yMax;
return (viewHeight) - ((percent * viewHeight)/100);
}
}
Thanks for all your attempts.The problem was actually in the Main Activity.
The following is the correct code
final Handler handler = new Handler();
Timer timer2 = new Timer();
TimerTask testing = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
for(int j=0;j<19;j++){
todays.set(j, todays.get(j+1));
}
Random diceRoller = new Random();
todays.set(19, diceRoller.nextInt(100)*10+1);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
bargraph.setData(todays);
}
});
}
});
I had not written the runOnUiThread at first...My bad...