Popup gridview cell onTOuch - java

I have a grid View In which I am adding Button dynamically.
I am setting OnTouch listener to grid view.
I want when my finger move on the particular cell then that cell element should get popup
similar way our android keyboard do.
public class MainActivity extends Activity {
private ArrayList<Integer> data;
private GridView gv;
private TextView biggerView = null;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createData();
gv = (GridView) findViewById(R.id.grid);
gv.setNumColumns(10);
gv.setAdapter(new FilterButtonAdapter(data, this));
gv.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
try {
int position = gv.pointToPosition((int) event.getX(),
(int) event.getY());
View v = (View) gv.getChildAt(position);
if (v != null) {
gv.requestFocus();
gv.setSelection(gv.pointToPosition( (int)
event.getX(), (int) event.getY()));
}
return true;
} catch (Exception e) {
return true;
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
int position = gv.pointToPosition((int) event.getX(),
(int) event.getY());
View v = (View) gv.getChildAt(position);
if (v != null) {
gv.clearFocus();
TextView tv = (TextView) v.findViewById(R.id.texttoadd);
Toast.makeText(MainActivity.this, tv.getText(),
Toast.LENGTH_SHORT).show();
}
return true;
}
return false;
}
});
}
private void createData() {
data = new ArrayList<Integer>();
for (int i = 0; i < 200; i++) {
data.add(i);
}
}
enter code here
i have write this code which is giving me the selected item but when item are more then grid is scrolled and after that the am not getting the item which i am selecting
i have figured out that the x and y position is getting change when grid is scrolled
i may be wrong
please help

