Converting Activity to use Fragments? - android

I basically have an activity that has tabs. I want it so that when I select a different tab the fragment at the bottom changes to the selected tab. I know that theres 2 ways to do it. 1 is reload the same grid view with new data. I want it so that I can switch between tabs and it loads all the grid views as you left them. Is this possible and how can I modify this code to support that:
MainActivity:
package com.td.flickrsearch;
import java.util.ArrayList;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.td.flickrsearch.entity.FlickrPhoto;
import com.td.flickrsearch.image.ImageCache.ImageCacheParams;
import com.td.flickrsearch.image.ImageFetcher;
public class MainActivity extends FragmentActivity implements OnClickListener, TabListener {
private int mImageThumbSize;
private int mImageThumbSpacing;
private ImageFetcher mImageFetcher;
public static int currentPage = 1;
private boolean endOfAlbums = false;
private int lastItem = 0;
private TextView tvNoAlbums;
private ProgressBar progressLoadMore;
GridView albumGrid;
ImageAdapter imageAdapter;
ArrayList<FlickrPhoto> _feed = new ArrayList<FlickrPhoto>();
ProgressDialog progressDialog;
private Handler myHandler = new Handler();
private Runnable updateRunnable;
EditText etSearch;
Button btnSearch;
private Animator mCurrentAnimator;
private int mShortAnimationDuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_fragment);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// For each of the sections in the app, add a tab to the action bar.
actionBar.addTab(actionBar.newTab().setText("Friends").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Chat").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Me").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Users").setTabListener(this));
//actionBar.addTab(actionBar.newTab().setText(R.string.title_section3).setTabListener(this));
// Set the Animation time form the android defaults
mShortAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);
// ////////////////////////////////////////
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Fetching images, please wait...");
progressDialog.setCancelable(false);
// ////////////////////////////////////////
// /////////////////////////////////////////
etSearch = (EditText) findViewById(R.id.etSearch);
btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
// /////////////////////////////////////////
mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.photo_thumbnail_size);
mImageThumbSpacing = getResources().getDimensionPixelSize(R.dimen.photo_thumbnail_spacing);
// ////////////////////////////////////////////
ImageCacheParams cacheParams = new ImageCacheParams(this, Util.IMAGE_CACHE_DIR);
// The ImageFetcher takes care of loading images into our ImageView
// children asynchronously
mImageFetcher = new ImageFetcher(this, mImageThumbSize);
mImageFetcher.setLoadingImage(R.drawable.empty_photo);
mImageFetcher.addImageCache(this.getSupportFragmentManager(), cacheParams);
// ////////////////////////////////////////////
progressLoadMore = (ProgressBar) findViewById(R.id.progress);
progressLoadMore.setVisibility(View.GONE);
// //////////////////////////////////////////////S
imageAdapter = new ImageAdapter();
albumGrid = (GridView) findViewById(R.id.photoGrid);
tvNoAlbums = (TextView) findViewById(R.id.tvNoAlbums);
albumGrid.setAdapter(imageAdapter);
albumGrid.setFastScrollEnabled(true);
// This listener is used to get the final width of the GridView and then
// calculate the
// number of columns and the width of each column. The width of each
// column is variable
// as the GridView has stretchMode=columnWidth. The column width is used
// to set the height
// of each view so we get nice square thumbnails.
albumGrid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (imageAdapter.getNumColumns() == 0) {
final int numColumns = (int) Math.floor(albumGrid.getWidth() / (mImageThumbSize + mImageThumbSpacing));
if (numColumns > 0) {
final int columnWidth = (albumGrid.getWidth() / numColumns) - mImageThumbSpacing;
imageAdapter.setNumColumns(numColumns);
imageAdapter.setItemHeight(columnWidth);
}
}
}
});
// albumGrid on item click:
albumGrid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int pos, long arg3) {
// On click
// Display the zoomed in image in full screen
zoomImageFromThumb(v, pos);
}
});
albumGrid.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
// Pause fetcher to ensure smoother scrolling when flinging
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
mImageFetcher.setPauseWork(true);
} else {
mImageFetcher.setPauseWork(false);
}
}
#Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
final int _lastItem = firstVisibleItem + visibleItemCount;
if (_lastItem > 0 && totalItemCount > 0)
if (_lastItem == _feed.size() && !endOfAlbums && lastItem != _lastItem) {
lastItem = _lastItem;
// Last item is fully visible.
loadAlbums(etSearch.getText().toString().trim());
}
}
});
etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
_feed.clear();
currentPage = 1;
Util.hideSoftKeyboard(MainActivity.this);
loadAlbums(etSearch.getText().toString().trim());
return true;
}
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_search:
// search action
Toast.makeText(this, "Search selected", Toast.LENGTH_SHORT)
.show();
return true;
case R.id.action_help:
// help action
Toast.makeText(this, "help selected", Toast.LENGTH_SHORT)
.show();
return true;
case R.id.action_refresh:
// refresh
Toast.makeText(this, "refresh selected", Toast.LENGTH_SHORT)
.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSearch:
// perform search
_feed.clear();
currentPage = 1;
Util.hideSoftKeyboard(MainActivity.this);
loadAlbums(etSearch.getText().toString().trim().replaceAll(" ", ""));
break;
default:
break;
}
}
private void loadAlbums(final String tag) {
if (currentPage == 1) {
_feed.clear();
endOfAlbums = false;
lastItem = 0;
// get new photos
progressDialog.show();
} else
progressLoadMore.setVisibility(View.VISIBLE);
if (Util.isNetworkAvailable(MainActivity.this)) {
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<FlickrPhoto> serverAlbums;
// get the serverAlbums
serverAlbums = FlickrParser.getPhotos(tag, currentPage);
if (serverAlbums.size() > 0)
_feed.addAll(serverAlbums);
else
endOfAlbums = true;
currentPage++;
myHandler.post(updateRunnable);
}
}).start();
updateRunnable = new Runnable() {
#Override
public void run() {
if (_feed.size() > 0) {
imageAdapter.notifyDataSetChanged();
// get listview current position - used to maintain
// scroll position
int currentPosition = albumGrid.getFirstVisiblePosition();
// Setting new scroll position
albumGrid.smoothScrollToPosition(currentPosition + 1, 0);
} else
tvNoAlbums.setVisibility(View.VISIBLE);
progressDialog.dismiss();
progressLoadMore.setVisibility(View.GONE);
}
};
} else {
Toast.makeText(this, R.string.check_connectivity, Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
progressLoadMore.setVisibility(View.GONE);
}
}
// ///////////////////////////Zoom in Image///////////////////////////////
private void zoomImageFromThumb(final View thumbView, int pos) {
// If there's an animation in progress, cancel it immediately and
// proceed with this one.
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}
// Load the high-resolution "zoomed-in" image.
final ImageView expandedImageView = (ImageView) findViewById(R.id.expanded_image);
// mImageFetcher.loadImage(Util.getPhotoUrlLarge(_feed.get(pos)),
// expandedImageView);
mImageFetcher.loadImage(Util.getPhotoUrl(_feed.get(pos)), expandedImageView);
// Calculate the starting and ending bounds for the zoomed-in image.
// This step
// involves lots of math. Yay, math.
final Rect startBounds = new Rect();
final Rect finalBounds = new Rect();
final Point globalOffset = new Point();
// The start bounds are the global visible rectangle of the thumbnail,
// and the
// final bounds are the global visible rectangle of the container view.
// Also
// set the container view's offset as the origin for the bounds, since
// that's
// the origin for the positioning animation properties (X, Y).
thumbView.getGlobalVisibleRect(startBounds);
findViewById(R.id.container).getGlobalVisibleRect(finalBounds, globalOffset);
startBounds.offset(-globalOffset.x, -globalOffset.y);
finalBounds.offset(-globalOffset.x, -globalOffset.y);
// Adjust the start bounds to be the same aspect ratio as the final
// bounds using the
// "center crop" technique. This prevents undesirable stretching during
// the animation.
// Also calculate the start scaling factor (the end scaling factor is
// always 1.0).
float startScale;
if ((float) finalBounds.width() / finalBounds.height() > (float) startBounds.width() / startBounds.height()) {
// Extend start bounds horizontally
startScale = (float) startBounds.height() / finalBounds.height();
float startWidth = startScale * finalBounds.width();
float deltaWidth = (startWidth - startBounds.width()) / 2;
startBounds.left -= deltaWidth;
startBounds.right += deltaWidth;
} else {
// Extend start bounds vertically
startScale = (float) startBounds.width() / finalBounds.width();
float startHeight = startScale * finalBounds.height();
float deltaHeight = (startHeight - startBounds.height()) / 2;
startBounds.top -= deltaHeight;
startBounds.bottom += deltaHeight;
}
// Hide the thumbnail and show the zoomed-in view. When the animation
// begins,
// it will position the zoomed-in view in the place of the thumbnail.
thumbView.setAlpha(0f);
expandedImageView.setVisibility(View.VISIBLE);
// Set the pivot point for SCALE_X and SCALE_Y transformations to the
// top-left corner of
// the zoomed-in view (the default is the center of the view).
expandedImageView.setPivotX(0f);
expandedImageView.setPivotY(0f);
// Construct and run the parallel animation of the four translation and
// scale properties
// (X, Y, SCALE_X, and SCALE_Y).
AnimatorSet set = new AnimatorSet();
set.play(ObjectAnimator.ofFloat(expandedImageView, View.X, startBounds.left, finalBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y, startBounds.top, finalBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScale, 1f))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScale, 1f));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mCurrentAnimator = null;
}
#Override
public void onAnimationCancel(Animator animation) {
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;
// Upon clicking the zoomed-in image, it should zoom back down to the
// original bounds
// and show the thumbnail instead of the expanded image.
final float startScaleFinal = startScale;
expandedImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}
// Animate the four positioning/sizing properties in parallel,
// back to their
// original values.
AnimatorSet set = new AnimatorSet();
set.play(ObjectAnimator.ofFloat(expandedImageView, View.X, startBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y, startBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScaleFinal))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScaleFinal));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}
#Override
public void onAnimationCancel(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;
}
});
}
// //////////////////////////////////////////////////////////
// ///////////////// ADAPTER ////////////////////////////////
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private int mItemHeight = 0;
private int mNumColumns = 0;
private RelativeLayout.LayoutParams mImageViewLayoutParams;
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mImageViewLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
public int getCount() {
return _feed.size();
}
public void setNumColumns(int numColumns) {
mNumColumns = numColumns;
}
public int getNumColumns() {
return mNumColumns;
}
public void setItemHeight(int height) {
if (height == mItemHeight) {
return;
}
mItemHeight = height;
mImageViewLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight);
notifyDataSetChanged();
}
public FlickrPhoto getItem(int position) {
return _feed.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = mInflater.inflate(R.layout.grid_item, null);
holder.cover = (ImageView) view.findViewById(R.id.cover);
holder.title = (TextView) view.findViewById(R.id.title);
view.setTag(holder);
} else
holder = (ViewHolder) view.getTag();
holder.cover.setLayoutParams(mImageViewLayoutParams);
// Check the height matches our calculated column width
if (holder.cover.getLayoutParams().height != mItemHeight) {
holder.cover.setLayoutParams(mImageViewLayoutParams);
}
FlickrPhoto photo = getItem(position);
mImageFetcher.loadImage(Util.getPhotoUrl(photo), holder.cover);
holder.cover.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.title.setText(photo.getTitle());
return view;
}
}
class ViewHolder {
ImageView cover;
TextView title;
}
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
if (tab.getPosition() == 0) {
}
else if (tab.getPosition() == 1) {
}
else {
//AndroidVersionList androidversionlist = new AndroidVersionList();
//getSupportFragmentManager().beginTransaction().replace(R.id.container, androidversionlist).commit();
/*Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, tab.getPosition() + 1);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();*/
}
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
ActivityMain.xml:
<FrameLayout 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"
tools:context=".MainActivity" />
ListFragment.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/llSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp" >
<EditText
android:id="#+id/etSearch"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_weight="9"
android:drawableRight="#drawable/edit_search"
android:hint="tag name"
android:imeOptions="actionSearch"
android:inputType="textNoSuggestions"
android:singleLine="true" />
<Button
android:id="#+id/btnSearch"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="2dp"
android:layout_weight="2"
android:text="Go!" />
</LinearLayout>
<GridView
android:id="#+id/photoGrid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/progress"
android:layout_below="#+id/llSearch"
android:alwaysDrawnWithCache="true"
android:clipChildren="true"
android:columnWidth="#dimen/photo_thumbnail_size"
android:fadeScrollbars="false"
android:fastScrollEnabled="true"
android:horizontalSpacing="#dimen/photo_thumbnail_spacing"
android:numColumns="auto_fit"
android:padding="6dp"
android:scrollbars="none"
android:scrollingCache="true"
android:smoothScrollbar="true"
android:stretchMode="columnWidth"
android:verticalSpacing="#dimen/photo_thumbnail_spacing" />
<ProgressBar
android:id="#+id/progress"
style="#android:style/Widget.ProgressBar.Large"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="4dp"
android:padding="10dp" />
<TextView
android:id="#+id/tvNoAlbums"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="No photos to display!"
android:textSize="14sp"
android:textStyle="bold"
android:visibility="gone" />
<ImageView
android:id="#+id/expanded_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/app_name"
android:visibility="invisible" />
</RelativeLayout>
Right now I think the best way to do it is probably separate the adapter, make this into separate fragments. Would I be able to switch back to the fragment and will it be in the state I left it in?
So for example if a user scrolled down in the gridview when I switch back to the fragment will it be at the same position with the same data?
It would be great if you could help me convert this into something that will do that. I dont really know much about it so all help is really appreciated. Thank You :)

