Lag after setImageDrawable - java

I have a problem with my code. The point is that I have 16 images and when the load initially my Scrolling acitivity no lag issues, but after several setimageas becomes very slow. I hope you can help me. ps: the 16 images are loaded on a fragment the problem of lag occurs when I move from one fragment to 'another scroll through.

I suggest you to use Picaso library to load images as its very fast and efficient
its as simple as
Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
for more information I suggest you to go to Picaso documentation

You can use Android Universal Image Loader library to get rid off this problem. Also try to use List View or Grid View.

This is the code, then if the load images via xml src nothing lag, just use setImageDrawable lag comes out..
for(int h=0;h<16;h++){
final int finalH = h;
button[h].setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
for (int i = 0; i < 8; i++) {
if (tresy[i] == ((int) button[finalH].getTag())) {
return true;
}
}
if ((test)&&(tempo)) {
Log.d("id", String.valueOf(button[finalH].getTag()));
button[finalH].setImageDrawable(carte[((int) button[finalH].getTag())]);
//set image resource tag!
logTaG[0] = (int) button[finalH].getTag();
logBtn = finalH;
test = false;
} else if(tempo) {
test = true;
button[finalH].setImageDrawable(carte[((int) button[finalH].getTag())]);
//set image resource tag!
logTaG[1] = (int) button[finalH].getTag();
if ((logTaG[0] == logTaG[1] && (logBtn != finalH))) {
tresy[j] = logTaG[0];
Intent intent = new Intent(v.getContext(), Browser_descrizione.class);
intent.putExtra("Tag", tresy[j]);
startActivity(intent);
j++;
Log.d("bravo", "hai vinto");
if (j == 7) {
Log.d("Bravo", "hai completato il gioco");
//Far comparire warning con scritto ricomincia o esci
attempt++;
SM.sendData(attempt);
}
} else {
Log.d("Riprova", "sarai piĆ¹ fortunato");
final Handler handler = new Handler();
tempo = false;
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 5s = 5000ms
button[finalH].setImageResource(R.drawable.back_card);
button[logBtn].setImageResource(R.drawable.back_card);
tempo = true;
}
}, 500);
attempt++;
SM.sendData(attempt);
}
}
return true;
}
return false;
}
});
}

Related

How To Change ImageView drawable For A Single RecyclerView Row