I think that suggested in the question way of touch position detection might be not effective, because there's more high-level way to obtain scrolling position.
The main ideas of the implementation are the following:
Use onScrollChanged() to track scroll position at every moment;
Display selection as separate view above GridView;
Track if selected item is visible (using this question);
So, to obtain proper scroll callback, slightly customized GridView is needed:
public class ScrollAwareGridView extends GridView {
/** Callback interface to report immediate scroll changes */
public interface ImmediateScrollListener {
void onImmediateScrollChanged();
}
/** External listener for */
private ImmediateScrollListener mScrollListener = null;
public ScrollAwareGridView(final Context context) {
super(context);
}
public ScrollAwareGridView(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
public ScrollAwareGridView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onScrollChanged(final int l, final int t, final int oldl, final int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (null != mScrollListener) {
mScrollListener.onImmediateScrollChanged();
}
}
/**
* #param listener {#link ImmediateScrollListener}
*/
public void setImmediateScrollListener(final ImmediateScrollListener listener) {
mScrollListener = listener;
}
}
It will be placed in the xml the following way (main.xml):
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.TestApp.ScrollAwareGridView
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3" />
<!-- Selection view -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/selectedImage"
android:visibility="gone" />
</RelativeLayout>
In above xml there's also selection view presented.
Activity will handle selection of items (however, it might be better to keep selection and scroll tracking logic in separate object (grid adapter or specific grid fragment) in order not to keep grid-specific logic in Activity code):
public class MyActivity extends Activity implements ScrollAwareGridView.ImmediateScrollListener, AdapterView.OnItemClickListener {
private static final String TAG = "MyActivity";
/** To start / pause music */
private ImageView mSelectedImage = null;
/** position of selected item in the adapter */
private int mSelectedPosition;
/** Main grid view */
private ScrollAwareGridView mGrid;
/** Adapter for grid view */
private ImageAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Show the layout with the test view
setContentView(R.layout.main);
mSelectedImage = (ImageView) findViewById(R.id.selectedImage);
mGrid = (ScrollAwareGridView) findViewById(R.id.grid);
if (null != mGrid) {
mAdapter = new ImageAdapter(this);
mGrid.setAdapter(mAdapter);
mGrid.setImmediateScrollListener(this);
mGrid.setOnItemClickListener(this);
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
mSelectedImage.setImageBitmap(null);
mSelectedImage.setVisibility(View.GONE);
mSelectedPosition = -1;
}
#Override
public void onImmediateScrollChanged() {
if (mSelectedPosition >= 0) {
int firstPosition = mGrid.getFirstVisiblePosition(); // This is the same as child #0
int wantedChild = mSelectedPosition - firstPosition;
// Say, first visible position is 8, you want position 10, wantedChild will now be 2
// So that means your view is child #2 in the ViewGroup:
if (wantedChild < 0 || wantedChild >= mGrid.getChildCount()) {
Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen.");
mSelectedImage.setVisibility(View.INVISIBLE);
return;
} else {
mSelectedImage.setVisibility(View.VISIBLE);
}
// Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead.
final View selectedView = mGrid.getChildAt(wantedChild);
if (null != selectedView && mSelectedImage.getVisibility() == View.VISIBLE) {
// Put selected view on new position
final ViewGroup.MarginLayoutParams zoomedImageLayoutParams = (ViewGroup.MarginLayoutParams) mSelectedImage.getLayoutParams();
// 200 is difference between zoomed and not zoomed images dimensions
// TODO: Avoid hardcoded values and use resources
final Integer thumbnailX = mGrid.getLeft() + selectedView.getLeft() - (ImageAdapter.HIGHLIGHTED_GRID_ITEM_DIMENSION - ImageAdapter.GRID_ITEM_DIMENSION) / 2;
final Integer thumbnailY = mGrid.getTop() + selectedView.getTop() - (ImageAdapter.HIGHLIGHTED_GRID_ITEM_DIMENSION - ImageAdapter.GRID_ITEM_DIMENSION) / 2;
zoomedImageLayoutParams.setMargins(thumbnailX,
thumbnailY,
0,
0);
mSelectedImage.setLayoutParams(zoomedImageLayoutParams);
}
}
}
#Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
mSelectedPosition = position;
final Bitmap bm = mAdapter.getImage(position);
// Obtain image from adapter, with check if image presented
if (bm != null) {
final ViewGroup.MarginLayoutParams zoomedImageLayoutParams = (ViewGroup.MarginLayoutParams) mSelectedImage.getLayoutParams();
// 200 is difference between zoomed and not zoomed images dimensions
// TODO: Avoid hardcoded values and use resources
final Integer thumbnailX = mGrid.getLeft() + view.getLeft() - (ImageAdapter.HIGHLIGHTED_GRID_ITEM_DIMENSION - ImageAdapter.GRID_ITEM_DIMENSION) / 2;
final Integer thumbnailY = mGrid.getTop() + view.getTop() - (ImageAdapter.HIGHLIGHTED_GRID_ITEM_DIMENSION - ImageAdapter.GRID_ITEM_DIMENSION) / 2;
zoomedImageLayoutParams.setMargins(thumbnailX,
thumbnailY,
0,
0);
zoomedImageLayoutParams.height = ImageAdapter.HIGHLIGHTED_GRID_ITEM_DIMENSION;
zoomedImageLayoutParams.width = ImageAdapter.HIGHLIGHTED_GRID_ITEM_DIMENSION;
mSelectedImage.setImageBitmap(bm);
mSelectedImage.setScaleType(ImageView.ScaleType.CENTER);
mSelectedImage.setLayoutParams(zoomedImageLayoutParams);
mSelectedImage.setVisibility(View.VISIBLE);
}
}
}
Below is GridViews adapter. However there's nothing specific in it which related to scrolling tracking (most of code I've reused from this answer):
public class ImageAdapter extends BaseAdapter {
private static final String TAG = "ImageAdapter";
/** For creation of child ImageViews */
private Context mContext;
public static final Integer[] IMAGES_RESOURCES = {
R.drawable.image001, R.drawable.image002, R.drawable.image003, R.drawable.image004,
R.drawable.image005, R.drawable.image006, R.drawable.image007, R.drawable.image008,
R.drawable.image009, R.drawable.image010, R.drawable.image011, R.drawable.image012,
R.drawable.image013, R.drawable.image014, R.drawable.image015, R.drawable.image016,
R.drawable.image017, R.drawable.image018, R.drawable.image019, R.drawable.image020,
R.drawable.image021, R.drawable.image022, R.drawable.image023, R.drawable.image024,
R.drawable.image025, R.drawable.image026, R.drawable.image027, R.drawable.image028,
R.drawable.image029, R.drawable.image030, R.drawable.image031, R.drawable.image032,
R.drawable.image033, R.drawable.image034, R.drawable.image035, R.drawable.image036,
R.drawable.image037, R.drawable.image038, R.drawable.image039, R.drawable.image040,
R.drawable.image041, R.drawable.image042, R.drawable.image043, R.drawable.image044,
R.drawable.image045, R.drawable.image046, R.drawable.image047, R.drawable.image048,
R.drawable.image049, R.drawable.image050
};
// TODO: use resources for that sizes, otherwise You'll GET PROBLEMS on other displays!
public final static int GRID_ITEM_DIMENSION = 300;
public final static int HIGHLIGHTED_GRID_ITEM_DIMENSION = 500;
private Bitmap mHolder = null;
private static final int CACHE_SIZE = 50 * 1024 * 1024; // 8 MiB cache
/** Cache to store all decoded images */
private LruCache<Integer, Bitmap> mBitmapsCache = new LruCache<Integer, Bitmap>(CACHE_SIZE) {
#Override
protected int sizeOf(final Integer key, final Bitmap value) {
return value.getByteCount();
}
#Override
protected void entryRemoved(final boolean evicted, final Integer key, final Bitmap oldValue, final Bitmap newValue) {
if (!oldValue.equals(mHolder)) {
oldValue.recycle();
}
}
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
mHolder = BitmapFactory.decodeResource(c.getResources(), R.drawable.ic_launcher, null);
}
#Override
public int getCount() {
return IMAGES_RESOURCES.length;
}
#Override
public Object getItem(int position) {
return IMAGES_RESOURCES[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(GRID_ITEM_DIMENSION, GRID_ITEM_DIMENSION));
} else {
imageView = (ImageView) convertView;
}
final Bitmap itemBitmap = mBitmapsCache.get(IMAGES_RESOURCES[position]);
if (itemBitmap == null || itemBitmap.isRecycled()) {
Log.e(TAG, position + " is missed, launch decode for " + IMAGES_RESOURCES[position]);
imageView.setImageBitmap(mHolder);
mBitmapsCache.put(IMAGES_RESOURCES[position], mHolder);
new BitmapWorkerTask(mBitmapsCache, mContext.getResources(), this).execute(IMAGES_RESOURCES[position]);
} else {
Log.e(TAG, position + " is here for " + IMAGES_RESOURCES[position]);
imageView.setImageBitmap(itemBitmap);
}
return imageView;
}
/**
* Obtains image at position (if there's only holder, then null to be returned)
*
* #param position int position in the adapter
*
* #return {#link Bitmap} image at position or null if image is not loaded yet
*/
public Bitmap getImage(final int position) {
final Bitmap bm = mBitmapsCache.get(IMAGES_RESOURCES[position]);
return ((mHolder.equals(bm) || bm == null) ? null : bm.copy(Bitmap.Config.ARGB_8888, false));
}
/** AsyncTask for decoding images from resources */
static class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private int data = 0;
private final LruCache<Integer, Bitmap> mCache;
private final Resources mRes;
private final BaseAdapter mAdapter;
public BitmapWorkerTask(LruCache<Integer, Bitmap> cache, Resources res, BaseAdapter adapter) {
// nothing to do here
mCache = cache;
mRes = res;
mAdapter = adapter;
}
// Decode image in background.
#Override
protected Bitmap doInBackground(Integer... params) {
data = params[0];
// Use sizes for selected bitmaps for good up-scaling
return decodeSampledBitmapFromResource(mRes, data, GRID_ITEM_DIMENSION, GRID_ITEM_DIMENSION);
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap) {
mCache.put(data, bitmap);
mAdapter.notifyDataSetChanged();
}
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
options.outHeight = GRID_ITEM_DIMENSION;
options.outWidth = GRID_ITEM_DIMENSION;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
}