I would suggest that:
when you do your fragment transactions, remember to add the fragment to the backstack public abstract FragmentTransaction addToBackStack (String name) so that you can find the fragment later instead of having the garbage collector destroy your fragment.
When you add your fragment to the backstack, it will do :
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
.... Save whatever else is uniqe about your fragment here
}
When you go back to your fragment, since you added it to the backstack, use :
onViewStateRestored()
Called when all saved state has been restored into the view hierarchy of the fragment.
This can be used to do initialization based on saved state that you are letting the view
hierarchy track itself, such as whether check box widgets are currently checked. This is
called after onActivityCreated(Bundle) and before onStart().

Related

Add Edit-Text dynamically on Horizontal List View item

I am developing a photo editor app. Where I am giving an option of add text to image i.e writing some CAPTION or you can say TAG on that image. What I want is on "A"`s click, an Edit-Text should be added to the in image. Where can I insert name or any text.
What I want is describes in below image...
My code is below....
Second.java
package com.MyFirstApp.myfirstapp;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Random;
import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.devsmart.android.ui.HorizontalListView;
public class Second extends Activity {
TouchImageView img_to_be_zoomedH, img_to_be_zoomed_secondH,
img_to_be_zoomedV, img_to_be_zoomed_secondV;
ImageView img_back, img_save;
HorizontalListView HListView, HListViewFirst, HListViewColor;
/* Save Parent Layout After Editing */
RelativeLayout parentLayoutforImgSaving;
Bitmap bitmap_img, bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
img_to_be_zoomedH = (TouchImageView) findViewById(R.id.img_to_be_zoomedH);
img_to_be_zoomed_secondH = (TouchImageView) findViewById(R.id.img_to_be_zoomed_secondH);
img_to_be_zoomedV = (TouchImageView) findViewById(R.id.img_to_be_zoomedV);
img_to_be_zoomed_secondV = (TouchImageView) findViewById(R.id.img_to_be_zoomed_secondV);
img_back = (ImageView) findViewById(R.id.img_back_icon);
img_save = (ImageView) findViewById(R.id.img_save_icon);
HListView = (HorizontalListView) findViewById(R.id.horizontal_list_view);
HListViewFirst = (HorizontalListView) findViewById(R.id.horizontal_list_view_first);
HListViewColor = (HorizontalListView) findViewById(R.id.horizontal_list_view_color);
parentLayoutforImgSaving = (RelativeLayout) findViewById(R.id.imagelayout);
/* Top Back Icon */
img_back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
/* Save Image Icon */
img_save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
saveImgAfterEditing(parentLayoutforImgSaving);
}
});
/* Left Image Touch Event */
img_to_be_zoomedH
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomed_secondH.setZoom(img_to_be_zoomedH);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomedH.getScrollPosition();
img_to_be_zoomed_secondH.setScrollPosition(
1 - pointF_img1.x, pointF_img1.y);
}
});
/* Right Image touch event */
img_to_be_zoomed_secondH
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomedH.setZoom(img_to_be_zoomed_secondH);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomed_secondH
.getScrollPosition();
img_to_be_zoomedH.setScrollPosition(1 - pointF_img1.x,
pointF_img1.y);
}
});
/* Top Image Touch Event */
img_to_be_zoomedV
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomed_secondV.setZoom(img_to_be_zoomedV);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomedV.getScrollPosition();
img_to_be_zoomed_secondV.setScrollPosition(
pointF_img1.x, 1 - pointF_img1.y);
}
});
/* Bottom Image touch event */
img_to_be_zoomed_secondV
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomedV.setZoom(img_to_be_zoomed_secondV);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomed_secondV
.getScrollPosition();
img_to_be_zoomedV.setScrollPosition(pointF_img1.x,
1 - pointF_img1.y);
}
});
int[] HorizontalListImages = new int[] { R.drawable.icon_grid,
R.drawable.icon_text, R.drawable.icon_clip_art };
final int[] HorizontalListImagesFirst = new int[] {
R.drawable.icon_go_back, R.drawable.icon_horizontal_grid,
R.drawable.icon_vertical_grid };
/* Animation References */
final Animation slideUp = AnimationUtils.loadAnimation(
getApplicationContext(), R.anim.slide_up);
final Animation slideDown = AnimationUtils.loadAnimation(
getApplicationContext(), R.anim.slide_down);
/* Setting Adapter for Horizontal List Views */
HorizontalListViewAdapter horizontalListViewAdapter = new HorizontalListViewAdapter(
Second.this, HorizontalListImages);
HListView.setAdapter(horizontalListViewAdapter);
/* Horizontal List View Item Click Listener */
HListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
switch (position) {
case 0:
HorizontalListViewAdapterFirst horizontalListViewAdapterFirst = new HorizontalListViewAdapterFirst(
Second.this, HorizontalListImagesFirst);
HListViewFirst.setAdapter(horizontalListViewAdapterFirst);
HListView.startAnimation(slideDown);
HListView.setVisibility(View.GONE);
HListViewFirst.startAnimation(slideUp);
HListViewFirst.setVisibility(View.VISIBLE);
break;
case 1:
/* Space for adding dynamic Edit-Text */
break;
default:
break;
}
}
});
HListViewFirst.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
/* HighLight Selected Option */
for (int i = 0; i < HListViewFirst.getChildCount(); i++) {
if (position == i) {
HListViewFirst.getChildAt(i).setBackgroundColor(
Color.GRAY);
} else {
HListViewFirst.getChildAt(i).setBackgroundColor(
Color.TRANSPARENT);
}
}
/* Get Device`s Height, Width */
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(
displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
switch (position) {
case 0:
HListViewFirst.startAnimation(slideDown);
HListViewFirst.setVisibility(View.GONE);
HListView.startAnimation(slideUp);
HListView.setVisibility(View.VISIBLE);
break;
case 1:
/* Setting Center Layout For Both Images */
RelativeLayout.LayoutParams ImagelayoutParams1 = new RelativeLayout.LayoutParams(
width, width);
ImagelayoutParams1.addRule(RelativeLayout.CENTER_IN_PARENT);
((RelativeLayout) findViewById(R.id.imagelayout))
.setLayoutParams(ImagelayoutParams1);
/* Setting Left ImageView width, height */
RelativeLayout.LayoutParams layoutParamsLeft = new RelativeLayout.LayoutParams(
width / 2, width);
layoutParamsLeft.setMargins(0, 0, 0, 0);
img_to_be_zoomedH.setLayoutParams(layoutParamsLeft);
img_to_be_zoomedH.setVisibility(view.VISIBLE);
bitmap_img = ((BitmapDrawable) img_to_be_zoomedH
.getDrawable()).getBitmap();
bitmap_img = flipImage(bitmap_img, 2);
img_to_be_zoomed_secondH.setImageBitmap(bitmap_img);
/* Setting Right ImageView width, height */
RelativeLayout.LayoutParams layoutParamsRight = new RelativeLayout.LayoutParams(
width / 2, width);
layoutParamsRight.setMargins(width / 2, 0, 0, 0);
img_to_be_zoomed_secondH.setLayoutParams(layoutParamsRight);
// img_to_be_zoomedH.invalidate();
img_to_be_zoomed_secondH.setVisibility(view.VISIBLE);
/* Hiding Vertical TouchIMageViews */
if ((img_to_be_zoomedV.getVisibility() == view.VISIBLE)
|| (img_to_be_zoomed_secondV.getVisibility() == view.VISIBLE)) {
img_to_be_zoomedV.setVisibility(view.GONE);
img_to_be_zoomed_secondV.setVisibility(view.GONE);
}
break;
case 2:
/* Setting Center Layout For Both Images */
RelativeLayout.LayoutParams ImagelayoutParams2 = new RelativeLayout.LayoutParams(
width, width);
ImagelayoutParams2.addRule(RelativeLayout.CENTER_IN_PARENT);
((RelativeLayout) findViewById(R.id.imagelayout))
.setLayoutParams(ImagelayoutParams2);
/* Setting Top ImageView width, height */
RelativeLayout.LayoutParams layoutParamsTop = new RelativeLayout.LayoutParams(
width, width / 2);
layoutParamsTop.setMargins(0, 0, 0, 0);
img_to_be_zoomedV.setLayoutParams(layoutParamsTop);
img_to_be_zoomedV.setVisibility(view.VISIBLE);
bitmap_img = ((BitmapDrawable) img_to_be_zoomedV
.getDrawable()).getBitmap();
bitmap_img = flipImage(bitmap_img, 1);
img_to_be_zoomed_secondV.setImageBitmap(bitmap_img);
/* Setting Bottom ImageView width, height */
RelativeLayout.LayoutParams layoutParamsBottom = new RelativeLayout.LayoutParams(
width, width / 2);
layoutParamsBottom.setMargins(0, width / 2, 0, 0);
img_to_be_zoomed_secondV
.setLayoutParams(layoutParamsBottom);
// img_to_be_zoomedV.invalidate();
img_to_be_zoomed_secondV.setVisibility(view.VISIBLE);
/* Hiding Horizontal TouchIMageViews */
if ((img_to_be_zoomedH.getVisibility() == view.VISIBLE)
|| (img_to_be_zoomed_secondH.getVisibility() == view.VISIBLE)) {
img_to_be_zoomedH.setVisibility(view.GONE);
img_to_be_zoomed_secondH.setVisibility(view.GONE);
}
break;
default:
break;
}
}
});
/* Getting ImageURI from Gallery from Main Activity */
Uri selectedImgUri = getIntent().getData();
if (selectedImgUri != null) {
String[] selectedImgPath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImgUri,
selectedImgPath, null, null, null);
cursor.moveToFirst();
int indexCol = cursor.getColumnIndex(selectedImgPath[0]);
String imgPath = cursor.getString(indexCol);
cursor.close();
img_to_be_zoomedH.setImageBitmap(BitmapFactory.decodeFile(imgPath));
img_to_be_zoomedV.setImageBitmap(BitmapFactory.decodeFile(imgPath));
}
/* Getting ImageBitmap from Camera from Main Activity */
Intent intent_camera = getIntent();
Bitmap camera_img_bitmap = (Bitmap) intent_camera
.getParcelableExtra("BitmapImage");
if (camera_img_bitmap != null) {
img_to_be_zoomedH.setImageBitmap(camera_img_bitmap);
img_to_be_zoomedV.setImageBitmap(camera_img_bitmap);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/* Flip Image Function */
public Bitmap flipImage(Bitmap src, int type) {
Matrix matrix = new Matrix();
/* Flip vertically */
if (type == 1) {
matrix.preScale(1.0f, -1.0f);
/* Flip horizontally */
} else if (type == 2) {
matrix.preScale(-1.0f, 1.0f);
} else {
return null;
}
return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(),
matrix, true);
}
/* Save Image Function */
private void saveImgAfterEditing(RelativeLayout perent) {
try {
View content = parentLayoutforImgSaving;
content.setDrawingCacheEnabled(true);
content.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = content.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extr + "/" + getString(R.string.app_name));
if (!mFolder.exists()) {
mFolder.mkdir();
}
Calendar c = Calendar.getInstance();
String s = getString(R.string.app_name) + c.getTimeInMillis()
+ ".png";
File f = new File(mFolder.getAbsolutePath(), s);
FileOutputStream fos = null;
fos = new FileOutputStream(f);
bitmap.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
bitmap.recycle();
Toast.makeText(getBaseContext(), "Image Saved", 5000).show();
addImageGallery(f);
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Failed To Save", 5000).show();
e.printStackTrace();
}
}
/* Save Image to Direct Gallery, No Need to Refresh */
private void addImageGallery(File file) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
}
activity_second.java
<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.MyFirstApp.myfirstapp.Second" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp" >
<ImageView
android:id="#+id/img_back_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:contentDescription="#string/img_back_icon"
android:src="#drawable/icon_back" />
<TextView
android:id="#+id/txtview_app_name_top"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/txtview_app_name_top" />
<ImageView
android:id="#+id/img_save_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:contentDescription="#string/img_save_icon"
android:src="#drawable/icon_save" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/imagelayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomedH"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="23dp"
android:src="#drawable/home" >
</com.MyFirstApp.myfirstapp.TouchImageView>
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomed_secondH"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:visibility="gone" >
</com.MyFirstApp.myfirstapp.TouchImageView>
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomedV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:visibility="gone" >
</com.MyFirstApp.myfirstapp.TouchImageView>
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomed_secondV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:visibility="gone" >
</com.MyFirstApp.myfirstapp.TouchImageView>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/horizontal_list_view"
android:layout_width="wrap_content"
android:layout_height="40dp" >
</com.devsmart.android.ui.HorizontalListView>
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/horizontal_list_view_first"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:choiceMode="singleChoice"
android:listSelector="#drawable/horizontal_list_view_selector"
android:visibility="gone" >
</com.devsmart.android.ui.HorizontalListView>
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/horizontal_list_view_color"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:visibility="gone" >
</com.devsmart.android.ui.HorizontalListView>
</RelativeLayout>
</RelativeLayout>
I want similar to below image...
Thanks in advance.