I am not particularly sure how to ask this question, so I will just use images to explain
In my App, onClick of the download icon calls a download method for the video in the row. When it is completely downloaded, the Icon changes from black to green. A boolean flag is used to save this state in SharedPreference. This saved state is called again in my RecyclerView Adapter so the downloaded state can reflect when the app is relaunched.
THE CHALLENGE IS...
When the app relaunches, instead only the downloaded row icon to show green, the Icon turns green for every row even when they have not been downloaded. below is my code.
class DownloadReceiver extends ResultReceiver { //DownloadReceiver class
public DownloadReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == TichaDownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress"); //get the progress
//Set the progress to progressBarCir
progressBarCir.setProgress(progress);
icon_download.setVisibility(View.GONE);
progressBarCir.setVisibility(View.VISIBLE);
Log.i("STATUS", "DOWNLOADING>>>");
if (progress == 100) { // Downloade process is completed
isNotDownloaded = false; // Flagging that the video has been downloaded
progressBarCir.setVisibility(View.GONE);
// Setting the Download Icon to reflect the New color state
icon_download.setColorFilter(itemView.getContext().getResources().getColor(R.color.funnygreen));
icon_download.setVisibility(View.VISIBLE);
// Saving the boolean flag in SharedPreferece
SharedPreferences sharedPreferences = getSharedPreferences("com.example.instagramclone",MODE_PRIVATE);
sharedPreferences.edit().putBoolean("isDownloadedState",isNotDownloaded).commit();
// Logging of the save state to confirm state is saved.
boolean newState= sharedPreferences.getBoolean("isDownloadedState",true);
Log.i("STATE XCHANGE", "DOWNLOADED HENCE, "+String.valueOf(newState));
}
} else {
Log.i("STATUS", " NOT DOWNLOADING,BOSS");
}
}
}
Below is a snippet of Holder section of my Adapter Class
public LectureClassesHolder(#NonNull final View itemView) {
super(itemView);
// Now we ref each custom layout view item using the itemView
textViewTitle = itemView.findViewById(R.id.subject_topic);
textViewDescription = itemView.findViewById(R.id.subject_description);
textViewDuration = itemView.findViewById(R.id.subject_duration);
imageViewDownload = itemView.findViewById(R.id.download);
textViewUrl = itemView.findViewById(R.id.url_link);
SharedPreferences sharedPreferences = itemView.getContext().getSharedPreferences("com.example.instagramclone",Context.MODE_PRIVATE);
isNotDownloaded = sharedPreferences.getBoolean("isDownloadedState",true);
if (isNotDownloaded){
imageViewDownload.setColorFilter(itemView.getContext().getResources().getColor(R.color.black));
Log.i("DOWNLOAD STATE ","NOT Downloaded State is "+ isNotDownloaded);
}else {
imageViewDownload.setColorFilter(itemView.getContext().getResources().getColor(R.color.funnygreen));
Log.i("DOWNLOAD STATE ","NOT Downloaded State is "+ isNotDownloaded);
}
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && listener != null) {
listener.onItemClick(getSnapshots().getSnapshot(position), position, itemView);
}
}
});
// Incase e no work
imageViewDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && listener != null) {
listener.onViewItemClick(getSnapshots().getSnapshot(position), position, itemView);
}
}
});
}
I NEED a way to make the change effective for only the row concerned. Would appreciate any assistance on how to achieve this.
The problem is there is of course no association between the individual records and what is stored .The best solution would be to use a database with a table containing atleast a column for the download url and another for status,store the records with the desired status (for example use 0 for not downloaded status and 1 for downloaded status ) and update status column of the row with your url after download then you can query to check the status of the record .however a quick fix to your solution while still using shared prefrence would be to store the links in an array and check against that array see:
public static String all_records(Context act)
{
SharedPreferences prefs = act.getSharedPreferences("SHARED_PREFS_NAME", act.MODE_PRIVATE);
return prefs.getString("all_records", "[]");
}
public static void add_download(Activity act,String url)
{
JSONArray ja=new JSONArray();
try {
ja=new JSONArray(all_records(act));
JSONObject jo=new JSONObject();
jo.put("url",url);
ja.put(jo);
} catch (JSONException e) {
e.printStackTrace();
}
SharedPreferences.Editor saver =act.getSharedPreferences("SHARED_PREFS_NAME", act.MODE_PRIVATE).edit();
saver.putString("all_records",ja.toString());
saver.commit();
}
public static boolean is_downloaded(Activity act,String url)
{
JSONArray ja=new JSONArray();
try {
ja=new JSONArray(all_records(act));
for (int i=0;i<ja.length();i++)
{
try {
Log.e("Check ", "" + ja.getJSONObject(i).getString("url") + " Against " + url);
if (ja.getJSONObject(i).getString("url").equalsIgnoreCase(url)) {
return true;
}
}catch (Exception ex){}
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
in this case you would use it like this to when downloading
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == TichaDownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress"); //get the progress
//Set the progress to progressBarCir
progressBarCir.setProgress(progress);
icon_download.setVisibility(View.GONE);
progressBarCir.setVisibility(View.VISIBLE);
Log.i("STATUS", "DOWNLOADING>>>");
if (progress == 100) { // Downloade process is completed
isNotDownloaded = false; // Flagging that the video has been downloaded
progressBarCir.setVisibility(View.GONE);
// Setting the Download Icon to reflect the New color state
icon_download.setColorFilter(itemView.getContext().getResources().getColor(R.color.funnygreen));
icon_download.setVisibility(View.VISIBLE);
// Saving the boolean flag in SharedPreferece
add_download(/*your context*/,/*your url*/);
}
} else {
Log.i("STATUS", " NOT DOWNLOADING,BOSS");
}
}
on your recycle view adapter onbindview or wherever you want to get retrieve the status of whether downloaded call is_downloaded(/*YOUR CONTEXT*/,"YOUR URL");

libgdx stopping running music with class

I'm working on a little Android Game with libGDX.
The structure is as follows:
Main > Screen:Splashscreen > Screen:MainMenu > Screen: Settings or GameScreen
I have a Preference for the state of music(if running "music" is true).
If the music is true the music starts in the MainMenu.
Now the user should be abled to turn the music on and off in the Settings Screen.
To manage the music I made a class called MusicPlayer.
The Code:
MainMenu:
public class StartScreen implements Screen {
MusicPlayer musicPl;
Preferences scorepref;
boolean music;
(...)
#Override
public void show() {
(...)
scorepref = Gdx.app.getPreferences("Highscore");
musicPl = new MusicPlayer();
music = scorepref.getBoolean("music");
if(music){
musicPl.play();
}
}
#Override
public void dispose() {
musicPl.dispose();
}
}
Settings:
public class SettingScreen implements Screen {
Preferences scorepref;
//Setting Values
boolean tut = false;
boolean music = false;
boolean sounds = false;
int theme = 0;
//
MusicPlayer musicPl;
int touchX = 0;
int touchY = 0;
boolean touchD = false;
boolean touchU = false;
#Override
public void show() {
(handling Input and setting touchX,touchY,touchD and touchU)
(...)
musicPl = new MusicPlayer();
scorepref = Gdx.app.getPreferences("Highscore");
}
#Override
public void render(float delta) {
tut = scorepref.getBoolean("tut");
music = scorepref.getBoolean("music");
sounds = scorepref.getBoolean("sounds");
(...)
//if Touched
if(touchD == true && touchU == true){
touchD = false;
touchU = false;
//wo?
Vector3 posn = new Vector3(Gdx.input.getX(),Gdx.input.getY(), 0);
camera.unproject(posn);
if(){
(...)
} else if (posn.x >= -192 && posn.x <= 192 && posn.y <= 53 && posn.y >= -75) {
if(music){
music = false;
scorepref.putBoolean("music", music);
scorepref.flush();
musicPl.stop(); //Error line 206 is here
} else {
music = true;
scorepref.putBoolean("music", music);
scorepref.flush();
musicPl.play();
}
} (...)
} else if (posn.x >= -344 && posn.x <= -248 && posn.y <= 543 && posn.y >= 463) {
((Game) Gdx.app.getApplicationListener()).setScreen(new StartScreen());
}
//var speichern
scorepref.putBoolean("tut", tut);
scorepref.putBoolean("music", music);
scorepref.putBoolean("sounds", sounds);
scorepref.flush();
}
#Override
public void dispose() {
musicPl.dispose();
}
}
MusicPlayer:
public class MusicPlayer{
Music menuMusic;
boolean isrunning;
Preferences scorepref;
public void play (){
scorepref = Gdx.app.getPreferences("Highscore");
if(scorepref.getBoolean("running") == true){
} else {
menuMusic = Gdx.audio.newMusic(Gdx.files.internal("Theme.mp3"));
menuMusic.setLooping(true);
scorepref.putBoolean("running", true);
scorepref.flush();
menuMusic.play();
}
}
public void stop(){
scorepref = Gdx.app.getPreferences("Highscore");
scorepref.putBoolean("running", false);
scorepref.flush();
menuMusic.stop(); //Error line 33 is here
}
public void dispose(){
menuMusic.dispose();
}
}
My Problem:
When I am in the Settings Screen the tunring on and off is working fine.
When I turn the music on and go back to the MainScreen the music is still playing. So far so good.
But when I return to the SettingsScreen with running music and I want to turn it off the App crashes.
I think the crash is caused by the stop method, because the MusicPlayer doesn't know what to stop. But how can I tell him or how can i solve this problem with a different technique?
Thanks for helping.
P.S.
Here is the error I get, when I run the App on the desktop:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at de.hatgames.canone.MusicPlayer.stop(MusicPlayer.java:33)
at de.hatgames.canone.SettingScreen.render(SettingScreen.java:206)
at com.badlogic.gdx.Game.render(Game.java:46)
at de.hatgames.canone.CanoneMain.render(CanoneMain.java:26)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
CanoneMain.java:26 is just this:
super.render();
when you return to SettingScreen you create a new MusicPlayer instance each time.
musicPl = new MusicPlayer();
The Music member is only instanciated when play() is called:
menuMusic = Gdx.audio.newMusic(Gdx.files.internal("Theme.mp3"));
That is why menuMusic is null when you call stop() before calling play()
There are several solutions. You can make the MusicPlayer static and global accesable.
Or you can make sure MusicPlayer is only instanitated once like this:
if(musicPl == null) {
musicPl = new MusicPlayer();
}
But this will only work when you make sure that SettingsScreen is only instantiated once.
Good topics to read are probably singleton and factory pattern since this case will often occur when programming games.
Additionally using a Singleton for the music player as part of it being a global object will be helpful.

Avoid overlap between touch and click android in OnTouch(), in IOnTouchListener?

I am creating this app.
code of my onsingletapup.cs file
class SingleTapUp : Android.Views.GestureDetector.SimpleOnGestureListener
{
public override bool OnSingleTapUp(MotionEvent e) {
// Toast.MakeText(this,, ToastLength.Long).Show();
return true;
}
}
here is my mainactivity.cs
public class MainActivity : ActionBarActivity, View.IOnTouchListener
{
GestureDetector gestureDetector;
float _viewX;
float _viewY;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
PopulateListView(someList,anynumbertoshow)
}
private void QueueListView(Queue<FeedItem> feedItemsList, int count)
{
RelativeLayout rl = this.FindViewById<RelativeLayout>(Resource.Id.newsContainer);
if(rl.Visibility == ViewStates.Gone)
{
this.FindViewById<LinearLayout>(Resource.Id.newsList).Visibility = ViewStates.Gone;
rl.Visibility = ViewStates.Visible;
}
Paint layerPaint = new Paint();
layerPaint.AntiAlias = true;
layerPaint.FilterBitmap = true;
layerPaint.Dither = true;
// RelativeLayout parentLayout = (RelativeLayout)LayoutInflater.from(context).inflate(R.layout.myLayout, null);
rl.SetLayerType(LayerType.Hardware, layerPaint);
rl.SetClipChildren(false);
Random rnd = new Random();
//this.progressDialog.Dismiss();
for (int i = 0; i < count; i++)
{
FeedItem rss = theNewsQueue.Dequeue();
var viewObj = this.LayoutInflater.Inflate(Resource.Layout.NewTile, rl, false);
TextView tv = viewObj.FindViewById<TextView>(Resource.Id.textView2);
TextView link = viewObj.FindViewById<TextView>(Resource.Id.link);
link.Text = rss.Link;
tv.Text = rss.Title;
viewObj.Rotation = angle;
angle = rnd.Next(-3, 3);
viewObj.SetLayerType(LayerType.Hardware, layerPaint);
rl.AddView(viewObj);
gestureDetector = new GestureDetector(this, new SingleTapUp());
viewObj.SetOnTouchListener(this); //Here I am adding my listener to all my control
rl.SetLayerType(LayerType.Hardware, layerPaint);
theNewsQueue.Enqueue(rss);
rss = null;
}
}
public bool OnTouch(View v, MotionEvent e)
{
if (gestureDetector.OnTouchEvent(e))
{
//will detect a click and open in browser
return true;
}
else
{
int initialTouchX = 0, initialTouchY = 0;
int newx = 0;
var x = v.Left;
switch (e.Action)
{
case MotionEventActions.Down:
{
_viewX = e.GetX();
_viewY = e.GetY();
initialTouchX = (int)e.RawX;
initialTouchY = (int)e.RawY;
break;
}
case MotionEventActions.Up:
{
int lastX = (int)e.GetX();
int lastY = (int)e.GetY();
if ((x - newx) > 40)
{
//right Swipe
sendViewToBack(v);
}
else if ((newx - x > 40))
{
//left Swipe
sendViewToBack(v);
}
break;
}
case MotionEventActions.Move:
{
// click = false;
var left = (int)(e.RawX - _viewX);
newx = left;
var right = (int)(left + v.Width);
var top = (int)(e.RawY - _viewY);
var bottom = (int)(top + v.Height);
v.Layout(left, top, right, bottom);
break;
}
}
}
// _gestureDetector.OnTouchEvent(e);
return true;
}
public void sendViewToBack(View child)
{
var parent = (ViewGroup)child.Parent;
if (null != parent)
{
parent.RemoveView(child);
if(viewType==0)
parent.AddView(QueueListView (theNewsQueue), 0);
else
parent.AddView(QueueListView (theNewsQueue), parent.ChildCount-1);
}
}
}
Now my question is on some devices my current code is giving some abnormal behavior. Like even if I perform OnSingleTapUp() which is supposed to perform click operation but it is performing a move operation. My question is what is wrong with my code so that it is not working correctly. Any help will be greatly appreciated. Thank you.
The onTouch and onClick doesn't work together. In all the cases the onTouch is going to get the priority, in fact onClick in also sort of fine implementation of onTouch. If you want to have onClick sort of functionality, let go the original onClick and try to handle that in onTouch. You can take help of the GestureDetector.SimpleOnGestureListener in Xamarin. For an example to override the double tap you can do it like this
class MyDoubleTapListener : GestureDetector.SimpleOnGestureListener
{
public override bool OnDoubleTap(MotionEvent e)
{
//Your code here
return false;
}
}
and then in your activity
public class Test : Activity, View.IOnTouchListener
{
private GestureDetector _gestureDetector = null;
protected override void OnCreate (Bundle bundle)
{
_gestureDetector = new GestureDetector(new MyDoubleTapListener (this));
_editText.SetOnTouchListener(this);
}
public bool OnTouch(View v, MotionEvent e)
{
return _gestureDetector.OnTouchEvent(e);
}
}
GestureDetector also provides you other methods that you can overide to suit your need. Follow this, https://developer.xamarin.com/api/type/Android.Views.GestureDetector/
I couldn't get exactly what your are trying to do inside onTouch interface. Anyway there's some points you must know:
1) When you handle a touch event, onTouch method returns a boolean that indicates if event was consumed (true) or not (false). If you consume touch event related to click, click listener won't be triggered. So, make sure you are only consuming what is desired.
2) When you set listeners as onClick or onTouch to some view, it becomes clickable and touchable, respectively, if it wasn't. If you are setting this attributes to false in some part of your code make sure it's enabled again when you want to handle such events.

