Image Swipe not working - android

I have a GridView in which I show the images. On the click of the Image the Image expands to full screen. Everything is fine up to this. Now I want to swipe these Image. When I swipe the Image, nothing happens. It remains as it is. Can anyone help me, whats wrong in the code. Below is my code and layout files.
public class MainActivity extends Activity {
private GridView gridview;
private int j = 0;
private final GestureDetector detector = new GestureDetector(new SwipeGestureDetector());
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
// Create Array thumbs resource id's:
private int thumb[] = { R.drawable.logowhite,
R.drawable.logo_bg,
R.drawable.logowhite,
R.drawable.logo_bg,
R.drawable.logowhite,
R.drawable.logo_bg, };
private ImageView expandedImageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize the variables:
gridview = (GridView) findViewById(R.id.gridView);
// Set an Adapter to the ListView
gridview.setAdapter(new ImageAdapter(this));
// Set on item click listener to the ListView
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,
long id) {
j = pos;
setContentView(R.layout.slide_image);
expandedImageView = (ImageView) findViewById(R.id.imageViewslides);
expandedImageView.setBackgroundResource(thumb[pos]);
}
});
}
// Create an Adapter Class extending the BaseAdapter
class ImageAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
public ImageAdapter(MainActivity activity) {
// TODO Auto-generated constructor stub
layoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// Set the count value to the total number of items in the Array
return thumb.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Inflate the item layout and set the views
View listItem = convertView;
int pos = position;
if (listItem == null) {
listItem = layoutInflater.inflate(R.layout.grid_item, null);
}
// Initialize the views in the layout
ImageView imgView = (ImageView) listItem.findViewById(R.id.thumb);
// Set the views in the layout
imgView.setBackgroundResource(thumb[pos]);
return listItem;
}
}
private class SwipeGestureDetector extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
if(thumb.length>j) {
j++;
if(j < thumb.length){
expandedImageView.setImageResource(thumb[j]);
return true;
}
else {
j = 0;
expandedImageView.setImageResource(thumb[j]);
return true;
}
}
}
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
if(j>0){
j--;
expandedImageView.setImageResource(thumb[j]);
return true;
}
else {
j = thumb.length-1;
expandedImageView.setImageResource(thumb[j]);
return true;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
}
Layout File are: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mukesh.gridviewimageswipe.MainActivity">
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<GridView
android:id="#+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="80dp"
android:horizontalSpacing="10dp"
android:numColumns="2"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" >
</GridView>
<ImageView
android:id="#+id/expanded_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/app_name"
android:visibility="invisible" />
</FrameLayout>
</RelativeLayout>
grid_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp" >
<ImageView
android:id="#+id/thumb"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_centerHorizontal="true"
android:contentDescription="#string/app_name" />
</RelativeLayout>
slide_image.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/imageViewslide"
android:layout_width="fill_parent"
android:layout_height="420dp"
android:orientation="horizontal"
android:layout_below="#+id/textq">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageViewslides">
</ImageView>
</LinearLayout>
</LinearLayout>

Related

Instagram like scroll in custom gallery