Related

Android restrict the size when text sizing with pinch zoom and temp image

There are texts on my static layout, the layout is an item in a Recyclerview. The touch event of the Recyclerview class controls the pinch zoom to the text with ScaleGestureDetector. The zooming senario is, when the user action move the screen of Recyclerview, getting the screenshot of the recyclerview and displaying the image over the Recyclerview, and the user zooming to the image. When the action up, applying new text size that coming from scaling to the items. The new text size is should be same with when the zooming to image displaying text size. For this I use RelativeSizeSpan and float scaler value. I want to limit the total text size changing but it just doesn't happen.
The real problem is, the pinch zoom can be done more than once and it is necessary to collect the scaling that each of them because the pinch zoom reseting each action pointer up. (mScaleFactor = 1.0f) And the all of scaling shouldn't cross the specified limit. (MAX_ZOOM and MIN_ZOOM)
Recyclerview:
private ScaleListener mScaleListener;
private ScaleGestureDetector mScaleGestureDetector;
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction() & MotionEvent.ACTION_MASK;
if(event.getPointerCount() == 2 && (action == MotionEvent.ACTION_MOVE || action == MotionEvent.ACTION_POINTER_UP)) {
if(mScaleGestureDetector == null){
mScaleListener = new ScaleListener(mRecyclerview, mContext);
mScaleGestureDetector = new ScaleGestureDetector(mContext, mScaleListener);
} return mScaleGestureDetector.onTouchEvent(event);
}
}
Adapter:
private void changeTextSize(float mScaleFactor){
...
float newFontSize = (relativeSizeSpan.getSizeChange() * mScaleFactor);
...
}
ScaleListener:
public class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
private static final float MAX_ZOOM = 2.5f;
private static final float MIN_ZOOM = 0.5f;
private float mScaleFactor = 1.0f;
private ImageView mScreenShotView;
private Context mContext;
private View mView;
public ScaleListener(View mView, Context mContext) {
this.mView = mView;
this.mContext = mContext;
init();
}
private void init(){
int mWidth = mView.getWidth();
int mHeight = mView.getHeight();
if(mWidth == 0 || mHeight == 0) return;
mScreenShotView = new ImageView(mContext);
mScreenShotView.setLayoutParams(new ViewGroup.LayoutParams(mWidth, mHeight));
ViewGroup mPhysicalParentLayout = (ViewGroup) mView.getParent();
mPhysicalParentLayout.addView(mScreenShotView, mPhysicalParentLayout.indexOfChild(mView));
}
#Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
mScreenShotView.setBackgroundDrawable(new BitmapDrawable(Kit.getScreenshot(mView)));
mScreenShotView.setAlpha(1f); mView.setAlpha(0f);
return true;
}
#Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector){
mScaleFactor *= scaleGestureDetector.getScaleFactor();
mScaleFactor = Math.max(MIN_ZOOM, Math.min(mScaleFactor, MAX_ZOOM));
mScreenShotView.setScaleX(mScaleFactor);
mScreenShotView.setScaleY(mScaleFactor);
return true;
}
#Override
public void onScaleEnd(ScaleGestureDetector detector) {
((ReadBookRcAdapter)Objects.requireNonNull(((RecyclerView)mView).getAdapter())).changeTextSize(mScaleFactor);
mScreenShotView.animate().alpha(0f).setDuration(300).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationStart(Animator animation) {
mView.animate().alpha(1f).setDuration(300).setListener(null);
}
#Override
public void onAnimationEnd(Animator animation) {
mScreenShotView.setScaleX(1.0f);
mScreenShotView.setScaleY(1.0f);
mScaleFactor = 1.0f;
}
});
}
}
Solved the issue with restricting value of TextView.setTextSize(). It's my adapter class:
public class ReadBookRcAdapter extends RecyclerView.Adapter<ReadBookRcAdapter.ReadBookViewHolder> {
private Context mContext;
private ArrayList<ReadBookTextBlockModel> mTextViewBlocks;
private float mTextSize;
public ReadBookRcAdapter(Context context) {
this.mContext = context;
this.mTextViewBlocks = new ReadBookTextBlockModel(context).getTextBlocks();
mTextSize = 15.0f;
}
class ReadBookViewHolder extends RecyclerView.ViewHolder {
TextView mTextViewItem;
ReadBookViewHolder(#NonNull View itemView) {
super(itemView);
this.mTextViewItem = itemView.findViewById(R.id.readBookTextRow);
}
void bind(ReadBookTextBlockModel dataList){
if (mTextSize != 15.0f) mTextViewItem.setTextSize(mTextSize);
mTextViewItem.setText(dataList.getBlockText());
}
}
#NonNull
#Override
public ReadBookViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rc_item_read_book, parent, false);
return new ReadBookViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ReadBookViewHolder holder, int position) {
ReadBookTextBlockModel model = mTextViewBlocks.get(position);
holder.bind(model);
}
public void setTextSize(float scale){
float maxTextSize = 37.5f;
float minTextSize = 7.5f;
if((mTextSize == minTextSize && scale < 1.0f) || (mTextSize == maxTextSize && scale >= 1.0f))
return;
float newTextSize = mTextSize * scale;
newTextSize = Math.max(minTextSize, Math.min(newTextSize, maxTextSize));
mTextSize = newTextSize;
Log.e("mTextSize*scale", String.valueOf(mTextSize));
notifyDataSetChanged();
}
}

