ListView clicked on left or right side - android

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;
}

Related

PageAdapter + VerticalViewPager NOT working Together. Why?

I'm trying to figure out why my images within class CustomPagerAdapter mResources are NOT showing up once the VerticalViewPager widget appears -- nothing on start and nothing during vertical swipe.
I've been at it for a couple days but just cant crack it. Doesnt help the documentation on ViewPager / Adapters isnt very clear.
Using - Nexus 6 AVD, minSdkVersion = 19
When i attempt to scroll up (single click from the bottom and swipe up all the way to the top) i then receive this error message...
*AndroidRuntime: FATAL EXCEPTION: main
Process: sparktic.com.verticalviewpager, PID: 19242
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)*
AFAIK i'm adding and removing pager_item correctly.
java/ MainActivity.java
package sparktic.com.verticalviewpager;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity
{
VerticalViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPager = findViewById(R.id.viewpager);
CustomPagerAdapter adapter = new CustomPagerAdapter(this);
mPager.setAdapter(adapter);
}
class CustomPagerAdapter extends PagerAdapter
{
Context mContext;
public LayoutInflater mLayoutInflater;
int[] mResources = {
R.drawable.first, // Dload: https://i.imgur.com/suvAa9x.jpg
R.drawable.second, // Dload: https://i.imgur.com/c2f0Hvy.jpg
R.drawable.third // Dload: https://i.imgur.com/0GAs8qp.jpg
};
public CustomPagerAdapter(Context context)
{
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount()
{
return mResources.length;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position)
{
View itemView = mLayoutInflater.inflate(R.layout.pager_item, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(mResources[position]);
container.addView(imageView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
container.removeView((LinearLayout) object);
}
}
}
layout/ 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="sparktic.com.verticalviewpager.MainActivity">
<sparktic.com.verticalviewpager.VerticalViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
layout/ pager_item.xml
<?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="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView" />
</LinearLayout>
java/ VerticalViewPager.java
package sparktic.com.verticalviewpager;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class VerticalViewPager extends ViewPager
{
public VerticalViewPager(Context context)
{
this(context, null);
}
public VerticalViewPager(Context context, AttributeSet attrs)
{
super(context, attrs);
init();
}
#Override
public boolean canScrollHorizontally(int direction)
{
return false;
}
#Override
public boolean canScrollVertically(int direction)
{
return super.canScrollHorizontally(direction);
}
private void init()
{
setPageTransformer(true, new VerticalPageTransformer());
setOverScrollMode(View.OVER_SCROLL_NEVER);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev)
{
final boolean toIntercept = super.onInterceptTouchEvent(flipXY(ev));
flipXY(ev);
return toIntercept;
}
#Override
public boolean onTouchEvent(MotionEvent ev)
{
final boolean toHandle = super.onTouchEvent(flipXY(ev));
flipXY(ev);
return toHandle;
}
private MotionEvent flipXY(MotionEvent ev)
{
final float width = getWidth();
final float height = getHeight();
final float x = (ev.getY() / height) * width;
final float y = (ev.getX() / width) * height;
ev.setLocation(x, y);
return ev;
}
private static final class VerticalPageTransformer implements ViewPager.PageTransformer
{
#Override
public void transformPage(View view, float position)
{
final int pageWidth = view.getWidth();
final int pageHeight = view.getHeight();
if (position < -1)
{
view.setAlpha(0);
}
else if (position <= 1)
{
view.setAlpha(1);
view.setTranslationX(pageWidth * -position);
float yPosition = position * pageHeight;
view.setTranslationY(yPosition);
}
else
{
view.setAlpha(0);
}
}
}
}
Solved my own problem. In case it helps someone else...
the issue was within "instantiateItem" method.
container.addView(imageView); should have been container.addView(itemView);
I still dont have a solid grasp as to what is happening within the PageAdapter overrides but it works so i'll take the win and move on.

[Android]onTouch in child View is not responding

I have been working on making Sudoku grid whose cell's value changes whenever I touch on a cell. So I have implemented this sudoku grid in a LinearLayout by Child View, and tried using OnTouch method, but it is not working. I tried using log method to check whether onTouch is actually called, but it seemes that this method is perfectly ignored. I have been searching for solutions on other question, but it seems none of those solutions helped. I feel kinda suck here, and any help would be greatly appreciated.
Here is my code:
SudokuActivity.java
package snacker.nonogramsolver;
import ...; /*many things are imported here*/
public class SudokuActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sudoku);
Button btn = (Button)findViewById(R.id.btn_clear);
Sudoku sdk = new Sudoku(this);
sdk.setOnTouchListener(sdk);
}
}
;
Sudoku.java
package snacker.nonogramsolver;
import ...;
public class Sudoku extends View implements View.OnTouchListener {
int mWidth = 9;
int mHeight = 9;
int mCellWidth, mCellHeight;
int mCellMargin;
int mEdgeThick;
int mStatus;
int mTextSize;
int mXNow = -1, mYNow = -1;
int[][] mBoard = new int[9][9];
Point mBoardPt;
Paint mTextPaint, mTileEdgePaint;
final static int VALID = 0;
public Sudoku(Context context){
super(context);
initializeBoard();
}
public Sudoku(Context context, AttributeSet attrs){
super(context, attrs);
initializeBoard();
}
#Override
protected void onDraw(Canvas canvas){
/* There are some codes here */
Log.d("LogTest","OnDraw Complete");
}
public void initializeBoard(){
for (int x=0; x< mWidth; x++){
for (int y=0; y< mHeight; y++){
mBoard[x][y] = 0;
}
}
invalidate();
}
public boolean onTouch(View v, MotionEvent event){
Log.d("LogTest","Touched?"); /* LOG NOT ACTIVE HERE */
if(event.getAction() == MotionEvent.ACTION_DOWN){
mXNow = getBoardX(event.getX());
Log.d("LogTest","" + mXNow); /* LOG NOT ACTIVE HERE */
mYNow = getBoardY(event.getY());
Log.d("LogTest","" + mYNow); /* LOG NOT ACTIVE HERE */
mBoard[mXNow][mYNow] = mBoard[mXNow][mYNow] + 1;
invalidate();
return true;
}
else return false;
}
int getBoardX(float scrx){
int x = (int)((scrx) / mCellWidth);
if (x < 0) x = 0;
if (x > 8) x= 8;
return x;
}
int getBoardY(float scry){
int y = (int)((scry) / mCellHeight);
if (y < 0) y = 0;
if (y > 8) y = 8;
return y;
}
}
Edit: added activity XML file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:id="#+id/activity_sudoku"
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="snacker.nonogramsolver.SudokuActivity">
<snacker.nonogramsolver.Sudoku
android:id="#+id/SudokuGrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn_clear"
android:layout_width="150dp"
android:layout_height="30dp"
android:layout_weight="0.06"
android:text="Clear" />
</LinearLayout>
You cannot directly add touchListener by just creating object of
Sudoku class. You should add view in xml or programatically.
Your Activity
public class MyActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//initializing custom views
MyCustomView1 myCustomView1 = new MyCustomView1(parameterList);
MyCustomView2 myCustomView2 = new MyCustomView2(parameterList);
//adding both custom views to the main activity
mainView.addView(myCustomView1);
mainView.addView(myCustomView1);
//adding custom listener to the custom view 1
myCustomView1.setCustomEventListener(new OnCustomEventListener() {
#Override
public void onEvent() {
//firing an event of custom view 1
Toast.makeText(MainActivity.this, "Touched custom view 1",
Toast.LENGTH_SHORT).show();
}
});
//adding custom listener to the custom view 2
myCustomView2.setCustomEventListener(new OnCustomEventListener() {
#Override
public void onEvent() {
//firing an event of custom view 2
Toast.makeText(MainActivity.this, "Touched custom view 2",
Toast.LENGTH_SHORT).show();
}
});
}
}
Your CustomView 1
public class MyCustomView1 extends LinearLayout{
OnCustomEventListener myCustomEventListener;
public MyCustomView1(ParameterList){
super(ContextFromParameterList);
//Just adding something to the custom view 1 in order to distinguish it on the screen
TextView tv = new TextView(ContextFromParameterList);
tv.setText("Hello world from custom view 1");
addView(tv);
this.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
//delegating one event to another (delegating touch event to custom event)
if (MyCustomView1.this.myCustomEventListener != null)
MyCustomView1.this.myCustomEventListener.onEvent();
return false;
}
}); }
public void setCustomEventListener(OnCustomEventListener
eventListener) {
//setting custom listener from activity
myCustomEventListener = eventListener; } }
Your CustomView2
public class MyCustomView2 extends LinearLayout {
OnCustomEventListener myCustomEventListener;
public MyCustomView2(ParameterList) {
super(ContextFromParameterList);
//Just adding something to the custom view 1 in order to distinguish it on the screen
TextView tv = new TextView(ContextFromParameterList);
tv.setText("Hello world from custom view 2");
addView(tv);
this.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
//delegating one event to another (delegating touch event to custom event)
if (MyCustomView2.this.myCustomEventListener != null)
MyCustomView2.this.myCustomEventListener.onEvent();
return false;
}
});
}
public void setCustomEventListener(OnCustomEventListener eventListener) {
//setting custom listener from activity
myCustomEventListener = eventListener;
}
}
Your listener interface:
public interface OnCustomEventListener{
//interface defines one method. Can be more and methods may have parameters
public void onEvent();
}