Can anyone please suggest how to implement the following in my droid app?
I've created a custom gallery, and when an image is selected, I show a preview of the image exactly like instagram. Now when I scoll up, I need some 20% of the image view to stick to the top like this:
I'm right now using, Observablegrid view, which is of not that much use!
Please suggest any ideas. Thanks!
Here is my answer using the same Observablegridview, which got to work after some analysis and modifications while scrolling the grid.
For the grid of image to be displayed, use this ObservableGridView.java
Here is the xml layout
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/mainFrame">
<com.sampleapp.Observablescroll.ObservableGridView
android:id="#+id/camera_gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:numColumns="4" />
<RelativeLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/gallery_lay"
android:layout_width="wrap_content"
android:layout_height="365dp"
android:background="#color/black"
android:orientation="vertical">
<com.fenchtose.nocropper.CropperImageView
android:id="#+id/gallery_click_img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:scaleType="centerCrop"
app:grid_color="#color/action_bar_color" />
</RelativeLayout>
<View
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="300dp" />
</RelativeLayout>
</FrameLayout>
In your java class, implement ObservableScrollViewCallbacks
mHeaderView = (RelativeLayout) rootview.findViewById(R.id.header);
mToolbarView = rootview.findViewById(R.id.toolbar);
camera_gridView = (ObservableGridView) rootview.findViewById(R.id.camera_gridView);
LayoutInflater inflaters = LayoutInflater.from(getActivity());
camera_gridView.addHeaderView(inflaters.inflate(R.layout.image_holder_view, camera_gridView, false));
// view that leaves 300dp space to display the selected image from the grid
camera_gridView.addHeaderView(inflaters.inflate(R.layout.sticky_tool_bar_view, camera_gridView, false));
// a sticky view with action bar's height, so that the grid doesn't scroll above this
camera_gridView.setScrollViewCallbacks(this);
//overridden methods
#Override
public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
if (dragging) {
int toolbarHeight = mToolbarView.getHeight();
// int toolbarHeight = 300;
if (camera_gridView.getCurrentScrollY() == 0) {
showToolbar();
}
if (firstScroll) {
float currentHeaderTranslationY = ViewHelper.getTranslationY(mHeaderView);
if (-toolbarHeight < currentHeaderTranslationY) {
mBaseTranslationY = scrollY;
}
}
float headerTranslationY = ScrollUtils.getFloat(-(scrollY - mBaseTranslationY), -toolbarHeight, 0);
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewHelper.setTranslationY(mHeaderView, headerTranslationY);
}
}
#Override
public void onDownMotionEvent() {
}
#Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
mBaseTranslationY = 0;
if (scrollState == ScrollState.DOWN) {
int toolbarHeight = mToolbarView.getHeight();
if (camera_gridView.getCurrentScrollY() == 0) {
showToolbar();
}
int scrollY = camera_gridView.getCurrentScrollY();
if (toolbarHeight <= scrollY) {
hideToolbar();
} else {
showToolbar();
}
} else if (scrollState == ScrollState.UP) {
int toolbarHeight = mToolbarView.getHeight();
int scrollY = camera_gridView.getCurrentScrollY();
if (toolbarHeight <= scrollY) {
System.out.println("++++upif" + scrollY);
hideToolbar();
} else {
System.out.println("++++upelse" + scrollY);
showToolbar();
}
if (camera_gridView.getCurrentScrollY() == 0) {
showToolbar();
}
} else {
if (!toolbarIsShown() && !toolbarIsHidden()) {
showToolbar();
}
}
}
//method to show the toolbar
private void showToolbar() {
float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
if (headerTranslationY != 0) {
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewPropertyAnimator.animate(mHeaderView).translationY(0).setDuration(200).start();
}
}
//method to hide the toolbar
private void hideToolbar() {
float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
int toolbarHeight = mToolbarView.getHeight();
if (headerTranslationY != -toolbarHeight) {
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewPropertyAnimator.animate(mHeaderView).translationY(-toolbarHeight).setDuration(200).start();
}
}
private boolean toolbarIsShown() {
return ViewHelper.getTranslationY(mHeaderView) == 0;
}
private boolean toolbarIsHidden() {
return ViewHelper.getTranslationY(mHeaderView) == -mToolbarView.getHeight();
}
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_below="#+id/mainFrame">
<RelativeLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/gallery_lay"
android:layout_width="wrap_content"
android:layout_height="365dp"
android:background="#color/black"
android:orientation="vertical">
<com.fenchtose.nocropper.CropperView
android:id="#+id/imageview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff282828"
app:nocropper__grid_color="#color/colorAccent"
app:nocropper__grid_opacity="0.8"
app:nocropper__grid_thickness="0.8dp"
app:nocropper__padding_color="#color/colorAccent" />
</RelativeLayout>
</RelativeLayout>
<com.myapp.Util.ObservableGridView
android:id="#+id/camera_gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:numColumns="4" />
</FrameLayout>
And below is java implementation
public class GalleryFragmentTest2 extends Fragment implements View.OnClickListener, ImageGridItemListner, ObservableScrollViewCallbacks {
private static final String TAG = "GalleryFragment";
CropperView mImageView;
RecyclerView recImgHolder;
CoordinatorLayout container;
AppBarLayout app_bar_main;
private Bitmap originalBitmap;
private Bitmap mBitmap;
private boolean isSnappedToCenter = false;
private int rotationCount = 0;
//constants
private static final int NUM_GRID_COLUMNS = 4;
//widgets
private GridView gridView;
private ImageView galleryImage;
private Spinner directorySpinner;
//vars
private ArrayList<Model_images> directories;
private String mAppend = "file://";
private String mSelectedImage;
RelativeLayout mHeaderView, relCropperView;
ObservableGridView camera_gridView;
private int mBaseTranslationY;
private void initImageLoader() {
UniversalImageLoader universalImageLoader = new UniversalImageLoader(getContext());
ImageLoader.getInstance().init(universalImageLoader.getConfig());
}
#SuppressLint("ClickableViewAccessibility")
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.gallery_test2, container, false);
mHeaderView = (RelativeLayout) view.findViewById(R.id.header);
View mToolbarView = view.findViewById(R.id.toolbar);
camera_gridView = (ObservableGridView) view.findViewById(R.id.camera_gridView);
LayoutInflater inflaters = LayoutInflater.from(getActivity());
View view1 = inflaters.inflate(R.layout.snippet_top_gallerytoolbar,camera_gridView,false);
View view2 = inflaters.inflate(R.layout.rec_img_test,camera_gridView,false);
camera_gridView.addHeaderView(inflaters.inflate(R.layout.snippet_top_gallerytoolbar,camera_gridView,false));
// view that leaves 300dp space to display the selected image from the grid
camera_gridView.addHeaderView(inflaters.inflate(R.layout.rec_img_test,camera_gridView,false));
// a sticky view with action bar's height, so that the grid doesn't scroll above this
camera_gridView.setScrollViewCallbacks(this);
mImageView = (CropperView) view.findViewById(R.id.imageview);
recImgHolder = view2.findViewById(R.id.recImgHolder);
LinearLayoutManager manager = new GridLayoutManager(getActivity(), 4);
recImgHolder.setLayoutManager(manager);
recImgHolder.setHasFixedSize(true);
recImgHolder.setItemViewCacheSize(20);
recImgHolder.setDrawingCacheEnabled(true);
recImgHolder.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
TextView nextScreen = (TextView) view.findViewById(R.id.tvNext);
directorySpinner = (Spinner) view1.findViewById(R.id.spinnerDirectory);
directories = new ArrayList<>();
Log.d(TAG, "onCreateView: started.");
initImageLoader();
init();
mImageView.setDebug(true);
mImageView.setGestureEnabled(true);
mImageView.setGridCallback(new CropperView.GridCallback() {
#Override
public boolean onGestureStarted() {
return true;
}
#Override
public boolean onGestureCompleted() {
return false;
}
});
return view;
}
private void init() {
try {
FilePaths filePaths = new FilePaths();
directories = new ArrayList<>();
//check for other folders indide "/storage/emulated/0/pictures"
directories = FileSearch.fn_imagespath(Objects.requireNonNull(getContext()), filePaths.PICTURES);
ArrayList<String> directoryNames = new ArrayList<>();
for (int i = 0; i < directories.size(); i++) {
int index = directories.get(i).getStr_folder().lastIndexOf("/");
String string = directories.get(i).getStr_folder().substring(index + 1);
directoryNames.add(string);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, directoryNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
directorySpinner.setAdapter(adapter);
directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected: " + directories.get(position));
//setup our image grid for the directory chosen
setupGridView(directories.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}catch (Exception e){
e.printStackTrace();
}
}
private void setupGridView(Model_images selectedDirectory) {
try {
final ArrayList<String> imgURLs = selectedDirectory.getAl_imagepath();
//use the grid adapter to adapter the images to gridview
GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, mAppend, imgURLs, (ImageGridItemListner) this);
adapter.setGridItemListner(this);
recImgHolder.setAdapter(adapter);
//set the first image to be displayed when the activity fragment view is inflated
try {
setImage(imgURLs.get(0), mAppend);
} catch (ArrayIndexOutOfBoundsException e) {
Log.e(TAG, "setupGridView: ArrayIndexOutOfBoundsException: " + e.getMessage());
}
}catch (Exception e){
e.printStackTrace();
Toast.makeText(getActivity(), ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void setImage(String imgURL, String append) {
Log.d(TAG, "setImage: setting image");
ImageLoader imageLoader = ImageLoader.getInstance();
Bitmap bmp = imageLoader.loadImageSync(append + imgURL);
mImageView.setImageBitmap(bmp);
mBitmap = bmp;
originalBitmap = bmp;
}
private void rotateImage() {
if (mBitmap == null) {
Log.e(TAG, "bitmap is not loaded yet");
return;
}
mBitmap = BitmapUtils.rotateBitmap(mBitmap, 90);
mImageView.setImageBitmap(mBitmap);
rotationCount++;
}
private void snapImage() {
if (isSnappedToCenter) {
mImageView.cropToCenter();
} else {
mImageView.fitToCenter();
}
isSnappedToCenter = !isSnappedToCenter;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.rotate_button:
rotateImage();
break;
case R.id.snap_button:
snapImage();
break;
}
}
#Override
public void onImageGridItemClick(String imgURL) {
try {
setImage(imgURL, mAppend);
} catch (ArrayIndexOutOfBoundsException e) {
Log.e(TAG, "setupGridView: ArrayIndexOutOfBoundsException: " + e.getMessage());
}
}
//overridden methods
#Override
public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
if (dragging) {
int toolbarHeight = mHeaderView.getHeight();
// int toolbarHeight = 300;
if (camera_gridView.getCurrentScrollY() == 0) {
showToolbar();
}
if (firstScroll) {
float currentHeaderTranslationY = ViewHelper.getTranslationY(mHeaderView);
if (-toolbarHeight < currentHeaderTranslationY) {
mBaseTranslationY = scrollY;
}
}
float headerTranslationY = ScrollUtils.getFloat(-(scrollY - mBaseTranslationY), -toolbarHeight, 0);
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewHelper.setTranslationY(mHeaderView, headerTranslationY);
}
}
#Override
public void onDownMotionEvent() {
}
#Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
mBaseTranslationY = 0;
if (scrollState == ScrollState.DOWN) {
int toolbarHeight = mHeaderView.getHeight();
if (camera_gridView.getCurrentScrollY() == 0) {
showToolbar();
}
int scrollY = camera_gridView.getCurrentScrollY();
if (toolbarHeight <= scrollY) {
hideToolbar();
} else {
showToolbar();
}
} else if (scrollState == ScrollState.UP) {
int toolbarHeight = mHeaderView.getHeight();
int scrollY = camera_gridView.getCurrentScrollY();
if (toolbarHeight <= scrollY) {
System.out.println("++++upif" + scrollY);
hideToolbar();
} else {
System.out.println("++++upelse" + scrollY);
showToolbar();
}
if (camera_gridView.getCurrentScrollY() == 0) {
showToolbar();
}
} else {
if (!toolbarIsShown() && !toolbarIsHidden()) {
showToolbar();
}
}
}
//method to show the toolbar
private void showToolbar() {
float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
if (headerTranslationY != 0) {
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewPropertyAnimator.animate(mHeaderView).translationY(0).setDuration(200).start();
}
}
//method to hide the toolbar
private void hideToolbar() {
float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
int toolbarHeight = mHeaderView.getHeight();
if (headerTranslationY != -toolbarHeight) {
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewPropertyAnimator.animate(mHeaderView).translationY(-toolbarHeight).setDuration(200).start();
}
}
private boolean toolbarIsShown() {
return ViewHelper.getTranslationY(mHeaderView) == 0;
}
private boolean toolbarIsHidden() {
return ViewHelper.getTranslationY(mHeaderView) == -mHeaderView.getHeight();
}
}
inflated headerview in observable is
layout :- snippet_top_gallerytoolbar
<android.support.design.widget.AppBarLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorPrimary"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.Toolbar
android:id="#+id/profileToolBar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/ivCloseShare"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginEnd="20dp"
android:src="#drawable/ic_back" />
<Spinner
android:id="#+id/spinnerDirectory"
android:layout_width="#dimen/_120sdp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/ivCloseShare"
android:gravity="center_vertical"
android:text="Gallery"
android:textColor="#color/black"
android:textSize="20sp">
</Spinner>
<TextView
android:id="#+id/tvNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="15dp"
android:text="#string/string_next"
android:textColor="#color/white"
android:textSize="20sp" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
second added headerview to observablegrid
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recImgHolder"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
i am getting view like below