Vertical ViewPager. Stop scrolling past certain point

I've created a vertical ViewPager, using ViewPage.PageTransformer and swapping X and Y coordinates. (I use this approach)
Now, what I want it to do is to stop scrolling at a certain point (I want the last view to take only 65% of the screen's height, but the full width).
Usually, I would override getPageWidth() in this case, but since my width and height are kind of mixed up right now, when I do that, my view takes 65% of both the height and width of the screen.
So how should I fix this?
Thank you!
MyViewPager.java
public class MyViewPager extends ViewPager {
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setPageTransformer(true, new VerticalPageTransformer());
setOverScrollMode(OVER_SCROLL_NEVER);
}
private class VerticalPageTransformer implements ViewPager.PageTransformer {
#Override
public void transformPage(View view, float position) {
if (position < -1) {
view.setAlpha(0);
} else if (position <= 1) {
view.setAlpha(1);
view.setTranslationX(view.getWidth() * -position);
float yPosition = position * view.getHeight();
view.setTranslationY(yPosition);
} else {
view.setAlpha(0);
}
}
}
private MotionEvent swapXY(MotionEvent ev) {
float width = getWidth();
float height = getHeight();
float newX = (ev.getY() / height) * width;
float newY = (ev.getX() / width) * height;
ev.setLocation(newX, newY);
return ev;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
return super.onTouchEvent(swapXY(ev));
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev){
boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
swapXY(ev);
return intercepted;
}
}
MyPagerAdapter.java
public class MyPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
public MyPagerAdapter(Context context) {
this.context = context;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
if (position == 0) {
View view = layoutInflater.inflate(R.layout.item_profile_picture, container, false);
container.addView(view);
return view;
}
else {
View view = layoutInflater.inflate(R.layout.item_profile_info, container, false);
container.addView(view);
return view;
}
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((FrameLayout) object);
}
#Override
public float getPageWidth(int position) {
if (position == 1) return (0.65f);
return super.getPageWidth(position);
}
}
Hi as far as I understand you are trying to stop at certain point without having the overscroll. Add overscroll(never) method to the viewpager that you want. And manage your margins on the objects. Wrap content as much as possible.
Solved this problem by using this library.

How to make an image shower larger from thumbnail in android?

I Have successfully started reading images back into my android app into a gridview, I need help now. When a user clicks on an image I want it to appear larger from the thumbnail. Any help is much appreciated.
My code for the images to get read :
[code]
public class View_Pictures extends AppCompatActivity {
public class ImageAdapter extends BaseAdapter {
private Context mContext;
ArrayList<String> itemList = new ArrayList<String>();
public ImageAdapter(Context c) {
mContext = c;
}
void add(String path){
itemList.add(path);
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(220, 220));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220);
imageView.setImageBitmap(bm);
return imageView;
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
}
ImageAdapter myImageAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view__pictures);
GridView gridview = (GridView) findViewById(R.id.gridview);
myImageAdapter = new ImageAdapter(this);
gridview.setAdapter(myImageAdapter);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Venns Road Accident";
Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files){
myImageAdapter.add(file.getAbsolutePath());
}
}
}
Gridview
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/textView47"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"/>
you can use photoviwer library which is used to show full detail image on seperate activity .
// Any implementation of ImageView can be used!
mImageView = (ImageView) findViewById(R.id.iv_photo);
// Set the Drawable displayed
Drawable bitmap = getResources().getDrawable(R.drawable.wallpaper);
// or
// get your bitmap here
mImageView.setImageDrawable(bitmap);
// Attach a PhotoViewAttacher, which takes care of all of the zooming functionality.
// (not needed unless you are going to change the drawable later)
mAttacher = new PhotoViewAttacher(mImageView);
please refer below link
https://github.com/chrisbanes/PhotoView

