a have some problem and didn't find a solution. The problem is, i have a image view that's lay on layout and this layout lay on window manager, this image view is clickable. This image view have to move to right and to the left and be clickable. Here is my code
`public class FloatingAnimationService extends Service {
private WindowManager windowManager;
private ImageView floatingUnit;
private boolean isClicked;
public void onCreate() {
super.onCreate();
isClicked = false;
floatingUnit = new ImageView(this);
//a unit as imageView
Picasso.with(this).load(new File(Environment.getExternalStorageDirectory().getPath() +"/" + "cat.png")).into(floatingUnit);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(AppMethods.getPxFromDp(120 ,this), AppMethods.getPxFromDp(120 , this));
floatingUnit.setLayoutParams(layoutParams);
final LinearLayout floatingUnitLayout = new LinearLayout(this);
floatingUnitLayout.addView(floatingUnit);
windowManager = (WindowManager) this.getSystemService(WINDOW_SERVICE);
//here is all the science of params
final LayoutParams myParams = new WindowManager.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT,
LayoutParams.TYPE_PHONE,
LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
myParams.gravity = Gravity.TOP | Gravity.LEFT;
myParams.x=0;
myParams.y=100;
windowManager.addView(floatingUnitLayout, myParams);
// add a floatingUnit icon in window
Animation animation = AnimationUtils.loadAnimation(this ,R.anim.floating_unit_animation);
floatingUnit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startQuestion();
stopSelf();
windowManager.removeViewImmediate(floatingUnitLayout);
isClicked = true;
}
});
floatingUnit.startAnimation(animation);
startAnimationTimer(floatingUnitLayout);
AnimationSet animationSet = new AnimationSet(true);
myParams.x = 100;
myParams.y = 100;
windowManager.updateViewLayout(floatingUnitLayout, myParams);
Animation animationToRight = AnimationUtils.loadAnimation(this ,R.anim.left_to_right_animation);
Animation animationToLeft = AnimationUtils.loadAnimation(this , R.anim.right_to_left_animation);
animationSet.addAnimation(animationToRight);
floatingUnit.startAnimation(animation);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private void startQuestion (){
Intent intentQuestionActivity = new Intent(this, QuestionActivity.class);
intentQuestionActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentQuestionActivity);
}
private void startAnimationTimer(final View floatingUnitLayout){
long animationLifeTime = 10000;
new CountDownTimer(animationLifeTime, 1000) {
public void onTick(long millisUntilFinished) {
Log.i("animation remaining: " , Long.toString(millisUntilFinished / 1000));
}
public void onFinish() {
Log.i("animation: " , "DONE");
if(!isClicked) {
windowManager.removeViewImmediate(floatingUnitLayout);
stopSelf();
}
}
}.start();
}
`
Please help. Thanks !
Thanks all . Found the solution by myself. The trick is: to move a image that lay on window manager, you have to update the Layout Params.
here is the code below
private void startAnimationTimer(final View floatingUnitLayout) {
long animationLifeTime = AppData.first(AppData.class).getCountSecondsPicShow();
countDownTimer = new CountDownTimer(animationLifeTime, 100) {
public void onTick(long millisUntilFinished) {
Log.i("animation remaining: ", Long.toString(millisUntilFinished / 1000));
myParams.x = myParams.x + 2;
myParams.y = myParams.y + 2;
windowManager.updateViewLayout(floatingUnitLayout, myParams);
}
public void onFinish() {
Log.i("animation: ", "DONE");
if (!isClicked) {
windowManager.removeViewImmediate(floatingUnitLayout);
stopSelf();
}
}
}.start();
}
Related
I have an Android app with a Service to Overlay a button on Android (like Facebook chat bubble).
I want to show a layout (overlay.xml) when the user click on the icon but I can't show the layout with the good dimension.
This is my result :
This is my OverlayShowingService.class :
public class OverlayShowingService extends Service {
private WindowManager windowManager;
private ImageView chatHead;
private Boolean _enable = true;
#Override
public IBinder onBind(Intent intent) {
_enable=false;
return null;
}
#Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
chatHead = new ImageView(this);
chatHead.setImageResource(R.mipmap.ic_launcher);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
windowManager.addView(chatHead, params);
chatHead.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.overlay, null);
final PopupWindow popupWindow = new PopupWindow(popupView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
popupWindow.update();
Button btnDismiss = (Button)popupView.findViewById(R.id.dismiss);
Button endService= (Button) popupView.findViewById(R.id.endService);
endService.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stopSelf();
Toast.makeText(getApplicationContext(), "Service Terminated", Toast.LENGTH_LONG).show();
}
});
btnDismiss.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), "Popup Terminated", Toast.LENGTH_LONG).show();
popupWindow.dismiss();
_enable=true;
}
});
if(_enable){
popupWindow.showAsDropDown(chatHead, 50, -30);
_enable=false;
}
else if(!_enable) {
Log.d("FALSE", "FALSE");
}
}
});
try {
chatHead.setOnTouchListener(new View.OnTouchListener() {
private WindowManager.LayoutParams paramsF = params;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
#Override public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = paramsF.x;
initialY = paramsF.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
paramsF.x = initialX + (int) (event.getRawX() - initialTouchX);
paramsF.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(chatHead, paramsF);
break;
}
return false;
}
});
} catch (Exception ignored) {}
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatHead != null) windowManager.removeView(chatHead);
}
}
This is the layout overlay.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="vertical"
android:layout_margin="5dp"
android:background="#545454">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="It's a PopupWindow"
android:textSize="40sp"
android:textColor="#ffffff" />
<Button
android:id="#+id/dismiss"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dismiss Popup"
android:textColor="#ffffff" />
<Button
android:id="#+id/endService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Finish Service"
android:textColor="#ffffff" />
</LinearLayout>
Edit: This is an alternate approach that mimics a popup window. I have kept the first answer with a altert dialog approach after the following explanation and code. Either way will work, but this new way may be preferable since it looks more like a popup window.
This approach simply adds the overlay.xml layout into a view that is place on the screen just like the chatHead view is.
OverlayShowingService.java
public class OverlayShowingService extends Service {
private WindowManager windowManager;
private ImageView chatHead;
private Boolean _enable = true;
#Override
public IBinder onBind(Intent intent) {
_enable = false;
return null;
}
#Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
chatHead = new ImageView(this);
chatHead.setImageResource(R.mipmap.ic_launcher);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
windowManager.addView(chatHead, params);
chatHead.post(new Runnable() {
#Override
public void run() {
params.x = (int) chatHead.getBottom() + 50;
params.y = (int) chatHead.getRight() - 30;
}
});
chatHead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
final View popupView = layoutInflater.inflate(R.layout.overlay, null);
final PopupWindow popupWindow = new PopupWindow(popupView,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.update();
Button btnDismiss = (Button) popupView.findViewById(R.id.dismiss);
Button endService = (Button) popupView.findViewById(R.id.endService);
endService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
windowManager.removeViewImmediate(popupView);
stopSelf();
Toast.makeText(getApplicationContext(), "Service Terminated", Toast.LENGTH_LONG).show();
}
});
btnDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), "Popup Terminated", Toast.LENGTH_LONG).show();
// popupWindow.dismiss();
windowManager.removeViewImmediate(popupView);
_enable = true;
}
});
if (_enable) {
windowManager.addView(popupView, params);
// popupWindow.showAsDropDown(chatHead, 50, -30);
_enable = false;
} else if (!_enable) {
Log.d("FALSE", "FALSE");
}
}
});
try {
chatHead.setOnTouchListener(new View.OnTouchListener() {
private WindowManager.LayoutParams paramsF = params;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = paramsF.x;
initialY = paramsF.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
paramsF.x = initialX + (int) (event.getRawX() - initialTouchX);
paramsF.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(chatHead, paramsF);
break;
}
return false;
}
});
} catch (Exception ignored) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatHead != null) windowManager.removeView(chatHead);
}
}
The first approach using an alert dialog.
Your code works as-is for API 21 and below. Something changed with API 22 that is prohibiting what you want to do.
I think the primary issue is with the popup and the service environment. I have modified your code to use an AlertDialog with the type TYPE_SYSTEM_ALERT. Although the styling is not what you want, it does work otherwise. You may be able to get it to style differently if you play with it a little.
Another alternative would be to start an activity from your service. An activity-based approach will present you with a more pliable (and forgiving) environment to do what you want with the UI. (This is not as straight-forward as one may think.)
Below is the code that works as a system-level alert. Here is a screen shot.
OverlayShowingService
chatHead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
final AlertDialog alertDialog = new AlertDialog.Builder(arg0.getContext(),
R.style.Theme_AppCompat_Dialog_Alert).create();
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
final View popupView = layoutInflater.inflate(R.layout.overlay, null);
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.setView(popupView);
Button btnDismiss = (Button) popupView.findViewById(R.id.dismiss);
Button endService = (Button) popupView.findViewById(R.id.endService);
endService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
stopSelf();
Toast.makeText(getApplicationContext(), "Service Terminated", Toast.LENGTH_LONG).show();
}
});
btnDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), "Popup Terminated", Toast.LENGTH_LONG).show();
alertDialog.dismiss();
}
});
alertDialog.show();
}
});
As I stated in my first answer, you are having this issue with API 22 and later. Your code works OK for API 21 and earlier.
You are running afoul of changes made to PopupWindow in API level 22. See this documentation.
Fix issue #17789629: PopupWindow overlaps with navigation bar.
The Lollipop release introduced a feature that allowed
apps to extend under the navigation bar. This also means
any popup window that is anchored to the bottom of its
parent window will overlap with the navigation bar if the
parent window is extending underneath the navigation bar.
This change introduces a new window flag
(FLAG_LAYOUT_ATTACHED_IN_DECOR) that allows the app to
specify if the popup window should be attached to the decor
frame of the parent window thereby avoiding an overlap
with the screen decorations.
By default the flag is set on SDK version LOLLIPOP_MR1 or
greater and cleared on lesser SDK versions.
You can turn off this flag with the setAttachedInDecor method of PopupWindow.
Add the following code to OverlayShowingService.java after popupWindow.update() in the OnClickListener and you should be good to go.
// Turn off this functionality introduced in API 22.
// See documentation for FLAG_LAYOUT_ATTACHED_IN_DECOR in
// WindowManager.LayoutParams
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
popupWindow.setAttachedInDecor(false);
}
I have opened a window(displayed on top of other activities) on clicking floating view(similar to FB chat head), how to close window when device back button is pressed. Below is my service code
public class ServiceFloating extends Service {
public static int ID_NOTIFICATION = 2018;
private WindowManager windowManager;
private ImageView chatHead;
private PopupWindow pwindo;
boolean mHasDoubleClicked = false;
long lastPressTime;
private Boolean _enable = true;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
chatHead = new ImageView(this);
chatHead.setImageResource(R.drawable.floating2);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
windowManager.addView(chatHead, params);
try {
chatHead.setOnTouchListener(new View.OnTouchListener() {
private WindowManager.LayoutParams paramsF = params;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
#Override public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Get current time in nano seconds.
long pressTime = System.currentTimeMillis();
// If double click...
if (pressTime - lastPressTime <= 300) {
createNotification();
ServiceFloating.this.stopSelf();
mHasDoubleClicked = true;
}
else { // If not double click....
mHasDoubleClicked = false;
}
lastPressTime = pressTime;
initialX = paramsF.x;
initialY = paramsF.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
paramsF.x = initialX + (int) (event.getRawX() - initialTouchX);
paramsF.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(chatHead, paramsF);
break;
}
return false;
}
});
} catch (Exception e) {
// TODO: handle exception
}
chatHead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
showOptions(chatHead);
_enable = false;
// Intent intent = new Intent(getApplicationContext(), MainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
// getApplicationContext().startActivity(intent);
}
});
}
public void showOptions(View anchor){
windowManager.removeView(anchor);
chatHead = null;
View myView = View.inflate(getApplicationContext(),R.layout.alert_layout,null);
ImageView img1,img2,img3;
img1 = (ImageView) myView.findViewById(R.id.id_img1);
img2 = (ImageView) myView.findViewById(R.id.id_img2);
img3 = (ImageView) myView.findViewById(R.id.id_img3);
img1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"img1 Clicked",Toast.LENGTH_LONG).show();
}
});
img2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
img3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER;
//params.x = 0;
//params.y = 100;
windowManager.addView(myView, params);
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatHead != null) windowManager.removeView(chatHead);
}
#Override
public void onTaskRemoved(Intent rootIntent) {
// TODO Auto-generated method stub
Intent restartService = new Intent(getApplicationContext(),
this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(
getApplicationContext(), 1, restartService,
PendingIntent.FLAG_ONE_SHOT);
//Restart the service once it has been killed android
AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 100, restartServicePI);
}
}
I couldn't add onBackPressed or a onKeyEvent methods inside the service. Please suggest a workaround. TIA
You should handle your view only from activity and use communication components such service binding or broadcasts. You shouldn't create views from service, its not appropriate.
I have popupWindow with some image views, which are created and added progammatically to popup window. Their position is set to bottom line with setY(). But when I use setEndValue to animate with spring, image goes from 0 to setEndValue, not from it's initial position.
How that can be fixed?
public SharePostPopupWindow(View parentView) {
super(MATCH_PARENT, MATCH_PARENT);
this.context = parentView.getContext();
this.parentView = parentView;
AndroidBlaBlaApplication.component(context).inject(this);
setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
FrameLayout container = new FrameLayout(context);
socialViews = new ArrayList<>();
socials = new ArrayList<>();
shadow = new View(context);
shadow.setId(R.id.share_view_shadow);
shadow.setBackgroundColor(Color.BLACK);
shadow.setClickable(true);
shadow.setAlpha(0.5f);
shadow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bus.post(new ShadowClickedEvent());
spring.setEndValue(initialPosition / 2 - Utils.convertDpToPixel(imageSize, context));
dismiss();
}
});
}
public void show() {
Utils.hideKeyboard(context, getContentView());
createButtons();
SpringSystem springSystem = SpringSystem.create();
spring = springSystem.createSpring();
SpringConfig slowConfig = new SpringConfig(TENSION, DAMPER);
spring.setSpringConfig(slowConfig);
spring.addListener(new SimpleSpringListener() {
#Override
public void onSpringUpdate(Spring spring) {
float value = (float) spring.getCurrentValue();
for (int i = 0; i < socialViews.size(); i++) {
if (i % 2 != 0) {
socialViews.get(i).setY(value);
}
}
}
});
showAtLocation(parentView, Gravity.CENTER_VERTICAL, 0, 0);
getContentView().setAlpha(1f);
}
If you want to force spring animation from certain position, you need to use
spring.setCurrentValue method first.
I am making horizontal scrollview gallery, and I want to autoscroll it. Now it's scrolling from left to right but when I reach end of list I just simply jump to first one, but it looks really bad, so I want to go scroll around from beginning avoiding just skipping to first one, or if it is not possible just start scrolling to the other side when I reach last view on right (maybe better option). Could someone help me how to do this?
private LinearLayout horizontalOuterLayout;
private HorizontalScrollView horizontalScrollview;
private int scrollMax;
private int scrollPos = 0;
private TimerTask clickSchedule;
private TimerTask scrollerSchedule;
private TimerTask faceAnimationSchedule;
private Timer scrollTimer = null;
private Timer faceTimer = null;
private String[] imageNameArray ={ "sponsors_czarnykot", "sponsors_estradarzeszow","sponsors_klubp","sponsors_kula","sponsors_czarnykot", "sponsors_estradarzeszow","sponsors_klubp","sponsors_kula" };
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.horizontal_layout);
horizontalScrollview = (HorizontalScrollView) findViewById(R.id.horiztonal_scrollview_id);
horizontalOuterLayout = (LinearLayout) findViewById(R.id.horiztonal_outer_layout_id);
horizontalScrollview.setHorizontalScrollBarEnabled(false);
addImagesToView();
ViewTreeObserver vto = horizontalOuterLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
#Override
public void onGlobalLayout()
{
horizontalOuterLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
getScrollMaxAmount();
startAutoScrolling();
}
});
}
public void getScrollMaxAmount()
{
int actualWidth = (horizontalOuterLayout.getMeasuredWidth() - 512);
scrollMax = actualWidth;
}
public void startAutoScrolling()
{
if (scrollTimer == null)
{
scrollTimer = new Timer();
final Runnable Timer_Tick = new Runnable()
{
public void run()
{
moveScrollViewRight();
}
};
if (scrollerSchedule != null)
{
scrollerSchedule.cancel();
scrollerSchedule = null;
}
scrollerSchedule = new TimerTask()
{
#Override
public void run()
{
runOnUiThread(Timer_Tick);
}
};
scrollTimer.schedule(scrollerSchedule, 30, 30);
}
}
public void moveScrollViewRight()
{
scrollPos = (int) (horizontalScrollview.getScrollX() + 1.0);
if (scrollPos >= scrollMax)
{
scrollPos = 0;
}
horizontalScrollview.scrollTo(scrollPos, 0);
}
/** Adds the images to view. */
public void addImagesToView()
{
for (int i = 0; i < imageNameArray.length; i++)
{
final ImageView imageView = new ImageView(this);
int imageResourceId = getResources().getIdentifier(imageNameArray[i], "drawable", getPackageName());
Drawable image = this.getResources().getDrawable(imageResourceId);
imageView.setBackgroundDrawable(image);
imageView.setTag(i);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(180, 123);
params.setMargins(0, 25, 0, 25);
imageView.setLayoutParams(params);
horizontalOuterLayout.addView(imageView);
}
}
public void stopAutoScrolling()
{
if (scrollTimer != null)
{
scrollTimer.cancel();
scrollTimer = null;
}
}
public void onBackPressed()
{
super.onBackPressed();
finish();
}
public void onPause()
{
super.onPause();
finish();
}
public void onDestroy()
{
clearTimerTaks(clickSchedule);
clearTimerTaks(scrollerSchedule);
clearTimerTaks(faceAnimationSchedule);
clearTimers(scrollTimer);
clearTimers(faceTimer);
clickSchedule = null;
scrollerSchedule = null;
faceAnimationSchedule = null;
scrollTimer = null;
faceTimer = null;
super.onDestroy();
}
private void clearTimers(Timer timer)
{
if (timer != null)
{
timer.cancel();
timer = null;
}
}
private void clearTimerTaks(TimerTask timerTask)
{
if (timerTask != null)
{
timerTask.cancel();
timerTask = null;
}
}
scrolling back the other way would be easiest.
add in a instance variable that is set to 1.0 (called say scrollDist)
then change this line
scrollPos = (int) (horizontalScrollview.getScrollX() + 1.0);
to
scrollPos = (int) (horizontalScrollview.getScrollX() + scrollDist);
and this line
scrollPos = 0;
to
scrollDist *= -1.0;
this way it will reverse each time it hits the end of the scrollview.
For endless scrolling use the following snnipet
public void getScrollMaxAmount() {
int actualWidth = (horizontalOuterLayout.getMeasuredWidth() - getWindowManager().getDefaultDisplay().getWidth());
scrollMax = actualWidth;
}
public void moveScrollView() {
// ********************* Scrollable Speed ***********************
scrollPos = (int) (horizontalScrollview.getScrollX() + 1.0);
if (scrollPos >= scrollMax) {
Log.v("childCount", ""+scrollMax);
addImagesToView();
getScrollMaxAmount();
}
horizontalScrollview.scrollTo(scrollPos, 0);
}
I'm using horizontalscrollView to move set of images as a slideshow. I've 5 images in drawable, I'm able to move images from right to left but in some phones it just scrolling to 3rd image and restarting the scroll and in some phones it just stops scrolling till reaching to the end of images in right. Please help !! This is the code I used :
public void getScrollMaxAmount(){
int actualWidth = (horizontalOuterLayout.getMeasuredWidth()-200);
scrollMax = actualWidth;
}
public void startAutoScrolling(){
if (scrollTimer == null) {
scrollTimer=new Timer();
final Runnable Timer_Tick=new Runnable() {
public void run() {
moveScrollView();
}
};
if(scrollerSchedule != null){
scrollerSchedule.cancel();
scrollerSchedule = null;
}
scrollerSchedule = new TimerTask(){
#Override
public void run(){
runOnUiThread(Timer_Tick);
}
};
scrollTimer.schedule(scrollerSchedule, 50, 50);
}
}
public void moveScrollView(){
scrollPos= (int) (hsv2.getScrollX() + 1.0);
if(scrollPos >= scrollMax){
scrollPos=0;
}
hsv2.scrollTo(scrollPos, 0);
}
public void addImagesToView(){
for (int i=0;i<imageNameArray.length;i++){
Log.d("imagname",String.valueOf(imageNameArray.length));
final ImageView imageButton = new ImageView(this);
int imageResourceId = getResources().getIdentifier(imageNameArray[i], "drawable",getPackageName());
Drawable image = this.getResources().getDrawable(imageResourceId);
imageButton.setBackgroundDrawable(image);
imageButton.setTag(i);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(90,LayoutParams.WRAP_CONTENT);
//params.setMargins(0, 25, 0, 25);
imageButton.setLayoutParams(params);
horizontalOuterLayout.addView(imageButton);
}
First calculate width of your scrollview like this here linearlayout is layout inside your scrollview
linearLayout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
LayoutParams layParamsGet = linearLayout.getLayoutParams();
width = layParamsGet.width;
}
});
Then in timertassk just scroll the scrollview upto end
private void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if (x <= width - KeyConstants.SCREEN_WIDTH) {
x = x + 1;
} else {
x = 0;
}
mhorizontalscrollView.scrollTo(x, 0);
} catch (Exception e) {
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 5);
}