How can i hide the first item when click the second item in ListView using Expandanimation?

I Using to develop listview acts like the expandablelistview its works fine but one problem wil be there when i click second item first item does not close
I am using animation class like
ExpandAnimation.java
public ExpandAnimation(View view, int duration) {
setDuration(duration);
mAnimatedView = view;
mViewLayoutParams = (LayoutParams) view.getLayoutParams();
// decide to show or hide the view
mIsVisibleAfter = (view.getVisibility() == View.VISIBLE);
mMarginStart = mViewLayoutParams.bottomMargin;
mMarginEnd = (mMarginStart == 0 ? (0- view.getHeight()) : 0);
view.setVisibility(View.VISIBLE);
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
if (interpolatedTime < 1.0f) {
// Calculating the new bottom margin, and setting it
mViewLayoutParams.bottomMargin = mMarginStart
+ (int) ((mMarginEnd - mMarginStart) * interpolatedTime);
// Invalidating the layout, making us seeing the changes we made
mAnimatedView.requestLayout();
// Making sure we didn't run the ending before (it happens!)
} else if (!mWasEndedAlready) {
mViewLayoutParams.bottomMargin = mMarginEnd;
mAnimatedView.requestLayout();
if (mIsVisibleAfter) {
mAnimatedView.setVisibility(View.GONE);
}
mWasEndedAlready = true;
}
}
ExpandAnimationDemo.java like
public class ExpandAnimationDemo extends Activity {
// Boolean sameItemClicked=false;
boolean boolitem = false;
View PreviousToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //To change body of overridden methods use File | Settings | File Templates.
setContentView(R.layout.main);
ListView list = (ListView)findViewById(R.id.udiniList);
// Creating the list adapter and populating the list
ArrayAdapter<String> listAdapter = new CustomListAdapter(this, R.layout.list_item);
for (int i=0; i<20;i++)
listAdapter.add("udini"+i);
list.setAdapter(listAdapter);
// Creating an item click listener, to open/close our toolbar for each item
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#SuppressWarnings("unused")
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
View toolbar = view.findViewById(R.id.toolbar);
// Creating the expand animation for the item
ExpandAnimation expandAni = new ExpandAnimation(toolbar, 500);
// Start the animation on the toolbar
toolbar.startAnimation(expandAni);
}
});
}
/**
* A simple implementation of list adapter.
*/
class CustomListAdapter extends ArrayAdapter<String> {
public CustomListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_item, null);
}
((TextView)convertView.findViewById(R.id.title)).setText(getItem(position));
// Resets the toolbar to be closed
View toolbar = convertView.findViewById(R.id.toolbar);
((LinearLayout.LayoutParams) toolbar.getLayoutParams()).bottomMargin = -50;
toolbar.setVisibility(View.GONE);
return convertView;
}
}
}
Myxml file is list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="#+id/title"
android:padding="20dip"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<!--***********************-->
<!--*** TOOLBAR LAYOUT ****-->
<!--***********************-->
<LinearLayout android:id="#+id/toolbar"
android:layout_marginBottom="-50dip"
android:visibility="gone"
android:layout_height="50dip"
android:layout_width="fill_parent">
<Button android:id="#+id/doSomething1"
android:layout_height="50dip"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:text="Harder"/>
<Button android:id="#+id/doSomething2"
android:layout_height="50dip"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:text="Better"/>
<Button android:id="#+id/doSomething3"
android:layout_height="50dip"
android:layout_width="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Faster"/>
<Button android:id="#+id/doSomething4"
android:layout_height="50dip"
android:layout_width="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Stronger"/>
</LinearLayout>
</LinearLayout>
This is developed based on this link
https://github.com/Udinic/SmallExamples/tree/master/ExpandAnimationExample
this works fine but when select second item first item does not close please guide how to implement my requirement advance thanks
is there any solutions plz gudide me
Check the following.
mExpandableListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
int len = menuAdapter.getGroupCount();
for (int i = 0; i < len; i++) {
if (i != groupPosition
&& menuAdapter.getChildrenCount(i) > 0) {
mExpandableListView.collapseGroup(i);
}
} }
});