TouchImageView zoom issue

I am developing a photo-editor app. I have done horizontally and vertically flipping. Now, The problem is that When I choose horizontally flip option and do zoom then choose vertically flip option and do zoom and then I choose horizontally flip option again, Than left TouchImageView is misplaced, but right TouchImageView is in place. Below images explains much better.....
Step-1: Choose image from Gallery....
Step-2: Flip it horizontally....
Step-3: Zoom in horizontal flip....
Step-4: Flip it vertically....
Step-5: Zoom in vertical flip....
Step-6: Now back to horizontal flip....
Now, see step no 3 & 6. Step no.6 must be same as step no.3
What I have done is below.
Second.java
package com.MyFirstApp.myfirstapp;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Random;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.devsmart.android.ui.HorizontalListView;
public class Second extends Activity {
TouchImageView img_to_be_zoomedH, img_to_be_zoomed_secondH,
img_to_be_zoomedV, img_to_be_zoomed_secondV;
ImageView img_back, img_save;
HorizontalListView HListView, HListViewFirst;
/* Save Parent Layout After Editing */
RelativeLayout parentLayoutforImgSaving;
Bitmap bitmap_img, bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
img_to_be_zoomedH = (TouchImageView) findViewById(R.id.img_to_be_zoomedH);
img_to_be_zoomed_secondH = (TouchImageView) findViewById(R.id.img_to_be_zoomed_secondH);
img_to_be_zoomedV = (TouchImageView) findViewById(R.id.img_to_be_zoomedV);
img_to_be_zoomed_secondV = (TouchImageView) findViewById(R.id.img_to_be_zoomed_secondV);
img_back = (ImageView) findViewById(R.id.img_back_icon);
img_save = (ImageView) findViewById(R.id.img_save_icon);
HListView = (HorizontalListView) findViewById(R.id.horizontal_list_view);
HListViewFirst = (HorizontalListView) findViewById(R.id.horizontal_list_view_first);
parentLayoutforImgSaving = (RelativeLayout) findViewById(R.id.imagelayout);
/* Top Back Icon */
img_back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
/* Save Image Icon */
img_save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
saveImgAfterEditing(parentLayoutforImgSaving);
}
});
/* Left Image Touch Event */
img_to_be_zoomedH
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomed_secondH.setZoom(img_to_be_zoomedH);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomedH.getScrollPosition();
img_to_be_zoomed_secondH.setScrollPosition(
1 - pointF_img1.x, pointF_img1.y);
}
});
/* Right Image touch event */
img_to_be_zoomed_secondH
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomedH.setZoom(img_to_be_zoomed_secondH);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomed_secondH
.getScrollPosition();
img_to_be_zoomedH.setScrollPosition(1 - pointF_img1.x,
pointF_img1.y);
}
});
/* Top Image Touch Event */
img_to_be_zoomedV
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomed_secondV.setZoom(img_to_be_zoomedV);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomedV.getScrollPosition();
img_to_be_zoomed_secondV.setScrollPosition(
pointF_img1.x, 1 - pointF_img1.y);
}
});
/* Bottom Image touch event */
img_to_be_zoomed_secondV
.setOnTouchImageViewListener(new com.MyFirstApp.myfirstapp.TouchImageView.OnTouchImageViewListener() {
#Override
public void onMove() {
img_to_be_zoomedV.setZoom(img_to_be_zoomed_secondV);
PointF pointF_img1 = new PointF();
pointF_img1 = img_to_be_zoomed_secondV
.getScrollPosition();
img_to_be_zoomedV.setScrollPosition(pointF_img1.x,
1 - pointF_img1.y);
}
});
int[] HorizontalListImages = new int[] { R.drawable.icon_grid,
R.drawable.icon_text, R.drawable.icon_clip_art };
final int[] HorizontalListImagesFirst = new int[] {
R.drawable.icon_go_back, R.drawable.icon_horizontal_grid,
R.drawable.icon_vertical_grid };
/* Animation References */
final Animation slideUp = AnimationUtils.loadAnimation(
getApplicationContext(), R.anim.slide_up);
final Animation slideDown = AnimationUtils.loadAnimation(
getApplicationContext(), R.anim.slide_down);
/* Setting Adapter for Horizontal List Views */
HorizontalListViewAdapter horizontalListViewAdapter = new HorizontalListViewAdapter(
Second.this, HorizontalListImages);
HListView.setAdapter(horizontalListViewAdapter);
/* Horizontal List View Item Click Listener */
HListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
switch (position) {
case 0:
HorizontalListViewAdapterFirst horizontalListViewAdapterFirst = new HorizontalListViewAdapterFirst(
Second.this, HorizontalListImagesFirst);
HListViewFirst.setAdapter(horizontalListViewAdapterFirst);
HListView.startAnimation(slideDown);
HListView.setVisibility(View.GONE);
HListViewFirst.startAnimation(slideUp);
HListViewFirst.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
});
HListViewFirst.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
/* HighLight Selected Option */
for (int i = 0; i < HListViewFirst.getChildCount(); i++) {
if (position == i) {
HListViewFirst.getChildAt(i).setBackgroundColor(
Color.GRAY);
} else {
HListViewFirst.getChildAt(i).setBackgroundColor(
Color.TRANSPARENT);
}
}
/* Get Device`s Height, Width */
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(
displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
switch (position) {
case 0:
HListViewFirst.startAnimation(slideDown);
HListViewFirst.setVisibility(View.GONE);
HListView.startAnimation(slideUp);
HListView.setVisibility(View.VISIBLE);
break;
case 1:
/* Setting Center Layout For Both Images */
RelativeLayout.LayoutParams ImagelayoutParams1 = new RelativeLayout.LayoutParams(
width, width);
ImagelayoutParams1.addRule(RelativeLayout.CENTER_IN_PARENT);
((RelativeLayout) findViewById(R.id.imagelayout))
.setLayoutParams(ImagelayoutParams1);
/* Setting Left ImageView width, height */
RelativeLayout.LayoutParams layoutParamsLeft = new RelativeLayout.LayoutParams(
width / 2, width);
layoutParamsLeft.setMargins(0, 0, 0, 0);
img_to_be_zoomedH.setLayoutParams(layoutParamsLeft);
img_to_be_zoomedH.setVisibility(view.VISIBLE);
bitmap_img = ((BitmapDrawable) img_to_be_zoomedH
.getDrawable()).getBitmap();
bitmap_img = flipImage(bitmap_img, 2);
img_to_be_zoomed_secondH.setImageBitmap(bitmap_img);
/* Setting Right ImageView width, height */
RelativeLayout.LayoutParams layoutParamsRight = new RelativeLayout.LayoutParams(
width / 2, width);
layoutParamsRight.setMargins(width / 2, 0, 0, 0);
img_to_be_zoomed_secondH.setLayoutParams(layoutParamsRight);
// img_to_be_zoomedH.invalidate();
img_to_be_zoomed_secondH.setVisibility(view.VISIBLE);
/* Hiding Vertical TouchIMageViews */
if ((img_to_be_zoomedV.getVisibility() == view.VISIBLE)
|| (img_to_be_zoomed_secondV.getVisibility() == view.VISIBLE)) {
img_to_be_zoomedV.setVisibility(view.GONE);
img_to_be_zoomed_secondV.setVisibility(view.GONE);
}
break;
case 2:
/* Setting Center Layout For Both Images */
RelativeLayout.LayoutParams ImagelayoutParams2 = new RelativeLayout.LayoutParams(
width, width);
ImagelayoutParams2.addRule(RelativeLayout.CENTER_IN_PARENT);
((RelativeLayout) findViewById(R.id.imagelayout))
.setLayoutParams(ImagelayoutParams2);
/* Setting Top ImageView width, height */
RelativeLayout.LayoutParams layoutParamsTop = new RelativeLayout.LayoutParams(
width, width / 2);
layoutParamsTop.setMargins(0, 0, 0, 0);
img_to_be_zoomedV.setLayoutParams(layoutParamsTop);
img_to_be_zoomedV.setVisibility(view.VISIBLE);
bitmap_img = ((BitmapDrawable) img_to_be_zoomedV
.getDrawable()).getBitmap();
bitmap_img = flipImage(bitmap_img, 1);
img_to_be_zoomed_secondV.setImageBitmap(bitmap_img);
/* Setting Bottom ImageView width, height */
RelativeLayout.LayoutParams layoutParamsBottom = new RelativeLayout.LayoutParams(
width, width / 2);
layoutParamsBottom.setMargins(0, width / 2, 0, 0);
img_to_be_zoomed_secondV
.setLayoutParams(layoutParamsBottom);
// img_to_be_zoomedV.invalidate();
img_to_be_zoomed_secondV.setVisibility(view.VISIBLE);
/* Hiding Horizontal TouchIMageViews */
if ((img_to_be_zoomedH.getVisibility() == view.VISIBLE)
|| (img_to_be_zoomed_secondH.getVisibility() == view.VISIBLE)) {
img_to_be_zoomedH.setVisibility(view.GONE);
img_to_be_zoomed_secondH.setVisibility(view.GONE);
}
break;
default:
break;
}
}
});
/* Getting ImageURI from Gallery from Main Activity */
Uri selectedImgUri = getIntent().getData();
if (selectedImgUri != null) {
String[] selectedImgPath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImgUri,
selectedImgPath, null, null, null);
cursor.moveToFirst();
int indexCol = cursor.getColumnIndex(selectedImgPath[0]);
String imgPath = cursor.getString(indexCol);
cursor.close();
img_to_be_zoomedH.setImageBitmap(BitmapFactory.decodeFile(imgPath));
img_to_be_zoomedV.setImageBitmap(BitmapFactory.decodeFile(imgPath));
}
/* Getting ImageBitmap from Camera from Main Activity */
Intent intent_camera = getIntent();
Bitmap camera_img_bitmap = (Bitmap) intent_camera
.getParcelableExtra("BitmapImage");
if (camera_img_bitmap != null) {
img_to_be_zoomedH.setImageBitmap(camera_img_bitmap);
img_to_be_zoomedV.setImageBitmap(camera_img_bitmap);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/* Flip Image Function */
public Bitmap flipImage(Bitmap src, int type) {
Matrix matrix = new Matrix();
/* Flip vertically */
if (type == 1) {
matrix.preScale(1.0f, -1.0f);
/* Flip horizontally */
} else if (type == 2) {
matrix.preScale(-1.0f, 1.0f);
} else {
return null;
}
return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(),
matrix, true);
}
/* Save Image Function */
private void saveImgAfterEditing(RelativeLayout perent) {
try {
View content = parentLayoutforImgSaving;
content.setDrawingCacheEnabled(true);
content.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = content.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extr + "/" + getString(R.string.app_name));
if (!mFolder.exists()) {
mFolder.mkdir();
}
Calendar c = Calendar.getInstance();
String s = getString(R.string.app_name) + c.getTimeInMillis()
+ ".png";
File f = new File(mFolder.getAbsolutePath(), s);
FileOutputStream fos = null;
fos = new FileOutputStream(f);
bitmap.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
bitmap.recycle();
Toast.makeText(getBaseContext(), "Image Saved", 5000).show();
addImageGallery(f);
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Failed To Save", 5000).show();
e.printStackTrace();
}
}
/* Save Image to Direct Gallery, No Need to Refresh */
private void addImageGallery(File file) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
}
activity_second.xml
<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.MyFirstApp.myfirstapp.Second" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp" >
<ImageView
android:id="#+id/img_back_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:contentDescription="#string/img_back_icon"
android:src="#drawable/icon_back" />
<TextView
android:id="#+id/txtview_app_name_top"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/txtview_app_name_top" />
<ImageView
android:id="#+id/img_save_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:contentDescription="#string/img_save_icon"
android:src="#drawable/icon_save" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/imagelayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomedH"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="23dp"
android:src="#drawable/home" >
</com.MyFirstApp.myfirstapp.TouchImageView>
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomed_secondH"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:visibility="gone" >
</com.MyFirstApp.myfirstapp.TouchImageView>
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomedV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:visibility="gone" >
</com.MyFirstApp.myfirstapp.TouchImageView>
<com.MyFirstApp.myfirstapp.TouchImageView
android:id="#+id/img_to_be_zoomed_secondV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:visibility="gone" >
</com.MyFirstApp.myfirstapp.TouchImageView>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/horizontal_list_view"
android:layout_width="wrap_content"
android:layout_height="40dp" >
</com.devsmart.android.ui.HorizontalListView>
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/horizontal_list_view_first"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:choiceMode="singleChoice"
android:listSelector="#drawable/horizontal_list_view_selector"
android:visibility="gone" >
</com.devsmart.android.ui.HorizontalListView>
</RelativeLayout>
</RelativeLayout>
Thanks in advance.