How to get Layout width modified in RecyclerView

I'm struggling in using a RecyclerView with a layout that has some listeners.
The code is this
ViewHolder
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView tickerSymbol;
public TextView companyName;
public View highlightBuy;
public LinearLayout categoryImage;
public LayoutParams categoryLayoutParams;
public LinearLayout arrowImage;
public ImageView categoryIconSeparator;
public ImageView arrowSeparator;
public ImageView arrowIcon;
public RelativeLayout stockRow;
public LinearLayout tickerInfo;
public Boolean isCategoryOpened = false;
public ViewHolder(View itemView) {
super(itemView);
this.tickerSymbol = (TextView) itemView.findViewById(R.id.ticker_symbol_textview);
this.companyName = (TextView) itemView.findViewById(R.id.company_name_textview);
this.highlightBuy = itemView.findViewById(R.id.highlight_buy_view);
this.categoryImage = (LinearLayout) itemView.findViewById(R.id.category_image);
this.categoryLayoutParams = (LayoutParams) categoryImage.getLayoutParams();
this.arrowImage = (LinearLayout) itemView.findViewById(R.id.arrow);
this.categoryIconSeparator = (ImageView) itemView.findViewById(R.id.category_icon_separator);
this.arrowSeparator = (ImageView) itemView.findViewById(R.id.arrow_separator);
this.arrowIcon = (ImageView) itemView.findViewById(R.id.arrow_icon_imageview);
this.stockRow = (RelativeLayout) itemView.findViewById(R.id.stock_row);
this.tickerInfo = (LinearLayout) itemView.findViewById(R.id.ticker_info);
}
}
onCreateViewHolder
#Override
public StockListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View stockView = inflater.inflate(R.layout.stock_list_row, parent, false);
return new StockListAdapter.ViewHolder(stockView);
}
onBindViewHolder
#Override
public void onBindViewHolder(final StockListAdapter.ViewHolder holder, final int position) {
final Stock stock = mStocks.get(position);
final int collapsedCategoryWidth = (int) mContext.getResources().getDimension(R.dimen.collapsed_category_icon_width);
final int stockRowHeight = (int) mContext.getResources().getDimension(R.dimen.stock_row_height);
//Reset holder status
if (holder.isCategoryOpened) {
holder.isCategoryOpened = false;
holder.categoryImage.getLayoutParams().width = collapsedCategoryWidth;
holder.categoryImage.setLayoutParams(holder.categoryImage.getLayoutParams());
holder.arrowIcon.setRotationY(0);
}
holder.tickerSymbol.setText(stock.ticker);
holder.companyName.setText(stock.name);
holder.companyName.setSelected(true);
holder.companyName.requestFocus();
holder.categoryImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int newWidth;
final int startWidth;
final int startArrowAngle;
final int newArrowAngle;
if (!holder.isCategoryOpened) {
holder.isCategoryOpened = true;
newWidth = holder.stockRow.getWidth() - holder.categoryLayoutParams.leftMargin - holder.arrowImage.getWidth() - ((LayoutParams) holder.arrowImage.getLayoutParams()).rightMargin - holder.categoryIconSeparator.getWidth();
startWidth = collapsedCategoryWidth;
startArrowAngle = 0;
newArrowAngle = 180;
} else {
holder.isCategoryOpened = false;
newWidth = collapsedCategoryWidth;
startWidth = holder.categoryImage.getWidth();
startArrowAngle = 180;
newArrowAngle = 0;
}
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
holder.categoryLayoutParams.width = startWidth + (int) ((newWidth - startWidth) * interpolatedTime);
//MAYBE PROBLEM HERE??
holder.categoryImage.setLayoutParams(holder.categoryLayoutParams);
holder.arrowIcon.setRotationY(startArrowAngle + (newArrowAngle - startArrowAngle) * interpolatedTime);
}
};
a.setDuration(500);
holder.categoryImage.startAnimation(a);
}
});
I'll attach a sample of the bug I have.
When I first click a view, the onClick work successfully, but if I scroll and then go back to that view, only the arrow gets flipped (which means the onClick gets called) but the LinearLayout Width won't get modified.
But now what's really strange is that if I click on another view that hasn't been clicked before, or (I guess) hasn't been recycled, happens the following:
So I guess, the Width is set, but isn't show.
I don't really know how to fix this.
An help or other ideas are appreciated!
Here is what I've already tried:
Putting the status in the stock;
Putting the listener outside the adapter;
Putting the listener inside the holder;
add 1 variable in your store class to stored value if you already clicked on that item or not..
the ilustration like this , i set variable isSelected in store :
private boolean mSelected=false;
public boolean getIsSelected(){
return this.mSelected;
}
public void setIsSelected(boolean mSelected){
this.mSelected=mSelected;
}
and then in your onClick method just add stock.setIsSelected(!stock.getIsSelected()) after if conditional and set your if conditional to read boolean from stock.getIsSelected() and the last, just remove variable isCategoryOpened from your holder.
public void onClick(View v) {
final int newWidth;
final int startWidth;
final int startArrowAngle;
final int newArrowAngle;
if (stock.getIsSelected()) {
newWidth = holder.stockRow.getWidth() - holder.categoryLayoutParams.leftMargin - holder.arrowImage.getWidth() - ((LayoutParams) holder.arrowImage.getLayoutParams()).rightMargin - holder.categoryIconSeparator.getWidth();
startWidth = collapsedCategoryWidth;
startArrowAngle = 0;
newArrowAngle = 180;
} else {
newWidth = collapsedCategoryWidth;
startWidth = holder.categoryImage.getWidth();
startArrowAngle = 180;
newArrowAngle = 0;
}
stock.setIsSelected(!stock.getIsSelected())
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
holder.categoryLayoutParams.width = startWidth + (int) ((newWidth - startWidth) * interpolatedTime);
//MAYBE PROBLEM HERE??
holder.categoryImage.setLayoutParams(holder.categoryLayoutParams);
holder.arrowIcon.setRotationY(startArrowAngle + (newArrowAngle - startArrowAngle) * interpolatedTime);
}
};
a.setDuration(500);
holder.categoryImage.startAnimation(a);
}
Correct me if i'm wrong :)
Problem Solved, the thing that was causing all this misfunctions was the holder.companyName.requestFocus() that I was calling to get the marquee working in the TextView.
It comes out I don't need the requestFocus() to get it working, and that it was the cause of the problem.