How to start an animation from a custom Gesture Listener?

I've written a small activity that uses fragments with a ViewPager to show images.
I've also implemented a custom GestureListener to catch the swipe up and swipe down gestures without interferring with the ViewPager's own gesture handling. What I want to achieve is to show a layout when the user swipes down.
Problem is, I haven't found out how to execute the animation when the gesture listener detects the swipe down gesture.
EDIT: Added context and view to MyGestureListener to reference the view and context. Logging shows that the gesture is detected correctly and the view inside MyGestureListener is the correct one but nothing gets animated.
Code as follows.
Activity:
public class MainActivity extends FragmentActivity {
private GestureDetector gestureDetector;
private ViewPager vwpMain;
private PagerAdapter pgaMain;
private RelativeLayout layout;
private LinearLayout topLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (RelativeLayout) findViewById(R.id.container);
topLayout = (LinearLayout) findViewById(R.id.topPanel);
vwpMain = (ViewPager) findViewById(R.id.vwpMain);
pgaMain = new MyPagerAdapter(getSupportFragmentManager());
vwpMain.setAdapter(pgaMain);
gestureDetector = new GestureDetector(this, new MyGestureListener(getApplicationContext(), topLayout));
layout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
});
}
public boolean dispatchTouchEvent(MotionEvent ev) {
super.dispatchTouchEvent(ev);
return gestureDetector.onTouchEvent(ev);
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int pos) {
return ImageFragment.create(pos);
}
#SuppressLint("SdCardPath")
#Override
public int getCount() {
File f = new File("/mnt/sdcard/FragmentImages/");
return f.listFiles().length;
}
}
Fragment:
public class ImageFragment extends Fragment {
private int pageNumber;
private ImageView i;
public static ImageFragment create(int pageNumber) {
ImageFragment f = new ImageFragment();
Bundle b = new Bundle();
b.putInt("index", pageNumber);
int indice = pageNumber + 1;
String ruta = Environment.getExternalStorageDirectory().getPath()
+ "/FragmentImages/imagen_" + indice + ".jpg";
b.putString("file", ruta);
f.setArguments(b);
return f;
}
public ImageFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt("index");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout containing a title and body text.
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_image, container, false);
i = (ImageView) rootView.findViewById(R.id.imgImagen);
BitmapWorkerTask task = new BitmapWorkerTask(i);
task.execute(getArguments().getString("file"));
return rootView;
}
public int getPageNumber() {
return pageNumber;
}
public class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private String data;
public BitmapWorkerTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
data = params[0];
return BitmapFactory.decodeFile(data);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
}
Gesture listener:
public class MyGestureListener extends SimpleOnGestureListener {
private static final int SWIPE_MIN_DISTANCE = 75;
private static final int SWIPE_MAX_OFF_PATH = 100;
private static final int SWIPE_THRESHOLD_VELOCITY = 50;
public Context context;
public View view;
public MyGestureListener() {
super();
context = _context;
view = _view;
}
#Override
public boolean onDown(MotionEvent event) {
return true;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
float dX = e2.getX() - e1.getX();
float dY = e1.getY() - e2.getY();
if (Math.abs(dY) < SWIPE_MAX_OFF_PATH
&& Math.abs(velocityX) >= SWIPE_THRESHOLD_VELOCITY
&& Math.abs(dX) >= SWIPE_MIN_DISTANCE) {
if (dX > 0) {
Log.d("Fragment", "Swiping right");
} else {
Log.d("Fragment", "Swiping left");
}
} else if (Math.abs(dX) < SWIPE_MAX_OFF_PATH
&& Math.abs(velocityY) >= SWIPE_THRESHOLD_VELOCITY
&& Math.abs(dY) >= SWIPE_MIN_DISTANCE) {
if (dY > 0) {
Log.d("Fragment", "Swiping up");
} else {
Log.d("Fragment", "Swiping down");
Animation a = AnimationUtils.loadAnimation(context, R.anim.show_top);
Log.d("Fragment", view.toString());
view.startAnimation(a);
}
}
return false;
}
}
Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/topPanel"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="horizontal"
android:visibility="gone" >
<TextView
android:id="#+id/topPanelTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/topPanelText"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#android:color/black" />
</LinearLayout>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/vwpMain"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Animation:
<?xml version="1.0" encoding="utf-8"?>
<translate
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="500"
android:fromYDelta="-100%"
android:toYDelta="0%" >
</translate>
Found a solution. I changed the swiping down detection code to this:
Log.d("Fragment", "Swiping down");
Animation showTopPanel = AnimationUtils.loadAnimation(context, R.anim.show_top);
topView.bringToFront();
topView.setVisibility(View.VISIBLE);
topView.startAnimation(showTopPanel);
Then the animation showed correctly.