ListView clicked on left or right side

I have a ListView, and when you tap on an item, I want to check whether the item was clicked on on the left or the right half. This is the code I have:
package com.testapp.toroco;
import android.support.v4.app.ListFragment;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class FragmentA extends ListFragment implements OnClickListener {
int width;
public void onCreate(Bundle b) {
super.onCreate(b);
getSize();
}
public void getSize(){
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] itemlist = {"A","b","C","d","E","f"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (getActivity(),R.layout.layoutrow,R.id.name,itemlist);
setListAdapter(adapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// do something with the data
}
public boolean dispatchTouchEvent(MotionEvent event) {
int actionX = (int) event.getX();
int middlePoint = width/2 ;
if(actionX >middlePoint ){
Log.d("Touch", "Right");
}else if (actionX <middlePoint ){
Log.d("Touch", "Left");
}
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I am aware that I haven't properly added the listener and that The onListItemClick and dispatchTouchEvent are currently two seperate events. But unfortunately I have now idea how I can accomplish that. Is there a better way to find out on which half it was clicked on? If not, on which View do I have to register the ClickListener and how can I make one Event (onListItemClick and dispatchTouchEvent) check the outcome of the other?
Thank you very much for your help!
Tweek! You can create a custom listview with custom layout, in which you can add two views to left and right half and setOnClickListeners() for both these views.
Edit:
Ill give you an example on how to do it.
create an xml layout for list item : listItem.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1" >
<LinearLayout
android:id="#+id/leftPart"
android:layout_width="0dip"
android:layout_height="10dp"
android:orientation="vertical"
android:layout_weight="0.5"
android:background="#ff0000" >
</LinearLayout>
<LinearLayout
android:id="#+id/rightPart"
android:layout_width="0dip"
android:layout_height="10dp"
android:orientation="vertical"
android:layout_weight="0.5"
android:background="#00ff00" >
</LinearLayout>
</LinearLayout>
Write a custom adapter for your listView: CustomListAdapter.java
public class CustomListAdapter extends ArrayAdapter<String> {
int resource;
// change String to your required datatype
public CustomListAdapter(Context context, int resource, int textViewResourceId, String[] objects) {
super(context, resource, textViewResourceId, objects);
this.resource = resource;
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(resource, parent, false);
}
final int pos = position;
convertView.findViewById(R.id.leftPart).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Do your work here
Toast.makeText(getContext(), "Left Side of " + pos + "th element clicked", Toast.LENGTH_SHORT).show();
}
});
convertView.findViewById(R.id.rightPart).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Do your work here
Toast.makeText(getContext(), "Right Side of " + pos + "th element clicked", Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
Set adapter to your ListView like this,
yourListView.setAdapter(getActivity(),R.id.listItem, /*your data*/);
I haven't tested this code, but this should work.
In your dispatchTouchEvent method :
public boolean dispatchTouchEvent(MotionEvent event) {
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
x1 = event.getX();
y1 = event.getY();
System.out.println("x1-- "+x1);
System.out.println("y1-- "+y1);
dx = x1 - y1 ;
break ;
case MotionEvent.ACTION_UP:
x2 = event.getX();
y2 = event.getY();
System.out.println("x2-- "+x2);
System.out.println("y2-- "+y2);
dy = x2 - y2 ;
}
if(dx > 1)
{
System.out.println(" clicked on right side ");
}else
{
System.out.println(" clicked on left side ");
}
return false;
}

Implement Swipe in ListView

I want to implement Swipe in ListView like in Samsung Android Phones calling function
I have a list shown in below image :
Now when I swipe right side at some distance of swipe from left i.e 25% distance it just changed background, like call function in Samsung device or like SwipeListView:
need solution for this.
try this code :
main.xml file
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
raw.xml
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:gravity="left"
android:text="ABC"
android:textSize="22sp" />
<LinearLayout
android:id="#+id/delete_lay"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#55ff0000"
android:visibility="gone" >
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:src="#drawable/ic_menu_delete"
android:visibility="visible" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:gravity="left"
android:text="Deleting..."
android:textColor="#ff0000"
android:textSize="22sp"
android:textStyle="bold" />
</LinearLayout>
MainActivity.java
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import de.timroes.swipetodismiss.SwipeDismissList;
import de.timroes.swipetodismiss.SwipeDismissList.SwipeDirection;
import de.timroes.swipetodismiss.SwipeDismissList.UndoMode;
import de.timroes.swipetodismiss.SwipeDismissList.Undoable;
public class MainActivity extends Activity {
ArrayList<String> listData;
ListView listView;
ArrayAdapter<String> adapter;
SwipeListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
listData = new ArrayList<String>();
listData.add("item 1");
listData.add("item 2");
listData.add("item 3");
listData.add("item 4");
listData.add("item 5");
listData.add("item 6");
listData.add("item 7");
listData.add("item 8");
listData.add("item 9");
listData.add("item 10");
listData.add("item 11");
listData.add("item 12");
listData.add("item 13");
listData.add("item 14");
listData.add("item 15");
listData.add("item 16");
listData.add("item 17");
listAdapter = new SwipeListAdapter(MainActivity.this);
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
SwipeDismissList.OnDismissCallback callback = new SwipeDismissList.OnDismissCallback() {
#Override
public Undoable onDismiss(AbsListView listView, int position) {
View view = (View) listView.getChildAt(0);
view.animate().alpha(1).setDuration(200).translationX(10);
listAdapter.remove(position);
return null;
}
};
UndoMode mode = SwipeDismissList.UndoMode.SINGLE_UNDO;
SwipeDismissList swipeList = new SwipeDismissList(listView, callback,
mode);
swipeList.setSwipeDirection(SwipeDirection.END);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class SwipeListAdapter extends BaseAdapter {
Context mContext;
public SwipeListAdapter(Context context) {
this.mContext = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private void remove(int pos) {
listData.remove(pos);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(
R.layout.raw, null);
}
TextView textView = (TextView) convertView
.findViewById(R.id.name);
textView.setText(listData.get(position));
RelativeLayout layout = (RelativeLayout) convertView
.findViewById(R.id.parentLayout);
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT, 50);
layout.setLayoutParams(params);
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
}
}
SwipeDismissList.java
import static com.nineoldandroids.view.ViewHelper.setAlpha;
import static com.nineoldandroids.view.ViewHelper.setTranslationX;
import static com.nineoldandroids.view.ViewPropertyAnimator.animate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.ValueAnimator;
public final class SwipeDismissList implements View.OnTouchListener {
// Cached ViewConfiguration and system-wide constant values
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;
// Fixed properties
private AbsListView mListView;
private OnDismissCallback mCallback;
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
// Transient properties
private SortedSet<PendingDismissData> mPendingDismisses = new TreeSet<PendingDismissData>();
private int mDismissAnimationRefCount = 0;
private float mDownX;
private boolean mSwiping;
private VelocityTracker mVelocityTracker;
private int mDownPosition;
private View mDownView;
private boolean mPaused;
private float mDensity;
private boolean mSwipeDisabled;
private UndoMode mMode;
private List<Undoable> mUndoActions;
private Handler mHandler;
private PopupWindow mUndoPopup;
private TextView mUndoText;
private Button mUndoButton;
private SwipeDirection mSwipeDirection = SwipeDirection.BOTH;
private int mAutoHideDelay = 5000;
private String mDeleteString = "Item deleted";
private String mDeleteMultipleString = "%d items deleted";
private boolean mTouchBeforeAutoHide = true;
private int mDelayedMsgId;
View frontView;
View backView;
RelativeLayout layout ;
public enum UndoMode {
SINGLE_UNDO,
MULTI_UNDO,
COLLAPSED_UNDO
};
public enum SwipeDirection {
BOTH,
START,
END
}
public interface OnDismissCallback {
Undoable onDismiss(AbsListView listView, int position);
}
public abstract static class Undoable {
public String getTitle() {
return null;
}
public abstract void undo();
public void discard() { }
}
public SwipeDismissList(AbsListView listView, OnDismissCallback callback) {
this(listView, callback, UndoMode.SINGLE_UNDO);
}
public SwipeDismissList(AbsListView listView, OnDismissCallback callback, UndoMode mode) {
if(listView == null) {
throw new IllegalArgumentException("listview must not be null.");
}
mHandler = new HideUndoPopupHandler();
mListView = listView;
mCallback = callback;
mMode = mode;
ViewConfiguration vc = ViewConfiguration.get(listView.getContext());
mSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
mAnimationTime = listView.getContext().getResources().getInteger(
android.R.integer.config_shortAnimTime);
mDensity = mListView.getResources().getDisplayMetrics().density;
// -- Load undo popup --
LayoutInflater inflater = (LayoutInflater) mListView.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.undo_popup, null);
mUndoButton = (Button)v.findViewById(R.id.undo);
mUndoButton.setOnClickListener(new UndoHandler());
mUndoButton.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// If user tabs "undo" button, reset delay time to remove popup
mDelayedMsgId++;
return false;
}
});
mUndoText = (TextView)v.findViewById(R.id.text);
mUndoPopup = new PopupWindow(v);
mUndoPopup.setAnimationStyle(R.style.fade_animation);
// Get scren width in dp and set width respectively
int xdensity = (int)(mListView.getContext().getResources().getDisplayMetrics().widthPixels / mDensity);
if(xdensity < 300) {
mUndoPopup.setWidth((int)(mDensity * 280));
} else if(xdensity < 350) {
mUndoPopup.setWidth((int)(mDensity * 300));
} else if(xdensity < 500) {
mUndoPopup.setWidth((int)(mDensity * 330));
} else {
mUndoPopup.setWidth((int)(mDensity * 450));
}
mUndoPopup.setHeight((int)(mDensity * 56));
// -- END Load undo popu --
listView.setOnTouchListener(this);
listView.setOnScrollListener(this.makeScrollListener());
switch(mode) {
case SINGLE_UNDO:
mUndoActions = new ArrayList<Undoable>(1);
break;
default:
mUndoActions = new ArrayList<Undoable>(10);
break;
}
}
private void setEnabled(boolean enabled) {
mPaused = !enabled;
}
public void setAutoHideDelay(int delay) {
mAutoHideDelay = delay;
}
public void setSwipeDirection(SwipeDirection direction) {
mSwipeDirection = direction;
}
public void setUndoString(String msg) {
mDeleteString = msg;
}
public void setUndoMultipleString(String msg) {
mDeleteMultipleString = msg;
}
public void setRequireTouchBeforeDismiss(boolean require) {
mTouchBeforeAutoHide = require;
}
public void discardUndo() {
for(Undoable undoable : mUndoActions) {
undoable.discard();
}
mUndoActions.clear();
mUndoPopup.dismiss();
}
private AbsListView.OnScrollListener makeScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
};
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (this.mSwipeDisabled) {
return false;
}
if (mViewWidth < 2) {
mViewWidth = mListView.getWidth();
}
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
if (mPaused) {
return false;
}
// TODO: ensure this is a finger, and set a flag
// Find the child view that was touched (perform a hit test)
Rect rect = new Rect();
int childCount = mListView.getChildCount();
int[] listViewCoords = new int[2];
mListView.getLocationOnScreen(listViewCoords);
int x = (int) motionEvent.getRawX() - listViewCoords[0];
int y = (int) motionEvent.getRawY() - listViewCoords[1];
View child;
for (int i = 0; i < childCount; i++) {
child = mListView.getChildAt(i);
child.getHitRect(rect);
if (rect.contains(x, y)) {
mDownView = child;
break;
}
}
if (mDownView != null) {
mDownX = motionEvent.getRawX();
mDownPosition = mListView.getPositionForView(mDownView);
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(motionEvent);
}
view.onTouchEvent(motionEvent);
return true;
}
case MotionEvent.ACTION_UP: {
if (mVelocityTracker == null) {
break;
}
float deltaX = motionEvent.getRawX() - mDownX;
mVelocityTracker.addMovement(motionEvent);
mVelocityTracker.computeCurrentVelocity(1000);
float velocityX = Math.abs(mVelocityTracker.getXVelocity());
float velocityY = Math.abs(mVelocityTracker.getYVelocity());
boolean dismiss = false;
boolean dismissRight = false;
if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) {
dismiss = true;
dismissRight = deltaX > 0;
} else if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity
&& velocityY < velocityX && mSwiping && isDirectionValid(mVelocityTracker.getXVelocity())
&& deltaX >= mViewWidth * 0.2f) {
dismiss = true;
dismissRight = mVelocityTracker.getXVelocity() > 0;
}
if (dismiss) {
// dismiss
final View downView = frontView; // mDownView gets null'd before animation ends
final int downPosition = mDownPosition;
++mDismissAnimationRefCount;
animate(frontView)
.translationX(dismissRight ? mViewWidth : -mViewWidth)
.alpha(0)
.setDuration(mAnimationTime)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
performDismiss(downView, downPosition);
}
});
} else {
// cancel
animate(frontView)
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker = null;
mDownX = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
if(backView != null) {
backView.setVisibility(View.GONE);
frontView.setVisibility(View.VISIBLE);
setTranslationX(frontView, 0);
layout = null;
backView = null;
frontView = null;
}
break;
}
case MotionEvent.ACTION_MOVE: {
if(mTouchBeforeAutoHide && mUndoPopup.isShowing()) {
// Send a delayed message to hide popup
mHandler.sendMessageDelayed(mHandler.obtainMessage(mDelayedMsgId),
mAutoHideDelay);
}
if (mVelocityTracker == null || mPaused) {
break;
}
mVelocityTracker.addMovement(motionEvent);
float deltaX = motionEvent.getRawX() - mDownX;
// Only start swipe in correct direction
if(isDirectionValid(deltaX)) {
if (Math.abs(deltaX) > mSlop) {
mSwiping = true;
mListView.requestDisallowInterceptTouchEvent(true);
// Cancel ListView's touch (un-highlighting the item)
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL
| (motionEvent.getActionIndex()
<< MotionEvent.ACTION_POINTER_INDEX_SHIFT));
mListView.onTouchEvent(cancelEvent);
}
} else {
mDownX = motionEvent.getRawX();
deltaX = 0;
}
if(layout == null) {
layout = (RelativeLayout) mDownView;
frontView = layout.getChildAt(0);
backView = layout.getChildAt(1);
}
if(deltaX > 50) {
backView.setVisibility(View.VISIBLE);
}
if (mSwiping) {
setTranslationX(frontView, deltaX);
setAlpha(frontView, Math.max(0f, Math.min(1f,
1f - 2f * Math.abs(deltaX) / mViewWidth)));
return true;
}
break;
}
}
return false;
}
private boolean isDirectionValid(float deltaX) {
int rtlSign = 1;
// On API level 17 and above, check if we are in a Right-To-Left layout
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if(mListView.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
rtlSign = -1;
}
}
// Check if swipe has been done in the corret direction
switch(mSwipeDirection) {
default:
case BOTH:
return true;
case START:
return rtlSign * deltaX < 0;
case END:
return rtlSign * deltaX > 0;
}
}
class PendingDismissData implements Comparable<PendingDismissData> {
public int position;
public View view;
public PendingDismissData(int position, View view) {
this.position = position;
this.view = view;
}
#Override
public int compareTo(PendingDismissData other) {
// Sort by descending position
return other.position - position;
}
}
private void performDismiss(final View dismissView, final int dismissPosition) {
// Animate the dismissed list item to zero-height and fire the dismiss callback when
// all dismissed list item animations have completed. This triggers layout on each animation
// frame; in the future we may want to do something smarter and more performant.
final ViewGroup.LayoutParams lp = dismissView.getLayoutParams();
final int originalHeight = dismissView.getHeight();
ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);
animator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
--mDismissAnimationRefCount;
if (mDismissAnimationRefCount == 0) {
// No active animations, process all pending dismisses.
for(PendingDismissData dismiss : mPendingDismisses) {
if(mMode == UndoMode.SINGLE_UNDO) {
for(Undoable undoable : mUndoActions) {
undoable.discard();
}
mUndoActions.clear();
}
Undoable undoable = mCallback.onDismiss(mListView, dismiss.position);
if(undoable != null) {
mUndoActions.add(undoable);
}
mDelayedMsgId++;
}
if(!mUndoActions.isEmpty()) {
changePopupText();
changeButtonLabel();
// Show undo popup
mUndoPopup.showAtLocation(mListView,
Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM,
0, (int)(mDensity * 15));
// Queue the dismiss only if required
if(!mTouchBeforeAutoHide) {
// Send a delayed message to hide popup
mHandler.sendMessageDelayed(mHandler.obtainMessage(mDelayedMsgId),
mAutoHideDelay);
}
}
ViewGroup.LayoutParams lp;
for (PendingDismissData pendingDismiss : mPendingDismisses) {
// Reset view presentation
setAlpha(pendingDismiss.view, 1f);
setTranslationX(pendingDismiss.view, 0);
lp = pendingDismiss.view.getLayoutParams();
lp.height = originalHeight;
pendingDismiss.view.setLayoutParams(lp);
}
mPendingDismisses.clear();
}
}
});
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
lp.height = (Integer) valueAnimator.getAnimatedValue();
dismissView.setLayoutParams(lp);
}
});
mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
animator.start();
}
private void changePopupText() {
String msg = "";
if(mUndoActions.size() > 1 && mDeleteMultipleString != null) {
msg = String.format(mDeleteMultipleString, mUndoActions.size());
} else if(mUndoActions.size() >= 1) {
// Set title from single undoable or when no multiple deletion string
// is given
if(mUndoActions.get(mUndoActions.size() - 1).getTitle() != null) {
msg = mUndoActions.get(mUndoActions.size() - 1).getTitle();
} else {
msg = mDeleteString;
}
}
mUndoText.setText(msg);
}
private void changeButtonLabel() {
String msg;
if(mUndoActions.size() > 1 && mMode == UndoMode.COLLAPSED_UNDO) {
msg = mListView.getResources().getString(R.string.undoall);
} else {
msg = mListView.getResources().getString(R.string.undo);
}
mUndoButton.setText(msg);
}
/**
* Takes care of undoing a dismiss. This will be added as a
* {#link View.OnClickListener} to the undo button in the undo popup.
*/
private class UndoHandler implements View.OnClickListener {
public void onClick(View v) {
if(!mUndoActions.isEmpty()) {
switch(mMode) {
case SINGLE_UNDO:
mUndoActions.get(0).undo();
mUndoActions.clear();
break;
case COLLAPSED_UNDO:
Collections.reverse(mUndoActions);
for(Undoable undo : mUndoActions) {
undo.undo();
}
mUndoActions.clear();
break;
case MULTI_UNDO:
mUndoActions.get(mUndoActions.size() - 1).undo();
mUndoActions.remove(mUndoActions.size() - 1);
break;
}
}
// Dismiss dialog or change text
if(mUndoActions.isEmpty()) {
mUndoPopup.dismiss();
} else {
changePopupText();
changeButtonLabel();
}
mDelayedMsgId++;
}
}
/**
* Handler used to hide the undo popup after a special delay.
*/
private class HideUndoPopupHandler extends Handler {
#Override
public void handleMessage(Message msg) {
if(msg.what == mDelayedMsgId) {
// Call discard on any element
for(Undoable undo : mUndoActions) {
undo.discard();
}
mUndoActions.clear();
mUndoPopup.dismiss();
}
}
}
/**
* Enable/disable swipe.
*/
public void setSwipeDisabled(boolean disabled) {
this.mSwipeDisabled = disabled;
}
}
enjoy!
Use a ListView extension such as android-swipelistview.
You may also need to refer to the demo source. Instructions for setting up the demo can be found here.
To make a phone call when the user swipes left, add the below code to the instance of SwipeListView:
src > activities > SwipeListViewExampleActivity.java > onCreate()
swipeListView.setSwipeListViewListener(new BaseSwipeListViewListener() {
#Override
public void onOpened(int position, boolean toRight) {
if(!toRight) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:0123456789"));
startActivity(intent);
}
}
});
For swipe right you can set it to dismiss which should be sufficient for what you are trying to achieve.
res > layout > swipe-list-view-activity.xml > SwipeListView
swipe:swipeActionRight="dismiss"
you can use this library https://github.com/timroes/EnhancedListView An Android ListView with enhanced functionality (e.g. Swipe To Dismiss or Undo).