Android simple tabs with toolbar

I've been struggling with tab implementation in my application and seen a lot of resources on the matter but nothing appears to be working for me. I just want 4 simple tabs with icons above my toolbar, that's all. Can someone help me out on achieving this?
Here's my code if needed:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class ProjectCreateScreen extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondary_layout1);
Toolbar toolbar = (Toolbar) findViewById(R.id.AwesomeBar);
setSupportActionBar(toolbar);
}
public void displayProjectOptions (View view) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_primary, menu);
return true;
}
final ArrayList<String> listItems=new ArrayList<String>();
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.addButton) {
final TextView noProject = (TextView) findViewById(R.id.NOPROJECT);
final ListAdapter addAdapter = new ArrayAdapter<String>(this,
R.layout.list_item, R.id.listFrame, listItems);
final ListView lv = (ListView) findViewById(R.id.lv);
lv.setAdapter(addAdapter);
noProject.setVisibility(View.GONE);
lv.setVisibility(View.VISIBLE);
listItems.add("New Project");
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent switchToEdit = new Intent(ProjectCreateScreen.this,
teamCreateScreen.class);
startActivity(switchToEdit);
}
});
}
return super.onOptionsItemSelected(item);
}
}
And xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rl">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/actionBarSize"
android:id="#+id/AwesomeBar"
android:background="#color/custom_white">
</android.support.v7.widget.Toolbar>
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="#string/noProjectsNotice"
android:id="#+id/NOPROJECT"
android:gravity="center"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="16sp"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/AwesomeBar"
android:id="#+id/lv"
android:visibility="invisible">
</ListView>
If you are using toolbar you need to use SlidingTabLayout for tabs in toolbar as follows
TabFragment.java
public class TabFragment extends Fragment {
private SlidingTabLayout mSlidingTabLayout;
private MyActivityAdapter mAdapter;
private ViewPager mViewPager;
private Menu mMenu;
private ScreenNames mScreenName = ScreenNames.UNRAVELING_ME;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_swipe, container, false);
mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setCustomTabView(R.layout.tab_indicator, android.R.id.text1);
mSlidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.unravel_secondary_red));
mSlidingTabLayout.setDistributeEvenly(true);
mSlidingTabLayout.setBackgroundColor(Color.parseColor("#F7F7F7"));
mSlidingTabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener (){
#Override
public void onPageSelected(int position)
{
if(position == 0){
}
else {
}
}
#Override
public void onPageScrollStateChanged(int state)
{
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
});
mViewPager = (ViewPager) view.findViewById(R.id.pager);
mAdapter = new MyActivityAdapter(this, getChildFragmentManager());
mViewPager.setAdapter(mAdapter);
mSlidingTabLayout.setViewPager(mViewPager);
return view;
}
fragment_swipe.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.unravel.widget.SlidingTabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"/>
</LinearLayout>
MyActivityAdapter.java
public class MyActivityAdapter extends FragmentPagerAdapter {
private MyActivityFragment mFragment;
public MyActivityAdapter(MyActivityFragment fragment, FragmentManager fm) {
super(fm);
mFragment = fragment;
}
#Override
public Fragment getItem(int i) {
if (i == 0) {
return new fragment1();
}
else {
return new fragment2();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "first tab";
} else {
return "second tab";
}
}
}
Fragment1.java
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}
Fragment2.java
public class Fragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}
SlidingTabLayout.java
public class SlidingTabLayout extends HorizontalScrollView {
/**
* Allows COMPLETE control over the colors drawn in the tab layout. Set with
* {#link #setCustomTabColorizer(TabColorizer)}.
*/
public interface TabColorizer {
/**
* #return return the color of the indicator used when {#code position} is selected.
*/
int getIndicatorColor(int position);
}
private static final int TITLE_OFFSET_DIPS = 24;
private static final int TAB_VIEW_PADDING_DIPS = 16;
private static final int TAB_VIEW_TEXT_SIZE_SP = 18;
private int mTitleOffset;
private int mTabViewLayoutId;
private int mTabViewTextViewId;
private boolean mDistributeEvenly;
private ViewPager mViewPager;
private SparseArray<String> mContentDescriptions = new SparseArray<String>();
private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;
private final SlidingTabStrip mTabStrip;
public SlidingTabLayout(Context context) {
this(context, null);
}
public SlidingTabLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Disable the Scroll Bar
setHorizontalScrollBarEnabled(false);
// Make sure that the Tab Strips fills this View
setFillViewport(true);
mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);
mTabStrip = new SlidingTabStrip(context);
addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
/**
* Set the custom {#link TabColorizer} to be used.
*
* If you only require simple custmisation then you can use
* {#link #setSelectedIndicatorColors(int...)} to achieve
* similar effects.
*/
public void setCustomTabColorizer(TabColorizer tabColorizer) {
mTabStrip.setCustomTabColorizer(tabColorizer);
}
public void setDistributeEvenly(boolean distributeEvenly) {
mDistributeEvenly = distributeEvenly;
}
/**
* Sets the colors to be used for indicating the selected tab. These colors are treated as a
* circular array. Providing one color will mean that all tabs are indicated with the same color.
*/
public void setSelectedIndicatorColors(int... colors) {
mTabStrip.setSelectedIndicatorColors(colors);
}
/**
* Set the {#link ViewPager.OnPageChangeListener}. When using {#link SlidingTabLayout} you are
* required to set any {#link ViewPager.OnPageChangeListener} through this method. This is so
* that the layout can update it's scroll position correctly.
*
* #see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener)
*/
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
mViewPagerPageChangeListener = listener;
}
/**
* Set the custom layout to be inflated for the tab views.
*
* #param layoutResId Layout id to be inflated
* #param textViewId id of the {#link TextView} in the inflated view
*/
public void setCustomTabView(int layoutResId, int textViewId) {
mTabViewLayoutId = layoutResId;
mTabViewTextViewId = textViewId;
}
/**
* Sets the associated view pager. Note that the assumption here is that the pager content
* (number of tabs and tab titles) does not change after this call has been made.
*/
public void setViewPager(ViewPager viewPager) {
mTabStrip.removeAllViews();
mViewPager = viewPager;
if (viewPager != null) {
viewPager.setOnPageChangeListener(new InternalViewPagerListener());
populateTabStrip();
}
}
/**
* Create a default view to be used for tabs. This is called if a custom tab view is not set via
* {#link #setCustomTabView(int, int)}.
*/
protected TextView createDefaultTabView(Context context) {
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
outValue, true);
textView.setBackgroundResource(outValue.resourceId);
textView.setAllCaps(true);
int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
textView.setPadding(padding, padding, padding, padding);
return textView;
}
private void populateTabStrip() {
final PagerAdapter adapter = mViewPager.getAdapter();
final View.OnClickListener tabClickListener = new TabClickListener();
for (int i = 0; i < adapter.getCount(); i++) {
View tabView = null;
TextView tabTitleView = null;
if (mTabViewLayoutId != 0) {
// If there is a custom tab view layout id set, try and inflate it
tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
false);
tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
}
if (tabView == null) {
tabView = createDefaultTabView(getContext());
}
if (tabTitleView == null && TextView.class.isInstance(tabView)) {
tabTitleView = (TextView) tabView;
}
if (mDistributeEvenly) {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
lp.width = 0;
lp.weight = 1;
}
tabTitleView.setText(adapter.getPageTitle(i));
tabView.setOnClickListener(tabClickListener);
String desc = mContentDescriptions.get(i, null);
if (desc != null) {
tabView.setContentDescription(desc);
}
mTabStrip.addView(tabView);
if (i == mViewPager.getCurrentItem()) {
tabView.setSelected(true);
}
}
}
public void setContentDescription(int i, String desc) {
mContentDescriptions.put(i, desc);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mViewPager != null) {
scrollToTab(mViewPager.getCurrentItem(), 0);
}
}
private void scrollToTab(int tabIndex, int positionOffset) {
final int tabStripChildCount = mTabStrip.getChildCount();
if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
return;
}
View selectedChild = mTabStrip.getChildAt(tabIndex);
if (selectedChild != null) {
int targetScrollX = selectedChild.getLeft() + positionOffset;
if (tabIndex > 0 || positionOffset > 0) {
// If we're not at the first child and are mid-scroll, make sure we obey the offset
targetScrollX -= mTitleOffset;
}
scrollTo(targetScrollX, 0);
}
}
private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
private int mScrollState;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int tabStripChildCount = mTabStrip.getChildCount();
if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
return;
}
mTabStrip.onViewPagerPageChanged(position, positionOffset);
View selectedTitle = mTabStrip.getChildAt(position);
int extraOffset = (selectedTitle != null)
? (int) (positionOffset * selectedTitle.getWidth())
: 0;
scrollToTab(position, extraOffset);
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
positionOffsetPixels);
}
}
#Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrollStateChanged(state);
}
}
#Override
public void onPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mTabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
mTabStrip.getChildAt(i).setSelected(position == i);
}
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageSelected(position);
}
}
}
private class TabClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
if (v == mTabStrip.getChildAt(i)) {
mViewPager.setCurrentItem(i);
return;
}
}
}
}
}
SlidingTabStrip.java
class SlidingTabStrip extends LinearLayout {
private static final int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 0;
private static final byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0x26;
private static final int SELECTED_INDICATOR_THICKNESS_DIPS = 2;
private static final int DEFAULT_SELECTED_INDICATOR_COLOR = 0xFF33B5E5;
private final int mBottomBorderThickness;
private final Paint mBottomBorderPaint;
private final int mSelectedIndicatorThickness;
private final Paint mSelectedIndicatorPaint;
private final int mDefaultBottomBorderColor;
private int mSelectedPosition;
private float mSelectionOffset;
private SlidingTabLayout.TabColorizer mCustomTabColorizer;
private final SimpleTabColorizer mDefaultTabColorizer;
SlidingTabStrip(Context context) {
this(context, null);
}
SlidingTabStrip(Context context, AttributeSet attrs) {
super(context, attrs);
setWillNotDraw(false);
final float density = getResources().getDisplayMetrics().density;
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.colorForeground, outValue, true);
final int themeForegroundColor = outValue.data;
mDefaultBottomBorderColor = setColorAlpha(themeForegroundColor,
DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);
mDefaultTabColorizer = new SimpleTabColorizer();
mDefaultTabColorizer.setIndicatorColors(DEFAULT_SELECTED_INDICATOR_COLOR);
mBottomBorderThickness = (int) (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
mBottomBorderPaint = new Paint();
mBottomBorderPaint.setColor(mDefaultBottomBorderColor);
mSelectedIndicatorThickness = (int) (SELECTED_INDICATOR_THICKNESS_DIPS * density);
mSelectedIndicatorPaint = new Paint();
}
void setCustomTabColorizer(SlidingTabLayout.TabColorizer customTabColorizer) {
mCustomTabColorizer = customTabColorizer;
invalidate();
}
void setSelectedIndicatorColors(int... colors) {
// Make sure that the custom colorizer is removed
mCustomTabColorizer = null;
mDefaultTabColorizer.setIndicatorColors(colors);
invalidate();
}
void onViewPagerPageChanged(int position, float positionOffset) {
mSelectedPosition = position;
mSelectionOffset = positionOffset;
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
final int height = getHeight();
final int childCount = getChildCount();
final SlidingTabLayout.TabColorizer tabColorizer = mCustomTabColorizer != null
? mCustomTabColorizer
: mDefaultTabColorizer;
// Thick colored underline below the current selection
if (childCount > 0) {
View selectedTitle = getChildAt(mSelectedPosition);
int left = selectedTitle.getLeft();
int right = selectedTitle.getRight();
int color = tabColorizer.getIndicatorColor(mSelectedPosition);
if (mSelectionOffset > 0f && mSelectedPosition < (getChildCount() - 1)) {
int nextColor = tabColorizer.getIndicatorColor(mSelectedPosition + 1);
if (color != nextColor) {
color = blendColors(nextColor, color, mSelectionOffset);
}
// Draw the selection partway between the tabs
View nextTitle = getChildAt(mSelectedPosition + 1);
left = (int) (mSelectionOffset * nextTitle.getLeft() +
(1.0f - mSelectionOffset) * left);
right = (int) (mSelectionOffset * nextTitle.getRight() +
(1.0f - mSelectionOffset) * right);
}
mSelectedIndicatorPaint.setColor(color);
canvas.drawRect(left, height - mSelectedIndicatorThickness, right,height, mSelectedIndicatorPaint);
}
// Thin underline along the entire bottom edge
canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint);
}
/**
* Set the alpha value of the {#code color} to be the given {#code alpha} value.
*/
private static int setColorAlpha(int color, byte alpha) {
return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
}
/**
* Blend {#code color1} and {#code color2} using the given ratio.
*
* #param ratio of which to blend. 1.0 will return {#code color1}, 0.5 will give an even blend,
* 0.0 will return {#code color2}.
*/
private static int blendColors(int color1, int color2, float ratio) {
final float inverseRation = 1f - ratio;
float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
return Color.rgb((int) r, (int) g, (int) b);
}
private static class SimpleTabColorizer implements SlidingTabLayout.TabColorizer {
private int[] mIndicatorColors;
#Override
public final int getIndicatorColor(int position) {
return mIndicatorColors[position % mIndicatorColors.length];
}
void setIndicatorColors(int... colors) {
mIndicatorColors = colors;
}
}
}

Categories

Resources