How to make sticky section headers (like iOS) in Android?

My specific question is: How I can achieve an effect like this: http://youtu.be/EJm7subFbQI
The bounce effect is not important, but i need the "sticky" effect for the headers. Where do I start?, In what can I base me? I need something that I can implement on API 8 to up.
Thanks.
There are a few solutions that already exist for this problem. What you're describing are section headers and have come to be referred to as sticky section headers in Android.
Sticky List Headers
Sticky Scroll Views
HeaderListView
EDIT: Had some free time to add the code of fully working example. Edited the answer accordingly.
For those who don't want to use 3rd party code (or cannot use it directly, e.g. in Xamarin), this could be done fairly easily by hand.
The idea is to use another ListView for the header. This list view contains only the header items. It will not be scrollable by the user (setEnabled(false)), but will be scrolled from code based on main lists' scrolling. So you will have two lists - headerListview and mainListview, and two corresponding adapters headerAdapter and mainAdapter. headerAdapter only returns section views, while mainAdapter supports two view types (section and item). You will need a method that takes a position in the main list and returns a corresponding position in the sections list.
Main activity
public class MainActivity extends AppCompatActivity {
public static final int TYPE_SECTION = 0;
public static final int TYPE_ITEM = 1;
ListView mainListView;
ListView headerListView;
MainAdapter mainAdapter;
HeaderAdapter headerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainListView = (ListView)findViewById(R.id.list);
headerListView = (ListView)findViewById(R.id.header);
mainAdapter = new MainAdapter();
headerAdapter = new HeaderAdapter();
headerListView.setEnabled(false);
headerListView.setAdapter(headerAdapter);
mainListView.setAdapter(mainAdapter);
mainListView.setOnScrollListener(new AbsListView.OnScrollListener(){
#Override
public void onScrollStateChanged(AbsListView view, int scrollState){
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// this should return an index in the headers list, based one the index in the main list. The logic for this is highly dependent on your data.
int pos = mainAdapter.getSectionIndexForPosition(firstVisibleItem);
// this makes sure our headerListview shows the proper section (the one on the top of the mainListview)
headerListView.setSelection(pos);
// this makes sure that headerListview is scrolled exactly the same amount as the mainListview
if(mainAdapter.getItemViewType(firstVisibleItem + 1) == TYPE_SECTION){
headerListView.setSelectionFromTop(pos, mainListView.getChildAt(0).getTop());
}
}
});
}
public class MainAdapter extends BaseAdapter{
int count = 30;
#Override
public int getItemViewType(int position){
if((float)position / 10 == (int)((float)position/10)){
return TYPE_SECTION;
}else{
return TYPE_ITEM;
}
}
#Override
public int getViewTypeCount(){ return 2; }
#Override
public int getCount() { return count - 1; }
#Override
public Object getItem(int position) { return null; }
#Override
public long getItemId(int position) { return position; }
public int getSectionIndexForPosition(int position){ return position / 10; }
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = getLayoutInflater().inflate(R.layout.item, parent, false);
position++;
if(getItemViewType(position) == TYPE_SECTION){
((TextView)v.findViewById(R.id.text)).setText("SECTION "+position);
}else{
((TextView)v.findViewById(R.id.text)).setText("Item "+position);
}
return v;
}
}
public class HeaderAdapter extends BaseAdapter{
int count = 5;
#Override
public int getCount() { return count; }
#Override
public Object getItem(int position) { return null; }
#Override
public long getItemId(int position) { return position; }
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = getLayoutInflater().inflate(R.layout.item, parent, false);
((TextView)v.findViewById(R.id.text)).setText("SECTION "+position*10);
return v;
}
}
}
A couple of things to note here. We do not want to show the very first section in the main view list, because it would produce a duplicate (it's already shown in the header). To avoid that, in your mainAdapter.getCount():
return actualCount - 1;
and make sure the first line in your getView() method is
position++;
This way your main list will be rendering all cells but the first one.
Another thing is that you want to make sure your headerListview's height matches the height of the list item. In this example the height is fixed, but it could be tricky if your items height is not set to an exact value in dp. Please refer to this answer for how to address this: https://stackoverflow.com/a/41577017/291688
Main layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<ListView
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="48dp"/>
<ListView
android:id="#+id/list"
android:layout_below="#+id/header"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Item / header layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="48dp">
<TextView
android:id="#+id/text"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
Add this in your app.gradle file
compile 'se.emilsjolander:StickyScrollViewItems:1.1.0'
then my layout, where I have added android:tag ="sticky" to specific views like textview or edittext not LinearLayout, looks like this. It also uses databinding, ignore that.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="temp"
type="com.lendingkart.prakhar.lendingkartdemo.databindingmodel.BusinessDetailFragmentModel" />
<variable
name="presenter"
type="com.lendingkart.prakhar.lendingkartdemo.presenters.BusinessDetailsPresenter" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.lendingkart.prakhar.lendingkartdemo.customview.StickyScrollView
android:id="#+id/sticky_scroll"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- scroll view child goes here -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
style="#style/group_view_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/businessdetailtitletextviewbackground"
android:padding="#dimen/activity_horizontal_margin"
android:tag="sticky"
android:text="#string/business_contact_detail" />
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp">
<android.support.design.widget.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/comapnyLabel"
android:textSize="16sp" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<android.support.design.widget.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/contactLabel"
android:textSize="16sp" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<android.support.design.widget.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/emailLabel"
android:textSize="16sp" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<android.support.design.widget.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/NumberOfEmployee"
android:textSize="16sp" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true">
<TextView
style="#style/group_view_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/businessdetailtitletextviewbackground"
android:padding="#dimen/activity_horizontal_margin"
android:tag="sticky"
android:text="#string/nature_of_business" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true">
<TextView
style="#style/group_view_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/businessdetailtitletextviewbackground"
android:padding="#dimen/activity_horizontal_margin"
android:tag="sticky"
android:text="#string/taxation" />
</android.support.v7.widget.CardView>
</LinearLayout>
</com.lendingkart.prakhar.lendingkartdemo.customview.StickyScrollView>
</LinearLayout>
</layout>
style group for the textview looks this
<style name="group_view_text" parent="#android:style/TextAppearance.Medium">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#color/edit_text_color</item>
<item name="android:textSize">16dp</item>
<item name="android:layout_centerVertical">true</item>
<item name="android:textStyle">bold</item>
</style>
and the background for the textview goes like this:(#drawable/businessdetailtitletextviewbackground)
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#color/edit_text_color" />
</shape>
</item>
<item android:bottom="2dp">
<shape android:shape="rectangle">
<solid android:color="#color/White" />
</shape>
</item>
</layer-list>
For those looking for a solution in 2020, I have quickly created a solution extending the Layout Manager from ruslansharipov project (Sticky Header) and combining it whith the RecycleView Adapter from lisawray Groupie project (Expandable RecycleView).
You can see my example here
Result Here
You can reach this effect using SuperSLiM library. It provides you a LayoutManager for RecyclerView with interchangeable linear, grid, and staggered displays of views.
A good demo is located in github repository
It is simply to get such result
app:slm_headerDisplay="inline|sticky"
or
app:slm_headerDisplay="sticky"
I have used one special class to achieve listview like iPhone.
You can find example with source code here. https://demonuts.com/android-recyclerview-sticky-header-like-iphone/
This class which has updated listview is as
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.RelativeLayout;
public class HeaderListView extends RelativeLayout {
// TODO: Handle listViews with fast scroll
// TODO: See if there are methods to dispatch to mListView
private static final int FADE_DELAY = 1000;
private static final int FADE_DURATION = 2000;
private InternalListView mListView;
private SectionAdapter mAdapter;
private RelativeLayout mHeader;
private View mHeaderConvertView;
private FrameLayout mScrollView;
private AbsListView.OnScrollListener mExternalOnScrollListener;
public HeaderListView(Context context) {
super(context);
init(context, null);
}
public HeaderListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
mListView = new InternalListView(getContext(), attrs);
LayoutParams listParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
listParams.addRule(ALIGN_PARENT_TOP);
mListView.setLayoutParams(listParams);
mListView.setOnScrollListener(new HeaderListViewOnScrollListener());
mListView.setVerticalScrollBarEnabled(false);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mAdapter != null) {
mAdapter.onItemClick(parent, view, position, id);
}
}
});
addView(mListView);
mHeader = new RelativeLayout(getContext());
LayoutParams headerParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
headerParams.addRule(ALIGN_PARENT_TOP);
mHeader.setLayoutParams(headerParams);
mHeader.setGravity(Gravity.BOTTOM);
addView(mHeader);
// The list view's scroll bar can be hidden by the header, so we display our own scroll bar instead
Drawable scrollBarDrawable = getResources().getDrawable(R.drawable.scrollbar_handle_holo_light);
mScrollView = new FrameLayout(getContext());
LayoutParams scrollParams = new LayoutParams(scrollBarDrawable.getIntrinsicWidth(), LayoutParams.MATCH_PARENT);
scrollParams.addRule(ALIGN_PARENT_RIGHT);
scrollParams.rightMargin = (int) dpToPx(2);
mScrollView.setLayoutParams(scrollParams);
ImageView scrollIndicator = new ImageView(context);
scrollIndicator.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
scrollIndicator.setImageDrawable(scrollBarDrawable);
scrollIndicator.setScaleType(ScaleType.FIT_XY);
mScrollView.addView(scrollIndicator);
mScrollView.setVisibility(INVISIBLE);
addView(mScrollView);
}
public void setAdapter(SectionAdapter adapter) {
mAdapter = adapter;
mListView.setAdapter(adapter);
}
public void setOnScrollListener(AbsListView.OnScrollListener l) {
mExternalOnScrollListener = l;
}
private class HeaderListViewOnScrollListener implements AbsListView.OnScrollListener {
private int previousFirstVisibleItem = -1;
private int direction = 0;
private int actualSection = 0;
private boolean scrollingStart = false;
private boolean doneMeasuring = false;
private int lastResetSection = -1;
private int nextH;
private int prevH;
private View previous;
private View next;
private AlphaAnimation fadeOut = new AlphaAnimation(1f, 0f);
private boolean noHeaderUpToHeader = false;
private boolean didScroll = false;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (mExternalOnScrollListener != null) {
mExternalOnScrollListener.onScrollStateChanged(view, scrollState);
}
didScroll = true;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (mExternalOnScrollListener != null) {
mExternalOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
if (!didScroll) {
return;
}
firstVisibleItem -= mListView.getHeaderViewsCount();
if (firstVisibleItem < 0) {
mHeader.removeAllViews();
return;
}
updateScrollBar();
if (visibleItemCount > 0 && firstVisibleItem == 0 && mHeader.getChildAt(0) == null) {
addSectionHeader(0);
lastResetSection = 0;
}
int realFirstVisibleItem = getRealFirstVisibleItem(firstVisibleItem, visibleItemCount);
if (totalItemCount > 0 && previousFirstVisibleItem != realFirstVisibleItem) {
direction = realFirstVisibleItem - previousFirstVisibleItem;
actualSection = mAdapter.getSection(realFirstVisibleItem);
boolean currIsHeader = mAdapter.isSectionHeader(realFirstVisibleItem);
boolean prevHasHeader = mAdapter.hasSectionHeaderView(actualSection - 1);
boolean nextHasHeader = mAdapter.hasSectionHeaderView(actualSection + 1);
boolean currHasHeader = mAdapter.hasSectionHeaderView(actualSection);
boolean currIsLast = mAdapter.getRowInSection(realFirstVisibleItem) == mAdapter.numberOfRows(actualSection) - 1;
boolean prevHasRows = mAdapter.numberOfRows(actualSection - 1) > 0;
boolean currIsFirst = mAdapter.getRowInSection(realFirstVisibleItem) == 0;
boolean needScrolling = currIsFirst && !currHasHeader && prevHasHeader && realFirstVisibleItem != firstVisibleItem;
boolean needNoHeaderUpToHeader = currIsLast && currHasHeader && !nextHasHeader && realFirstVisibleItem == firstVisibleItem && Math.abs(mListView.getChildAt(0).getTop()) >= mListView.getChildAt(0).getHeight() / 2;
noHeaderUpToHeader = false;
if (currIsHeader && !prevHasHeader && firstVisibleItem >= 0) {
resetHeader(direction < 0 ? actualSection - 1 : actualSection);
} else if ((currIsHeader && firstVisibleItem > 0) || needScrolling) {
if (!prevHasRows) {
resetHeader(actualSection-1);
}
startScrolling();
} else if (needNoHeaderUpToHeader) {
noHeaderUpToHeader = true;
} else if (lastResetSection != actualSection) {
resetHeader(actualSection);
}
previousFirstVisibleItem = realFirstVisibleItem;
}
if (scrollingStart) {
int scrolled = realFirstVisibleItem >= firstVisibleItem ? mListView.getChildAt(realFirstVisibleItem - firstVisibleItem).getTop() : 0;
if (!doneMeasuring) {
setMeasurements(realFirstVisibleItem, firstVisibleItem);
}
int headerH = doneMeasuring ? (prevH - nextH) * direction * Math.abs(scrolled) / (direction < 0 ? nextH : prevH) + (direction > 0 ? nextH : prevH) : 0;
mHeader.scrollTo(0, -Math.min(0, scrolled - headerH));
if (doneMeasuring && headerH != mHeader.getLayoutParams().height) {
LayoutParams p = (LayoutParams) (direction < 0 ? next.getLayoutParams() : previous.getLayoutParams());
p.topMargin = headerH - p.height;
mHeader.getLayoutParams().height = headerH;
mHeader.requestLayout();
}
}
if (noHeaderUpToHeader) {
if (lastResetSection != actualSection) {
addSectionHeader(actualSection);
lastResetSection = actualSection + 1;
}
mHeader.scrollTo(0, mHeader.getLayoutParams().height - (mListView.getChildAt(0).getHeight() + mListView.getChildAt(0).getTop()));
}
}
private void startScrolling() {
scrollingStart = true;
doneMeasuring = false;
lastResetSection = -1;
}
private void resetHeader(int section) {
scrollingStart = false;
addSectionHeader(section);
mHeader.requestLayout();
lastResetSection = section;
}
private void setMeasurements(int realFirstVisibleItem, int firstVisibleItem) {
if (direction > 0) {
nextH = realFirstVisibleItem >= firstVisibleItem ? mListView.getChildAt(realFirstVisibleItem - firstVisibleItem).getMeasuredHeight() : 0;
}
previous = mHeader.getChildAt(0);
prevH = previous != null ? previous.getMeasuredHeight() : mHeader.getHeight();
if (direction < 0) {
if (lastResetSection != actualSection - 1) {
addSectionHeader(Math.max(0, actualSection - 1));
next = mHeader.getChildAt(0);
}
nextH = mHeader.getChildCount() > 0 ? mHeader.getChildAt(0).getMeasuredHeight() : 0;
mHeader.scrollTo(0, prevH);
}
doneMeasuring = previous != null && prevH > 0 && nextH > 0;
}
private void updateScrollBar() {
if (mHeader != null && mListView != null && mScrollView != null) {
int offset = mListView.computeVerticalScrollOffset();
int range = mListView.computeVerticalScrollRange();
int extent = mListView.computeVerticalScrollExtent();
mScrollView.setVisibility(extent >= range ? View.INVISIBLE : View.VISIBLE);
if (extent >= range) {
return;
}
int top = range == 0 ? mListView.getHeight() : mListView.getHeight() * offset / range;
int bottom = range == 0 ? 0 : mListView.getHeight() - mListView.getHeight() * (offset + extent) / range;
mScrollView.setPadding(0, top, 0, bottom);
fadeOut.reset();
fadeOut.setFillBefore(true);
fadeOut.setFillAfter(true);
fadeOut.setStartOffset(FADE_DELAY);
fadeOut.setDuration(FADE_DURATION);
mScrollView.clearAnimation();
mScrollView.startAnimation(fadeOut);
}
}
private void addSectionHeader(int actualSection) {
View previousHeader = mHeader.getChildAt(0);
if (previousHeader != null) {
mHeader.removeViewAt(0);
}
if (mAdapter.hasSectionHeaderView(actualSection)) {
mHeaderConvertView = mAdapter.getSectionHeaderView(actualSection, mHeaderConvertView, mHeader);
mHeaderConvertView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
mHeaderConvertView.measure(MeasureSpec.makeMeasureSpec(mHeader.getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
mHeader.getLayoutParams().height = mHeaderConvertView.getMeasuredHeight();
mHeaderConvertView.scrollTo(0, 0);
mHeader.scrollTo(0, 0);
mHeader.addView(mHeaderConvertView, 0);
} else {
mHeader.getLayoutParams().height = 0;
mHeader.scrollTo(0, 0);
}
mScrollView.bringToFront();
}
private int getRealFirstVisibleItem(int firstVisibleItem, int visibleItemCount) {
if (visibleItemCount == 0) {
return -1;
}
int relativeIndex = 0, totalHeight = mListView.getChildAt(0).getTop();
for (relativeIndex = 0; relativeIndex < visibleItemCount && totalHeight < mHeader.getHeight(); relativeIndex++) {
totalHeight += mListView.getChildAt(relativeIndex).getHeight();
}
int realFVI = Math.max(firstVisibleItem, firstVisibleItem + relativeIndex - 1);
return realFVI;
}
}
public ListView getListView() {
return mListView;
}
public void addHeaderView(View v) {
mListView.addHeaderView(v);
}
private float dpToPx(float dp) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getContext().getResources().getDisplayMetrics());
}
protected class InternalListView extends ListView {
public InternalListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected int computeVerticalScrollExtent() {
return super.computeVerticalScrollExtent();
}
#Override
protected int computeVerticalScrollOffset() {
return super.computeVerticalScrollOffset();
}
#Override
protected int computeVerticalScrollRange() {
return super.computeVerticalScrollRange();
}
}
}
XML usage
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context=".MainActivity">
<com.example.parsaniahardik.listview_stickyheader_ios.HeaderListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv">
</com.example.parsaniahardik.listview_stickyheader_ios.HeaderListView>