Android. Remote the android tv box from a remote control

You have propaply seen those pretty cheap android tv boxes available on the market. They are usually followed with a remote control that has some functionalities like clicking, swipe or slide to left and right up and down.
Recently i made an app and tried to navigate it using the remote control. I have some gesture methods in the project. I tried to swipe to left and right but the app didnt do anything while when i try it on my phone that has a screen gets the gesture and do what it should. Like opening the navigation drawer etc.
Now to my question: does one need to use speciel methods? Is there some rules that one should be ware of?
Edit
This is what Ive done so far. I made a class that defines the action: It's from google.developer
public class Dpad {
public final static int UP = 0;
public final static int LEFT = 1;
public final static int RIGHT = 2;
public final static int DOWN = 3;
public final static int CENTER = 4;
int directionPressed = -1; // initialized to -1
public int getDirectionPressed(InputEvent event) {
if (!isDpadDevice(event)) {
return -1;
}
// If the input event is a MotionEvent, check its hat axis values.
if (event instanceof MotionEvent) {
// Use the hat axis value to find the D-pad direction
MotionEvent motionEvent = (MotionEvent) event;
float xaxis = motionEvent.getAxisValue(MotionEvent.AXIS_HAT_X);
float yaxis = motionEvent.getAxisValue(MotionEvent.AXIS_HAT_Y);
// Check if the AXIS_HAT_X value is -1 or 1, and set the D-pad
// LEFT and RIGHT direction accordingly.
if (Float.compare(xaxis, -1.0f) == 0) {
directionPressed = Dpad.LEFT;
} else if (Float.compare(xaxis, 1.0f) == 0) {
directionPressed = Dpad.RIGHT;
}
// Check if the AXIS_HAT_Y value is -1 or 1, and set the D-pad
// UP and DOWN direction accordingly.
else if (Float.compare(yaxis, -1.0f) == 0) {
directionPressed = Dpad.UP;
} else if (Float.compare(yaxis, 1.0f) == 0) {
directionPressed = Dpad.DOWN;
}
}
// If the input event is a KeyEvent, check its key code.
else if (event instanceof KeyEvent) {
// Use the key code to find the D-pad direction.
KeyEvent keyEvent = (KeyEvent) event;
if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) {
directionPressed = Dpad.LEFT;
} else if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) {
directionPressed = Dpad.RIGHT;
} else if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP) {
directionPressed = Dpad.UP;
} else if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) {
directionPressed = Dpad.DOWN;
} else if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER) {
directionPressed = Dpad.CENTER;
}
}
return directionPressed;
}
public static boolean isDpadDevice(InputEvent event) {
// Check that input comes from a device with directional pads.
if ((event.getSource() & InputDevice.SOURCE_DPAD)
!= InputDevice.SOURCE_DPAD) {
return true;
} else {
return false;
}
}
}
In my MainActivity I have a navigationdrawer. which I want to open and close when remotecontrol D-pad wants it
mDrawerLayout.setOnGenericMotionListener(new View.OnGenericMotionListener() {
#Override
public boolean onGenericMotion(View view, MotionEvent motionEvent) {
if (Dpad.isDpadDevice(motionEvent)) {
int press = mDpad.getDirectionPressed(motionEvent);
switch (press) {
case Dpad.RIGHT:
// Do something for UP direction press Open the drawer
mDrawerLayout.openDrawer(Gravity.START);
return true;
case Dpad.LEFT:
mDrawerLayout.closeDrawer(Gravity.START);
return true;
}
}
return false;
}
});
In one of the fragments I have a media player and using D-pad up and D-pad down I change the video.
v.setOnGenericMotionListener(new View.OnGenericMotionListener() {
#Override
public boolean onGenericMotion(View view, MotionEvent motionEvent) {
if (Dpad.isDpadDevice(motionEvent)) {
int press = mDpad.getDirectionPressed(motionEvent);
switch (press) {
case Dpad.UP:
// Do something for UP direction press
UP(); // Change the video to next
return true;
case Dpad.DOWN:
DOWN(); // Change the video the earlier on
return true;
}
}
return false;
}
});
EDIT
It' now become a problem since it doesn't response to any motion. I tried on a emulator with physical keyboard and not a single action happens. I would appritiate if someone gives me a hint.
i mean this kind of remote control in the picture below
Thanks in advance
I think the code on Android Developer is wrong:
public static boolean isDpadDevice(InputEvent event) {
// Check that input comes from a device with directional pads.
if ((event.getSource() & InputDevice.SOURCE_DPAD)
!= InputDevice.SOURCE_DPAD) {
return true;
} else {
return false;
}
}
The condition should be "==" instead of "!=", so this is correct:
public static boolean isDpadDevice(InputEvent event) {
// Check that input comes from a device with directional pads.
if ((event.getSource() & InputDevice.SOURCE_DPAD)
== InputDevice.SOURCE_DPAD) {
return true;
} else {
return false;
}
}

How to handle drop event in Drag and drop of an imageview?

I need drag and drop in my new project. I referred this blogpost. But I'm facing a problem while performing Drop. I cannot get the image which I hold and can't drop into view. DragListner which I used is given below. I don't know how to handle the dropevent.
class MyDragListener implements OnDragListener {
#Override
public boolean onDrag(View view, DragEvent dragEvent) {
int dragAction = dragEvent.getAction();
View dragView = (View) dragEvent.getLocalState();
if (dragAction == DragEvent.ACTION_DRAG_EXITED) {
System.out.println("exit------------");
containsDragable = false;
} else if (dragAction == DragEvent.ACTION_DRAG_ENTERED) {
System.out.println("enter------------");
containsDragable = true;
} else if (dragAction == DragEvent.ACTION_DRAG_ENDED) {
System.out.println("end------------");
dragView.setVisibility(View.VISIBLE);
} else if (dragAction == DragEvent.ACTION_DROP && containsDragable) {
dragView.setVisibility(View.VISIBLE);
}
return true;
}
maybe at first you can print out the
DragEvent.ACTION_DROP
code, and compare it to the value of the dragAction .
if the value is the same then the problem are at containsDragable function.
hope this helps

Categories

Resources