Display images in auto scrolling horizontalscrolview - android

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

Related

animation not working in api response success callback

The expand animation not working if its in the success block of the api call. But if i put it out from the success block then its working well.
I have to call animation block inside the success block. Because the data is coming from the api.
Here is the sample.
getWeeklyWaterDate method:
public void getWeeklyWaterData(final WaterDataCallBack callBack)
{
// Find last monday
Calendar lastMonday = Calendar.getInstance();
while (lastMonday.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY)
{
lastMonday.add(Calendar.DATE, -1);
}
Calendar now = Calendar.getInstance();
lastMonday.add(Calendar.DAY_OF_YEAR, -1);
lastMonday.set(Calendar.HOUR, 24);
lastMonday.set(Calendar.MINUTE, 0);
lastMonday.set(Calendar.SECOND, 0);
lastMonday.set(Calendar.MILLISECOND, 0);
HashMap<String, String> params = new HashMap<>();
params.put("startDate", Utils.formatYYMMDDDTHHMMSSz(lastMonday.getTimeInMillis()));
params.put("endDate", Utils.formatYYMMDDDTHHMMSSz(now.getTimeInMillis()));
ServiceConnector.groupamaAPI.getMyWaters(params).enqueue(new SuccessCallback<MyWaterResponse>() {
#Override
public void onSuccess(Response<MyWaterResponse> response) {
super.onSuccess(response);
callBack.onWaterDataReceived(response.body());
}
});
}
calling getWeeklyWaterDataMethod from the fragment.
WaterHelper.getCurrent().getWeeklyWaterData(new WaterHelper.WaterDataCallBack() {
#Override
public void onWaterDataReceived(MyWaterResponse waterResponse) {
Collections.reverse(waterResponse.waterLogs);
for (Integer i = 0 ; i < waterResponse.waterLogs.size() ; i++)
{
WaterLog waterLog = waterResponse.waterLogs.get(i);
Calendar calendar = Calendar.getInstance();
calendar.setTime(waterLog.LogDate);
dates.add(calendar);
waterAmounts.add(new WaterAmount(calendar, waterLog.WaterMililiter.intValue()));
}
prepareTotalAndAverage(waterResponse.waterAverage);
prepareGraph2();
}
});
here is the animation code:
final Integer finalGraphMaxY = 6000;
chartContainerLL.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
#Override
public void onGlobalLayout()
{
chartContainerLL.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// Animate Bars
Integer totalHeight = chartContainerLL.getHeight();
ExpandHeightAnimation expandHeightAnimation = new ExpandHeightAnimation(barMonday, 55);
expandHeightAnimation.setDuration(800/* animation time */);
barMonday.startAnimation(expandHeightAnimation);
ExpandHeightAnimation expandHeightAnimation2 = new ExpandHeightAnimation(barTuesday, 30);
expandHeightAnimation2.setDuration(800/* animation time */);
barTuesday.startAnimation(expandHeightAnimation2);
ExpandHeightAnimation expandHeightAnimation3 = new ExpandHeightAnimation(barWednesday, 40);
expandHeightAnimation3.setDuration(800/* animation time */);
barWednesday.startAnimation(expandHeightAnimation3);
ExpandHeightAnimation expandHeightAnimation4 = new ExpandHeightAnimation(barThursday, 30);
expandHeightAnimation4.setDuration(800/* animation time */);
barThursday.startAnimation(expandHeightAnimation4);
ExpandHeightAnimation expandHeightAnimation5 = new ExpandHeightAnimation(barFriday, 40);
expandHeightAnimation5.setDuration(800/* animation time */);
barFriday.startAnimation(expandHeightAnimation5);
if(dates.size() >= 6 && dates.get(5).get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY)
{
ExpandHeightAnimation expandHeightAnimation6 = new ExpandHeightAnimation(barSaturday, totalHeight * getNeededDayWaterAmount(Calendar.SATURDAY).mililiter / finalGraphMaxY);
expandHeightAnimation6.setDuration(800/* animation time */);
barSaturday.startAnimation(expandHeightAnimation6);
}
if(dates.size() >= 7 && dates.get(6).get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY)
{
ExpandHeightAnimation expandHeightAnimation7 = new ExpandHeightAnimation(barSunday, totalHeight * getNeededDayWaterAmount(Calendar.SUNDAY).mililiter / finalGraphMaxY);
expandHeightAnimation7.setDuration(800/* animation time */);
barSunday.startAnimation(expandHeightAnimation7);
}
}
});
ExpandHeightAnimation Class
public class ExpandHeightAnimation extends Animation
{
int targetHeight;
View view;
public ExpandHeightAnimation(View view, int targetHeight) {
this.view = view;
this.targetHeight = targetHeight;
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
view.getLayoutParams().height = (int) (targetHeight * interpolatedTime);
view.requestLayout();
}
#Override
public void initialize(int width, int height, int parentWidth,
int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
}
#Override
public boolean willChangeBounds() {
return true;
}
}
You need to add GlobalLayoutListener when onCreate() or onCreateView() called.
First add two flags for animation. If these both are true, your animation will start.
boolean animateFlag1 = false;
boolean animateFlag2 = false;
Secondly, add your global layout listener inside onCreate():
llContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
#Override
public void onGlobalLayout()
{
llContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
animateFlag1 = true;
animate();
}
});
You can see that when onGlobalLayout() called, remove listener, set first flag to true and call animate method.
After these, do the same thing for your callback which starts to animation. Set your second flag as true,
#Override
public void success(Result result) {
animateFlag2 = true;
animate();
}
Here is the animate method, which includes your onGlobalLayout() method codes you wrote before.
private void animate(){
if(animateFlag1 && animateFlag2){
// Animate Bars
ExpandHeightAnimation expandHeightAnimation = new ExpandHeightAnimation(view, 500);
expandHeightAnimation.setDuration(800/* animation time */);
view.startAnimation(expandHeightAnimation);
//More your codes to animate
//Set your all flags to false to prevent animating again
animateFlag1 = animateFlag2 = false;
}
}
try replacing this
prepareTotalAndAverage(waterResponse.waterAverage);
prepareGraph2();
with
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
prepareTotalAndAverage(waterResponse.waterAverage);
prepareGraph2();
}
}, 1);
OR
runOnUiThread(new Runnable() {
#Override
public void run() {
prepareTotalAndAverage(waterResponse.waterAverage);
prepareGraph2();
}
});
Its a bit of trick , but worked for me.