disable swiping between tabs in FragmentActivity

I have a (Sherlock)FragmentActivity with 2 tabbed fragments. The left fragment is a GridView that displays pictures of an album and the right fragment consists of a ViewPager that is used to view individual pictures. From the left fragment you can scroll through the pictures and select one. Tabbing (or swiping) over to the right fragment will show the picture and because it is a ViewPager you can swipe to the preceding or the next picture.
This works great except that the FragmentActivity wants to intercept the right swipe and move back to the left tab. I would like to prevent the FragmentActivity from intercepting the swipes when I am on the right tab. If I had to disable swiping between tabs altogether it would be satisfactory. I just want the swiping to be dedicated to the current tab and not be used to move between tabs.
The following images indicate the current behavior. The right image shows what happens when I do a swipe to the right. As you can see the left tab starts to appear. I want the swipe to instead apply to the right tab only so that I can swipe between the images without the left tab appearing.
I see solutions to control swiping within a ViewPager but have yet to find a solution to control swiping between tabbed fragments.
Here is the xml for the GridView fragment and the ViewPager fragment:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<FrameLayout android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="100dip"
android:gravity="center"
android:horizontalSpacing="4dip"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="4dip" />
</FrameLayout>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"/>
</LinearLayout>
Here a code summary of the ViewPager fragment:
public class FragmentFlash extends SherlockFragment {
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
private ViewPager pager = null;
private int pagerPosition;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pagerPosition = 0;
// Gesture detection
gestureDetector = new GestureDetector(new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.flash, container, false);
pager = (ViewPager) v.findViewById(R.id.pager);
pager.setOnTouchListener(gestureListener);
return v;
}
class MyGestureDetector extends SimpleOnGestureListener {
private static final int SWIPE_MIN_DISTANCE = 10;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 50;
#Override
public boolean onDown(MotionEvent e) {
return true;//false; make onFling work with fragments
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
else
// right to left swipe
if(distanceX > SWIPE_MIN_DISTANCE) {
if (pagerPosition < imageUrls.length-1)
pager.setCurrentItem(++pagerPosition);
// left to right swipe
} else if (distanceX < -SWIPE_MIN_DISTANCE) {
if (pagerPosition > 0)
pager.setCurrentItem(--pagerPosition);
}
return true;
} catch (Exception e) {
// nothing
}
return false;
}
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images) {
this.images = images;
inflater = mContext.getLayoutInflater();
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public void finishUpdate(View container) {
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object instantiateItem(View view, int position) {
final View imageLayout = inflater.inflate(R.layout.item_pager_image, null);
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
byte[] image = ;//get byte array from file at images[position];
if (null != image) {
Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
imageView.setImageBitmap(bitmap);
}
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View container) {
}
}
public void pagerPositionSet(int pagerPosition, String[] imageUrls) {
Log.i(Flashum.LOG_TAG, "FragmentFlash pagerPositionSet: " + pagerPosition);
if (pagerPosition >= 0)
this.pagerPosition = pagerPosition;
if (pager != null) {
pager.setAdapter(new ImagePagerAdapter(imageUrls));
pager.setCurrentItem(this.pagerPosition);
}
}
}
This is the item_pager_image.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="1dip" >
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:contentDescription="#string/descr_image" />
<ProgressBar
android:id="#+id/loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
</FrameLayout>
Ok, I finally figured this out. Laurence Dawson was on the right track but instead of applying the CustomViewPager to the fragment it needs to be applied to the FragmentActivity. You see, switching between tabs, which is managed by the activity, is also a ViewPager adaptor. Thus, xml for the activity is
<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<com.Flashum.CustomViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</TabHost>
And the custom ViewPager is as suggested except that that the constructor enables it to cause onInterceptTouchEvent to return false. This prevents the FragmentActivity from acting on the swipe so that it can be dedicated to the fragment!
public class CustomViewPager extends ViewPager {
private boolean enabled;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = **false**;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
}
You need to override the onInterceptTouchEvent method for your ViewPager, you can do this by extending ViewPager or visit this link for a great tutorial on adding this:
http://blog.svpino.com/2011/08/disabling-pagingswiping-on-android.html

Categories

Resources