I have some ImageViews in my xml file. In my code section I want to move an image according to my wish. For that, I've done event.getx() and event.getY() and then use imageView.layout(). This process is not working. How can i move that image?
I think this might help:
package com.example.moveimageview;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
ImageView im;
RelativeLayout rl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting the wrapper layout from the xml
rl = (RelativeLayout) findViewById(R.id.relative1);
//getting the ImageView from xml
im = (ImageView) findViewById(R.id.myImageView);
rl.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent e) {
// TODO Auto-generated method stub
if(e.getAction()==android.view.MotionEvent.ACTION_DOWN)
{
//sending the new coordinates to the method
//that will change the view's location
setImageViewLocation(e.getX(), e.getY());
return true;
}
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void setImageViewLocation(float x, float y)
{
//setting the coordinates
im.setX(x);
im.setY(y);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
im.invalidate();//invoking the view onDraw
}
});
}
}
(Edit) If you want to your ImageView around, here's the onTouchListner code for this (Same code as before just replace the OnTouchListner with this):
rl.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent e) {
// TODO Auto-generated method stub
if(e.getAction()==android.view.MotionEvent.ACTION_DOWN)
{
//sending the new coordinates to the method
//that will change the view's location
setImageViewLocation(e.getRawX(), e.getRawY());
return true;
}
if(e.getAction()==android.view.MotionEvent.ACTION_MOVE)
{
setImageViewLocation(e.getRawX(), e.getRawY());
return true;
}
return false;
}
});
Related
So I have tried this one tutorial which tells how the gestures work and I made a simple activity which detects the gesture and generates a toast. Now I am working on my project and made my homepage which has a simple Relative layout and an image view. The gestures work find there as well. Now I made a new Help page and tried everything I could but the gesture is not working for me. Is it because of the layout? as this one contains multiple relative and linear layouts.
Given below is my Help activity. I wanna open speech recognition on LongPress (I am trying a toast here but its not working)
Any help would be appreciated. I may be missing out something stupid
package com.example.dell.optasia;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.speech.tts.TextToSpeech;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import static android.view.GestureDetector.*;
import org.w3c.dom.Text;
import java.util.List;
public class Help extends AppCompatActivity implements
OnGestureListener, OnDoubleTapListener {
private GestureDetectorCompat GestureDetect;
public MediaPlayer mp1;
TextView textView;
TextView answer5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
mp1 = MediaPlayer.create(Help.this, R.raw.help);
mp1.start();
ActionBar ab = getSupportActionBar(); //Actionbar
ab.setLogo(R.mipmap.iconlaunch);
ab.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); // set your desired color
ab.setDisplayUseLogoEnabled(true); //shows logo
ab.setDisplayShowHomeEnabled(true); //shows home page
TextView textView= (TextView) findViewById(R.id.textView);
GestureDetect = new GestureDetectorCompat(this, this);
GestureDetect.setOnDoubleTapListener(this);
TextView txtview = (TextView) findViewById(R.id.question1);
final TextView answer1 = (TextView) findViewById(R.id.answer1);
txtview.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
if (answer1.getVisibility() == View.VISIBLE)
answer1.setVisibility(View.GONE);
else
answer1.setVisibility(View.VISIBLE);
}
});
TextView txtview1 = (TextView) findViewById(R.id.question2);
final TextView answer2 = (TextView) findViewById(R.id.answer2);
txtview1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
if (answer2.getVisibility() == View.VISIBLE)
answer2.setVisibility(View.GONE);
else
answer2.setVisibility(View.VISIBLE);
}
});
TextView txtview2 = (TextView) findViewById(R.id.question3);
final TextView answer3 = (TextView) findViewById(R.id.answer3);
txtview2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (answer3.getVisibility() == View.VISIBLE)
answer3.setVisibility(View.GONE);
else
answer3.setVisibility(View.VISIBLE);
}
});
TextView txtview3 = (TextView) findViewById(R.id.question4);
final TextView answer4 = (TextView) findViewById(R.id.answer4);
txtview3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (answer4.getVisibility() == View.VISIBLE)
answer4.setVisibility(View.GONE);
else
answer4.setVisibility(View.VISIBLE);
}
});
TextView txtview4 = (TextView) findViewById(R.id.question5);
final TextView answer5 = (TextView) findViewById(R.id.answer5);
txtview4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (answer5.getVisibility() == View.VISIBLE)
answer5.setVisibility(View.GONE);
else
answer5.setVisibility(View.VISIBLE);
}
});
}
//for the overflow actionbar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_activity_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//for the actionbar menu items
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Play_ID:
mp1 = MediaPlayer.create(Help.this, R.raw.manual);
mp1.start();
break;
case R.id.Help_ID:
startActivity(new Intent(Help.this, Help.class));
break;
case R.id.About_ID: {
startActivity(new Intent(Help.this, LocationMain.class));
return true;
}
case R.id.Contact_Us:{
startActivity(new Intent(Help.this, ContactUs.class));
return true;
}
case android.R.id.home:{
startActivity(new Intent(Help.this, HomeScreen.class));
return true;
}
default:
return super.onOptionsItemSelected(item);
}
return false;
}
//calls event for the gestures
#Override
public boolean onTouchEvent(MotionEvent event) {
GestureDetect.onTouchEvent(event);
return super.onTouchEvent(event);
}
#Override
public boolean onDoubleTap(MotionEvent motionEvent) {
return false;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
return false;
}
#Override
public boolean onDoubleTapEvent(MotionEvent motionEvent) {
if(mp1!=null)
{
mp1.stop();
} return false;
}
#Override
public boolean onDown(MotionEvent motionEvent) {
return false;
}
#Override
public void onShowPress(MotionEvent motionEvent) {
}
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return false;
}
#Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
return false;
}
#Override
public void onLongPress(MotionEvent motionEvent) {
Toast.makeText(Help.this, "longpress!", Toast.LENGTH_LONG).show();
}
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
return false;
}
}
You are creating a GestureDetector but you are never "hooking it up" to your View. Try changing your onCreate like this:
super.onCreate(savedInstanceState);
View v = new RelativeLayout(this);
v.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
setContentView(v);
mDetector = new GestureDetectorCompat(this, this);
mDetector.setOnDoubleTapListener(this);
v.setOnTouchListener(new OnTouchListener(){
public boolean onTouch(View v, MotionEvent me){
return mDetector.onTouchEvent(me);
}
});
or you can try this
public boolean onTouchEvent(MotionEvent event) {
return gestureDetectorCompat.onTouchEvent(event)
}
I have a viewpager and several fragments.I extend a ViewPager and implement a my own class.Also i implemented onInterceptTouchEvent method.Now when i swipe it doesn't work.I think onInterceptTouchEvent intercept them. How to handle this?
package com.android.ho;
import com.sph.custom.ViewPagerWithTapGestreDetection;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class PDFActivity extends FragmentActivity implements ImageOnTapCallback,OnPageChangeListener{
static final int ITEMS = 20;
MyAdapter mAdapter;
//ViewPager mPager;
ViewPagerWithTapGestreDetection mPager;
//ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
try {
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPagerWithTapGestreDetection) findViewById(R.id.pager);
mPager.setId(5000);
mPager.setImageOnTapCallback(this);
mPager.setAdapter(mAdapter);
//mPager.setOffscreenPageLimit(1);
mPager.setOnPageChangeListener(this);
/*
Button button = (Button) findViewById(R.id.first);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
button = (Button) findViewById(R.id.last);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(ITEMS - 1);
}
});
*/
mPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show image
return MyFragment.newInstance("1.pdf");
case 1: // Fragment # 1 - This will show image
return MyFragment.newInstance("2.pdf");
case 2: // Fragment # 1 - This will show image
return MyFragment.newInstance("3.pdf");
case 3: // Fragment # 1 - This will show image
return MyFragment.newInstance("4.pdf");
case 4: // Fragment # 1 - This will show image
return MyFragment.newInstance("5.pdf");
default:// Fragment # 2-9 - Will show list
return MyFragment.newInstance("1.pdf");
}
}
}
#Override
public void tapDetected() {
// TODO Auto-generated method stub
Log.e("tapDetected", "tapDetected");
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
Log.e("onPageScrollStateChanged", "onPageScrollStateChanged");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
Log.e("onPageScrolled", "onPageScrolled");
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
Log.e("onPageSelected", "onPageSelected");
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e("onDestroy", "onDestroy onDestroy onDestroy");
}
}
This is my fragment class
package com.android.ho;
import java.io.File;
import java.io.InputStream;
import com.epapyrus.plugpdf.core.viewer.ReaderView;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MyFragment extends Fragment{
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static int count = 1;
static String file;
TextView txt;
ReaderView readerView;
public static final MyFragment newInstance(String message) {
MyFragment f = new MyFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
file = message;
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
try {
File fl = new File(Environment.getExternalStorageDirectory(), "/pdf/2.pdf");
readerView = (ReaderView) v.findViewById(R.id.pdfviews);
//readerView.setOnClickListener(this);
Log.e("readerView", fl.toString());
v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return true;
}
});
// readerView.openFile("/mnt/sdcard/pdf/1.pdf","");
if (count > 5)
count = 1;
readerView.openFile("/mnt/sdcard/pdf/" + count + ".pdf", "");
Log.e("Inside onCreateView count is ", "" + count);
count++;
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getActivity(), "Cilcked..",Toast.LENGTH_SHORT).show();
}
});
/*v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return false;
}
});*/
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
#Override
public void onDestroyView() {
super.onDestroyView();
// Log.d("PDFVIEW", "onDestroyView");
try {
if (readerView != null) {
readerView.clear();
// readerView.clearAllField(5);
// readerView.destroyDrawingCache();
// readerView.
// readerView=null;
// mPDFView.purgeMemory();
// mPDFView.destroy();//added to force release memory
// mPDFView = null;
}
Log.e("Fragment onDestroyView ", " onDestroyView readerView is "+readerView);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is my custom viewpager class
package com.android.ho
import java.util.Calendar;
import java.util.Currency;
import java.util.Date;
import com.sph.bh.ImageOnTapCallback;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
import android.widget.Toast;
public class ViewPagerWithTapGestreDetection extends ViewPager {
private ImageOnTapCallback imageOnTapCallback;
private GestureDetector tapGestureDetector;
private OnGestureListener mGestureListener;
public ViewPagerWithTapGestreDetection(Context context) {
super(context);
try {
imageOnTapCallback = null;// set if needed
mGestureListener = new GestureListener();
tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
} catch (Exception e) {
}
}
public ViewPagerWithTapGestreDetection(Context context, AttributeSet attrs) {
super(context, attrs);
try {
imageOnTapCallback = null;// set if needed
mGestureListener = new GestureListener();
tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
} catch (Exception e) {
}
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//Don't let any touches be passed down to the children automatically
Log.d("onInterceptTouchEvent ", "onInterceptTouchEvent");
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("onTouchEvent", "onTouchEvent");
if (imageOnTapCallback != null) {
tapGestureDetector.onTouchEvent(event);
}
return super.onTouchEvent(event);
}
public ImageOnTapCallback getImageOnTapCallback() {
return imageOnTapCallback;
}
public void setImageOnTapCallback(ImageOnTapCallback imageOnTapCallback) {
this.imageOnTapCallback = imageOnTapCallback;
}
public class GestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Log.d("onSingleTapConfirmed", "onSingleTapConfirmed");
if (null != imageOnTapCallback) {
imageOnTapCallback.tapDetected();
}
return super.onSingleTapConfirmed(e);
}
#Override
public boolean onDoubleTap(MotionEvent e) {
Log.d("onDoubleTap", "onDoubleTap");
return super.onDoubleTap(e);
}
#Override
public void onLongPress(MotionEvent e) {
Log.d("onLongPress", "onLongPress");
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
Log.d("onScroll", "onScroll");
return super.onScroll(e1, e2, distanceX, distanceY);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.e("onFling ", "onFling");
return super.onFling(e1, e2, velocityX, velocityY);
}
}
}
I think onInterceptTouchEvent intercept them.
Well, you are returning true from onInterceptTouchEvent(), which means, that as a ViewGroup you do not want any touch event to be passed to children, instead pass that touch event to onTouchEvent().
You should listen for event in onInterceptTouchEvent() return false until you see that this is such a gesture, that shouldn't be handled by children. And on that point only you should return true.
I have a viewpager with several fragments in the viewpager.I need to handle click event.I have already implement the onTouch event,but its not trigger for click event.When i swiping onTouch is triggering.I don't know why it's not trigger for click event.
This is my viewpager class
package com.android.ho;
import com.sph.custom.ViewPagerWithTapGestreDetection;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class PDFActivity extends FragmentActivity implements ImageOnTapCallback,OnPageChangeListener{
static final int ITEMS = 20;
MyAdapter mAdapter;
//ViewPager mPager;
ViewPagerWithTapGestreDetection mPager;
//ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
try {
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPagerWithTapGestreDetection) findViewById(R.id.pager);
mPager.setId(5000);
mPager.setImageOnTapCallback(this);
mPager.setAdapter(mAdapter);
//mPager.setOffscreenPageLimit(1);
mPager.setOnPageChangeListener(this);
/*
Button button = (Button) findViewById(R.id.first);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
button = (Button) findViewById(R.id.last);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(ITEMS - 1);
}
});
*/
mPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show image
return MyFragment.newInstance("1.pdf");
case 1: // Fragment # 1 - This will show image
return MyFragment.newInstance("2.pdf");
case 2: // Fragment # 1 - This will show image
return MyFragment.newInstance("3.pdf");
case 3: // Fragment # 1 - This will show image
return MyFragment.newInstance("4.pdf");
case 4: // Fragment # 1 - This will show image
return MyFragment.newInstance("5.pdf");
default:// Fragment # 2-9 - Will show list
return MyFragment.newInstance("1.pdf");
}
}
}
#Override
public void tapDetected() {
// TODO Auto-generated method stub
Log.e("tapDetected", "tapDetected");
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
Log.e("onPageScrollStateChanged", "onPageScrollStateChanged");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
Log.e("onPageScrolled", "onPageScrolled");
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
Log.e("onPageSelected", "onPageSelected");
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e("onDestroy", "onDestroy onDestroy onDestroy");
}
}
This is my fragment class
package com.android.ho;
import java.io.File;
import java.io.InputStream;
import com.epapyrus.plugpdf.core.viewer.ReaderView;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MyFragment extends Fragment{
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static int count = 1;
static String file;
TextView txt;
ReaderView readerView;
public static final MyFragment newInstance(String message) {
MyFragment f = new MyFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
file = message;
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
try {
File fl = new File(Environment.getExternalStorageDirectory(), "/pdf/2.pdf");
readerView = (ReaderView) v.findViewById(R.id.pdfviews);
//readerView.setOnClickListener(this);
Log.e("readerView", fl.toString());
v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return true;
}
});
// readerView.openFile("/mnt/sdcard/pdf/1.pdf","");
if (count > 5)
count = 1;
readerView.openFile("/mnt/sdcard/pdf/" + count + ".pdf", "");
Log.e("Inside onCreateView count is ", "" + count);
count++;
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getActivity(), "Cilcked..",Toast.LENGTH_SHORT).show();
}
});
/*v.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
Log.e("Inside onTouch onTouch onTouch onTouch onTouch onTouch ", "onTouch");
return false;
}
});*/
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
#Override
public void onDestroyView() {
super.onDestroyView();
// Log.d("PDFVIEW", "onDestroyView");
try {
if (readerView != null) {
readerView.clear();
// readerView.clearAllField(5);
// readerView.destroyDrawingCache();
// readerView.
// readerView=null;
// mPDFView.purgeMemory();
// mPDFView.destroy();//added to force release memory
// mPDFView = null;
}
Log.e("Fragment onDestroyView ", " onDestroyView readerView is "+readerView);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is my custom viewpager class
package com.android.ho
import java.util.Calendar;
import java.util.Currency;
import java.util.Date;
import com.sph.bh.ImageOnTapCallback;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
import android.widget.Toast;
public class ViewPagerWithTapGestreDetection extends ViewPager {
private ImageOnTapCallback imageOnTapCallback;
private GestureDetector tapGestureDetector;
private OnGestureListener mGestureListener;
public ViewPagerWithTapGestreDetection(Context context) {
super(context);
try {
imageOnTapCallback = null;// set if needed
mGestureListener = new GestureListener();
tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
} catch (Exception e) {
}
}
public ViewPagerWithTapGestreDetection(Context context, AttributeSet attrs) {
super(context, attrs);
try {
imageOnTapCallback = null;// set if needed
mGestureListener = new GestureListener();
tapGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
} catch (Exception e) {
}
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//Don't let any touches be passed down to the children automatically
Log.d("onInterceptTouchEvent ", "onInterceptTouchEvent");
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("onTouchEvent", "onTouchEvent");
if (imageOnTapCallback != null) {
tapGestureDetector.onTouchEvent(event);
}
return super.onTouchEvent(event);
}
public ImageOnTapCallback getImageOnTapCallback() {
return imageOnTapCallback;
}
public void setImageOnTapCallback(ImageOnTapCallback imageOnTapCallback) {
this.imageOnTapCallback = imageOnTapCallback;
}
public class GestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Log.d("onSingleTapConfirmed", "onSingleTapConfirmed");
if (null != imageOnTapCallback) {
imageOnTapCallback.tapDetected();
}
return super.onSingleTapConfirmed(e);
}
#Override
public boolean onDoubleTap(MotionEvent e) {
Log.d("onDoubleTap", "onDoubleTap");
return super.onDoubleTap(e);
}
#Override
public void onLongPress(MotionEvent e) {
Log.d("onLongPress", "onLongPress");
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
Log.d("onScroll", "onScroll");
return super.onScroll(e1, e2, distanceX, distanceY);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.e("onFling ", "onFling");
return super.onFling(e1, e2, velocityX, velocityY);
}
}
}
Now when i click it identified by the onInterceptTouchEvent in the ViewPagerWithTapGestreDetection class.So i need to view a Horizontal scrollbar when i click.Is it the correct way to call it inside onInterceptTouchEvent ?
I was trying to run some test on SurfaceViewer with SurfaceViewer having its own thread and everything worked just fine. Then I changed my code to change orientation of screen using setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
In the code below: I have an activity which uses Fragments. I have another class which extends SurfaceView class. Problem starts when I add setRequestedOrientation. After I add setRequestedOrientation. Value of running at in FastRender Class run method is always false. If I comment line with setRequestedOrientation , it runs fines.
package com.example.testpractise;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.AssetManager;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
public class SurfaceViewTest extends ActionBarActivity {
static int counter;
static {
Log.i("Intializing class Surface Test","counter");
System.out.println("Statrting here");
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
counter++;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
counter++;
Log.i("Counter vlase",String.valueOf(counter));
System.out.println("value of counter"+counter);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_surface_view_test);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.surface_view_test, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
FastRenderView renderView;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//View rootView = inflater.inflate(
// R.layout.fragment_surface_view_test, container, false);
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
BitmapCollection.initializeBitMapCollection(getActivity());
renderView = new FastRenderView(getActivity());
return renderView;
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
renderView.resume();
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
renderView.pause();
}
static class FastRenderView extends SurfaceView implements Runnable {
Thread renderThread = null;
SurfaceHolder holder;
static volatile boolean running = false;
int x=0;
int y=0;
public FastRenderView(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder = getHolder();
}
public void pause()
{
running = false;
while(true)
{
try{
renderThread.join();
}catch (InterruptedException i){
}
}
}
public void resume()
{
running = true;
renderThread = new Thread(this);
renderThread.setName("RendererThread");
renderThread.start();
running=true;
}
#Override
public void run() {
// TODO Auto-generated method stub
int sleepCounter=0;
while(!running)
{
try {
if(sleepCounter <5)
{
sleepCounter++;
Thread.sleep(5000);
}else{
break;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
while(running)
{
if(!holder.getSurface().isValid())
{
continue;
}
Canvas canvas=holder.lockCanvas();
canvas.drawRGB(255, 0, 0);
holder.unlockCanvasAndPost(canvas);
}
}
}
}
}
Sorry if my question doesn't match the format. This is my first time. Any pointers on what is wrong and why would be greatly appreciated.
Thanks
If you just want to lock the Activity to landscape, you can do it in Manifest by adding the android:screenOrientation="landscape" attribute to the activity element.
I've been working on a personal project in Android and ran into a strange situation regarding an Activity which uses a ListView. The basics of the problem are that I have a list of items, each which have 2 buttons, edit and delete. Right now I'm working on implementing the Delete button, which works functionally, but doesn't update the ListView correctly. Instead, it puts what was just deleted on top of the list. It of course refreshes whenever I renavigate to that activity.
Right now the Delete button is detected inside the a custom BaseAdapter, and when I call the notifyDataSetChanged, the situation described above happens instead of removing the now deleted item. How can I correctly update the list inside the adapter class?
I realize that there have been some questions about this, but I haven't been able to integrate them, and solutions I think may work don't really explain how they work; I'm using this project to understand Android app development more, so I would prefer answers with some level of explanation, although any help is of course appreciated!
Thanks!
Here's the relevent code. Note that this is an unfinished project, so there are some unused/incomplete things inside it. Please ignore these.
EditItemsActivity:
package com.example.mybudget;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
public class EditItemsActivity extends Activity implements OnGestureListener{
private DatabaseHandler db;
private List<DataPoint> dpList;
private EditItemsAdapter adapter;
private ListView lv;
private GestureDetector gestureDetector;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_items);
// Show the Up button in the action bar.
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
getActionBar().setDisplayHomeAsUpEnabled(true);
db = new DatabaseHandler(this);
dpList = db.allDataThisMonth();
lv = (ListView) findViewById(R.id.edititems);
adapter = new EditItemsAdapter(this, R.id.edititems, dpList);
lv.setAdapter(adapter);
gestureDetector = new GestureDetector(getBaseContext(), this);
// buttonDelete.setVisibility(View.GONE);
}
public void refreshList()
{
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_edit_items, menu);
return true;
}
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
public void onDelete()
{
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY)
{
// Log.d("Swipe", "" + velocityX + ", " + velocityY);
// if(velocityX > 200 && velocityY < 50 && velocityY > -50)
// {
// buttonEdit.setVisibility(View.GONE);
// buttonDelete.setVisibility(View.VISIBLE);
// }
// else if(velocityX < -200 && velocityY < 50 && velocityY > -50)
// {
// buttonDelete.setVisibility(View.GONE);
// buttonEdit.setVisibility(View.VISIBLE);
// }
return false;
}
#Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
}
And here's the adapter class:
package com.example.mybudget;
import java.text.NumberFormat;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
public class EditItemsAdapter extends BaseAdapter implements OnClickListener{
private List<DataPoint> dpList;
private Activity activity;
private DatabaseHandler db;
public EditItemsAdapter(Activity a)
{
activity = a;
}
public EditItemsAdapter(Activity a, int textViewResourceId, List<DataPoint> dpList)
{
super();
this.dpList = dpList;
activity = a;
db = new DatabaseHandler(activity);
}
public static class ViewHolder
{
public TextView item1;
public TextView item2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
//ViewHolder holder;
NumberFormat format = NumberFormat.getCurrencyInstance();
if (v == null)
{
// LayoutInflater vi =
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater vi = activity.getLayoutInflater();
v = vi.inflate(R.layout.edit_grid_items, null);
// holder = new ViewHolder();
// holder.item1 = (TextView) v.findViewById(R.id.edit_item_name);
// holder.item2 = (TextView) v.findViewById(R.id.edit_item_cost);
// v.setTag(holder);
TextView tv1 = (TextView)v.findViewById(R.id.edit_item_name);
TextView tv2 = (TextView)v.findViewById(R.id.edit_item_cost);
Button edit = (Button)v.findViewById(R.id.edit_item_button);
Button delete = (Button)v.findViewById(R.id.delete_item_button);
final DataPoint dp = dpList.get(position);
tv1.setText(dp.getName());
tv2.setText(Float.toString(dp.getCost()));
delete.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
db.deleteRowByKey(dp);
((EditItemsActivity) activity).refreshList();
}
});
}
// else
// holder = (ViewHolder)v.getTag();
// if(dp != null)
// {
// holder.item1.setText(dp.getName());
// holder.item2.setText(format.format(dp.getCost()));
// }
return v;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return dpList.size();
}
#Override
public DataPoint getItem(int position) {
// TODO Auto-generated method stub
return dpList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return dpList.size();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
EDIT:
The solution involved the inflation explanation that Adam provided, but required a complete repopulation of dpList, the
dpList = db.allDataThisMonth();
that Anup suggested.
In your getView method of your adapter, you're checking if (convertView == null) and if it's null you're inflating a new view. If it's not null, you're just returning the non-null view that was supplied.
The convertView supplied to the getView method is a cached view that has already been displayed. You're supposed to re-use this (if it's a valid view - you may have multiple different views in your list), rather than inflating a new one. You're forgetting to update the content of it for the corresponding position.
So, how to fix it? Simply close your if (v == null) after inflation:
if (v == null)
{
LayoutInflater vi = activity.getLayoutInflater();
v = vi.inflate(R.layout.edit_grid_items, null);
}
Edit: As Anup points out, you also need to update your dpList variable or it will keep returning the same values for the given position. You can do this in your click listener:
delete.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
db.deleteRowByKey(dp);
dpList.remove((Integer)v.getTag());
((EditItemsActivity) activity).refreshList();
}
});
// Required so we know which index to remove from our dpList.
delete.setTag(position);
From your code, I can see that your adapter is populated by dplist. When you delete a row using db.deleteRowByKey(dp);you are updating the database but you are not updating your dplist.
You need to repopulate your dplist to match the database and only then will notifyDataSetChanged() work as expected.
A simply way to do this would be to change your refreshList() function to:
public void refreshList()
{
//reload dpList so that it can sync up with the database
dpList = db.allDataThisMonth();
//now notify adapter that the data set has changed so that it can update itself.
adapter.notifyDataSetChanged();
}