Horizontal Recycler view auto scrolling error

I have this RecyclerView that functions as a ticker, the auto scrolling works fine at first but after a period of time it becomes strange (back and forth) and the RecyclerView gets stuck at an item without smooth scrolling anymore, can anyone help me.
this is my layout manager:
LinearLayoutManager layoutManager = new LinearLayoutManager(HomeActivity.this, LinearLayoutManager.HORIZONTAL, false) {
#Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
LinearSmoothScroller smoothScroller = new LinearSmoothScroller(HomeActivity.this) {
private static final float SPEED = 5500f;// Change this value (default=25f)
#Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return SPEED / displayMetrics.densityDpi;
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
};
rvTicker.setLayoutManager(layoutManager);
this is my auto scrolling function:
public void autoScroll(){
speedScroll = 0;
handler = new Handler();
runnable = new Runnable() {
int count = 0;
#Override
public void run() {
if(count == tickerAdapter.getItemCount())
count = 0;
if(count < tickerAdapter.getItemCount()){
rvTicker.smoothScrollToPosition(++count);
handler.postDelayed(this,speedScroll);
}
}
};
handler.postDelayed(runnable,speedScroll);
}
SOLVED, I tweaked the autoscroll function:
public void autoScroll(){
speedScroll = 0;
handler = new Handler();
runnable = new Runnable() {
int count = 0;
#Override
public void run() {
if(count == tickerAdapter.getItemCount())
count = 0;
else {
if(count < tickerAdapter.getItemCount()){
rvTicker.smoothScrollToPosition(++count);
handler.postDelayed(this,speedScroll);
}else {
count = 0;
}
}
Log.wtf("tickerAdapter.getItemCount()", tickerAdapter.getItemCount()+"");
Log.wtf("count", count+"");
Log.wtf("++count", ++count+"");
Log.wtf("==============","=============");
}
};
handler.postDelayed(runnable,speedScroll);
}

Android: move imageView thats lay on window manager with animation

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

Horizontal ScrollView Gallery. Scroll both directions or from begining

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

OnClickListener in TranslateAnimation

I am doing a project using TranslateAnimation in Android. In that I am translating images successfully but I have to add onClickListener to the images. That means I have click the images during translating and get their values but I am getting the onClick action on the images.
I am using following code:
public class SampleGame extends Activity implements OnClickListener {
int x10, x20, y10, y20;
ImageView img;
Button animation;
Handler transHandler;
RelativeLayout layout;
Random rand;
int mSpeedX, mSpeedY;
int width, height;
Thread thread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layout = (RelativeLayout) findViewById(R.id.layout);
animation = (Button) findViewById(R.id.animation);
animation.setOnClickListener(this);
rand = new Random();
width = getWindow().getWindowManager().getDefaultDisplay().getWidth() - 20;
height = getWindow().getWindowManager().getDefaultDisplay().getHeight() - 70;
x10 = width - rand.nextInt(width);
y10 = height;
x20 = width;
y20 = height - rand.nextInt(height);
thread = new Thread();
img.setOnClickListener(this);
}
public void onPause() {
super.onPause();
thread = null;
}
#Override
public void onClick(View v) {
if (v.equals(img)) {
Log.e("img clicked :", "yaaaaaaaaa");
}
if (v.equals(animation)) {
animation.setVisibility(View.INVISIBLE);
callTransform();
}
}
public void callTransform() {
if (thread != null) {
thread = new Thread() {
public void run() {
// Log.e("X1 value :",String.valueOf(x10));
// Log.e("X2 value :",String.valueOf(x20));
// Log.e("Y1 value :",String.valueOf(y10));
// Log.e("Y2 value :",String.valueOf(y20));
transformAnimation(x10, x20, y10, y20, img, 4000);
try {
Thread.sleep(4000);
} catch (Exception e) {
}
// Message msg=transHandler.obtainMessage();
// transHandler.sendMessage(msg);
x10 = x20;
y10 = y20;
if (x10 == width) {
x20 = width - rand.nextInt(width);
y20 = 0;
} else if (y10 == 0) {
x20 = 0;
y20 = height - rand.nextInt(height);
} else if (x10 == 0) {
x20 = width - rand.nextInt(width);
y20 = height;
} else if (y10 == height) {
x20 = width;
y20 = height - rand.nextInt(height);
}
callTransform();
}
};
thread.start();
}
}
public void transformAnimation(int xFrom, int xTo, int yFrom, int yTo, final ImageView image, int time) {
TranslateAnimation anim = new TranslateAnimation(xFrom, xTo, yFrom, yTo);
anim.setDuration(time);
image.setAnimation(anim);
}
}
and I tried the following example also - 2D-Tutorial Example.
But in this also I didn't onClick action for images.
So how to get the onClick action on image during translation?
or
Is there any other way to translate the image with on click action?
Thanks in Advance.
during animation the object remains in its original position but it animates translation so you would need to update the Layout Parameters manually during animation

Categories

Resources