Converting Activity to use Fragments?

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().

how to add a swipe view to these existing coding

I need to add a swipe view in tab activity.In these below xml coding
I just created a six tabs namely home,blog,audio,video,more and
gallery.
The Tabs are created perfectly.But I cannot able to know how to add a swipe for that six tabs.I need
to add a right to left swipe and left to right swipe.
layout_home.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#drawable/bottom_bar"
android:layout_weight="0" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout
android:id="#+id/tab_home"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+id/tab_video"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+id/tab_audio"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</FrameLayout>
<FrameLayout
android:id="#+id/tab_blog"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</FrameLayout>
<FrameLayout
android:id="#+id/tab_gal"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</FrameLayout>
<FrameLayout
android:id="#+id/tab_more"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</FrameLayout>
</FrameLayout>
<com.sit.gems.util.AppPromoPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0" />
</LinearLayout>
</TabHost>
</LinearLayout>
AppPromoPager.java:
These is the AppPromopager.Here I am using the ViewPager.
package com.sit.gems.util;
import java.net.URLDecoder;
import java.util.List;
import android.content.Context;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import com.gems.android.R;
import com.sit.gems.app.AppData;
import com.sit.gems.util.ImageCache.ImageCacheParams;
public class AppPromoPager extends RelativeLayout implements
ViewPager.OnPageChangeListener {
//private PromoPageIndicator indicator;
private PromoPagerListener listener;
private Handler trackerHandler = new Handler();
private ImageFetcher mImageFetcher;
public AppPromoPager(Context context) {
super(context);
}
public AppPromoPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AppPromoPager(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void init(FragmentActivity context, List<String> promotions) {
ImageCacheParams cacheParams = new ImageCacheParams(context, AppConstants.IMAGE_CACHE_DIR);
mImageFetcher = new ImageFetcher(context, AppData.getScreenWidth(),(AppData.getScreenWidth()/2));
mImageFetcher.setLoadingImage(R.drawable.ic_launcher);
mImageFetcher.addImageCache(context.getSupportFragmentManager(), cacheParams);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
ViewPager pager = new ViewPager(context);
ViewPagerAdapter adapter = new ViewPagerAdapter(context, promotions);
pager.setAdapter(adapter);
pager.setCurrentItem(0);
pager.setOnPageChangeListener(this);
addView(pager, params);
//indicator = new PromoPageIndicator(context);
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params1.addRule(RelativeLayout.CENTER_HORIZONTAL);
params1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params1.setMargins(0, 0, 0, 3);
//addView(indicator, params1);
//if (promotions.size() > 1)
// indicator.addCircleImage(promotions.size());
/*pager.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE
&& scrollView != null) {
scrollView.requestDisallowInterceptTouchEvent(true);
}
return false;
}
});*/
}
class ViewPagerAdapter extends PagerAdapter {
Context activity;
List<String> promotions;
public ViewPagerAdapter(Context context, List<String> promotions) {
this.promotions = promotions;
activity = context;
}
public int getCount() {
return promotions.size();
}
public Object instantiateItem(View collection, final int position) {
final ImageView view = new ImageView(activity);
view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
view.setScaleType(ScaleType.CENTER);
String imageUrl = promotions.get(position);
if (imageUrl != null && imageUrl.length() > 0) {
setImage(view, imageUrl);
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.selectedPromo(promotions.get(position),position);
}
});
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
//listener.selectedPosition(arg0);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
listener.selectedPosition(position);
}
public interface PromoPagerListener {
public void selectedPromo(String offer,int postion);
public void selectedPosition(int postion);
}
public void setPromoPagerListener(PromoPagerListener listener) {
this.listener = listener;
}
private void setImage(final ImageView view, final String imageUrl) {
trackerHandler.post(new Runnable() {
#Override
public void run() {
mImageFetcher.loadImage(URLDecoder.decode(imageUrl),view);
}
});
}
}
I thought with the help of viewpager I can able to get a Swipe view.
ViewPager was added in AppPromoPager.
I added an AppPromoPager to that
layout_home.xml file.But till now I didn't get a swipe view.Anybody can help me with these.Thank you.
Better to use the Scrollable Tabs which uses a combination of Swipe view pager with the action bar tabs.
What I did is in each tabcontent, implement the swipe listener. In the tabhost, implement a swipe method.
tabcontent
layout.setOnTouchListener(new OnTouchListener() {
private PointerCoords mDownPos = new PointerCoords();
private PointerCoords mUpPos = new PointerCoords();
#Override
public boolean onTouch(View arg0, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
event.getPointerCoords(0, mDownPos);
return true;
}
case MotionEvent.ACTION_UP: {
event.getPointerCoords(0, mUpPos);
float dx = mDownPos.x - mUpPos.x;
// Check for horizontal wipe
if (Math.abs(dx) > SWIPE_MIN_DISTANCE) {
if (dx > 0) {
mParent.swipe(DIRECTION_RIGHT);
} else {
mParent.swipe(DIRECTION_LEFT);
}
return true;
}
}
}
return false;
}
});
protected void swipe(int direction) {
int current = mTabHost.getCurrentTab();
if (direction == DIRECTION_LEFT) {
int newTab = --current % mTabHost.getTabWidget().getTabCount();
mTabHost.setCurrentTab( (newTab < 0) ? mTabHost.getTabWidget().getTabCount()-1 : newTab);
}
else {
mTabHost.setCurrentTab(++current % mTabHost.getTabWidget().getTabCount());
}
}
hey you should do this by actionBar tabs + viewpager here is a tutorial which let you make what you want.
http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/