Update Progressbar according to ImageSwitcher progress

I currently have implemented an ImageSwitcher in my app, which slides through an array of pictures. Now I want to have a ProgressBar under the picture which shows on which position we are in the collection so the user gets a feeling of how much pictures are left.
Is this possible? Can I have some advices on how I might implement this?
Picture:
progress
[--|--------]
My ImageSwticher:
package com.example.cfaslides;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ProgressBar;
import android.widget.ViewSwitcher;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.view.Window;
import android.content.Context;
public class l2_AltInvestActivity extends Activity implements ViewFactory {
ImageSwitcher imageSwitcher;
Integer[] imageList = {
R.drawable.av_01,
R.drawable.av_02,
R.drawable.av_03,
R.drawable.av_04,
R.drawable.av_05
};
int curIndex=0;
int maxIndex = 4; //# imageList -1
int downX, upX;
private Animation mIn1, mOut1, mIn2, mOut2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slider);
final ProgressBar mProgressBar = (ProgressBar) findViewById(R.id.progressB);
mProgressBar.setProgress(0);
mProgressBar.setMax(maxIndex);
mProgressBar.setVisibility(View.VISIBLE);
mIn1 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,android.R.anim.slide_in_left);
mOut1 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,android.R.anim.slide_out_right);
mIn2 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,R.anim.slide_in_right);
mOut2 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,R.anim.slide_out_left);
AnimationListener mAnimListener = new AnimationListener() {
public void onAnimationEnd(Animation animation) {
// the in animation has ended so update the ProgressBar with the new
// progress
mProgressBar.setProgress(curIndex); // I don't know your progress?!?
}
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
// rest of the callbacks
};
//set this listener for the both of the in animations
mIn1.setAnimationListener(mAnimListener);
mIn2.setAnimationListener(mAnimListener);
// rest of the onCreate method
imageSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
imageSwitcher.setFactory(this);
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));
imageSwitcher.setImageResource(imageList[curIndex]);
imageSwitcher.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
downX = (int) event.getX();
Log.i("event.getX()", " downX " + downX);
return true;
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
upX = (int) event.getX();
Log.i("event.getX()", " upX " + downX);
if (upX - downX > 100) {
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(l2_AltInvestActivity.this,android.R.anim.slide_in_left));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(l2_AltInvestActivity.this,android.R.anim.slide_out_right));
//curIndex current image index in array viewed by user
curIndex--;
if (curIndex < 0) {
curIndex = maxIndex; //maximum
}
//imageList :-image list array
imageSwitcher.setImageResource(imageList[curIndex]);
//GalleryActivity.this.setTitle(curIndex);
}
else if (downX -upX > -100) {
curIndex++;
if (curIndex > maxIndex) {
curIndex = 0;
}
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(l2_AltInvestActivity.this,R.anim.slide_in_right));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(l2_AltInvestActivity.this,R.anim.slide_out_left));
imageSwitcher.setImageResource(imageList[curIndex]);
//GalleryActivity.this.setTitle(curIndex);
}
return true;
}
return false;
}
});
} //END onCreate
#Override
public View makeView() {
ImageView i = new ImageView(this);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
i.setBackgroundColor(0xFF000000);
return i;
} //END makeView
} // END Class
Slider:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/widget32"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ProgressBar
android:id="#+id/progressB"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageSwitcher android:id="#+id/switcher"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
>
</ImageSwitcher>
</RelativeLayout>
now i like to have an progress bar under the picture which shows on
which position we are in the collection. so that someone gets a
feeling how much pictures are left.
Place a ProgressBar in your R.layout.slider layout file
Make the four different Animations that you used for the ImageSwitcher's transitions as fields in your Activity and also set an AnimationListener for each of them:
//...
private Animation mIn1, mOut1, mIn2, mOut2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slider);
final ProgressBar = (ProgressBar) findViewById(R.id.theIdOfTheProgressBar);
mIn1 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,android.R.anim.slide_in_left);
mOut1 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,android.R.anim.slide_out_right);
mIn2 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,R.anim.slide_in_right);
mOut2 = AnimationUtils.loadAnimation(l2_AltInvestActivity.this,R.anim.slide_out_left);
AnimationListener mAnimListener = new AnimationListener() {
public void onAnimationEnd(Animation animation) {
// the in animation has ended so update the ProgressBar with the new
// progress
mProgressBar.setProgress(curIndex); // I don't know your progress?!?
}
// rest of the callbacks
});
//set this listener for the both of the in animations
mIn1.setAnimationListener(mAnimListener);
mIn2.setAnimationListener(mAnimListener);
// rest of the onCreate method
In the onTouch method update the ImageSwitcher with the proper animations(from mIn1, mOut1, mIn2, mOut2)

Categories

Resources