(Android) Making Images Visible/Not Visible when touched

This is my updated code. It doesn't detect movement at all now. Maybe I shouldn't be making each Image an instance? Basically I want to user to be able to swipe through all the images to make them dissapear.
Thanks for all the help.
package com.picomputing.mythirdapplication;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
/**
* Created by Paul on 8/13/13.
*/
public class Pin extends ImageView implements View.OnTouchListener {
boolean isPinDown;
public Pin(Context context) {
super(context);
this.isPinDown = false;
}
public Pin(Context context, AttributeSet attrs) {
super(context, attrs);
this.isPinDown = false;
}
public Pin(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.isPinDown = false;
}
public boolean pinDown() {
return this.isPinDown;
}
public void setPinDown() {
this.isPinDown = true;
}
public void setPinUp() {
this.isPinDown = false;
}
public void togglePin() {
if (isPinDown == false)
{
isPinDown = true;
this.setImageResource(Color.TRANSPARENT);
}
else
{
isPinDown = false;
this.setImageResource(R.drawable.pin);
}
}
#Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_MOVE:
int x = (int) event.getX(); //--relative to mLayout--
int y = (int) event.getY(); //--relative to mLayout--
Rect r = new Rect();
view.getHitRect(r);
if(r.contains(x,y) && view instanceof ImageView){
togglePin();
}
}
return true;
}
}
You need to listen and consume ACTION_MOVE events, for the parent view of whatever you are trying to change.
Here's an example with a couple of ImageViews in a LinerLayout as a parent:
public class test extends Activity {
LinearLayout mLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLayout = new LinearLayout(this);
mLayout.setOrientation(LinearLayout.VERTICAL);
for(int i = 0 ; i < 5; i++){
ImageView iv = new ImageView(this);
iv.setImageResource(android.R.drawable.ic_dialog_info);
mLayout.addView(iv);
}
setContentView(mLayout);
mLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_MOVE:
int x = (int) event.getX(); //--relative to mLayout--
int y = (int) event.getY(); //--relative to mLayout--
Rect r = new Rect();
for(int i = 0 ; i < mLayout.getChildCount(); i++){
View v = mLayout.getChildAt(i);
v.getHitRect(r);
if(r.contains(x,y) && v instanceof ImageView){
((ImageView) v).setImageResource(android.R.drawable.ic_dialog_alert);
}
}
}
return true; //-- this means that view is interested in more events of all kinds--
}
});
}
}
I hope I didn't misunderstand your question
but if what you want to do is to prevent multitoch on the image you can add this attribute
android:splitMotionEvents="false"
in the xml in the parent view of the imageview. for example :
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:splitMotionEvents="false"
>
// YOUR IMAGE VIEW HERE
</LinearLayout>
if you have any question feel free to ask in the comment :)
there are mainly three events on OnTouch action_down,Action_move and Action_up. do your coding on action down event i.e when user has touched your view. see the example here:
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
if (arg1.getAction()==MotionEvent.ACTION_DOWN) {
//write your code here
}
else {
if (arg1.getAction()==MotionEvent.ACTION_MOVE){
do things
}
else {
if (arg1.getAction()==MotionEvent.ACTION_UP){
do things
}
}
}

Categories

Resources