SoFunction
Updated on 2025-04-10

Android uses Handler to achieve elastic sliding of View

Elastic sliding principle

A large slide is not a few small slides and is completed within a time period. A better user experience

There are many ways to implement it, including using Scroller, animation, and delay strategies.

Use Handler to achieve elastic sliding

The effect can be seen to slide the Button button. Note that here is to change the content of the View.

You can try to remove the RelativeLayout on the outer layer of Button and place the id under the Button. It was found that it was Button's text sliding

<RelativeLayout xmlns:andro
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:
android:layout_height="wrap_content"
android:layout_width="300dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" 
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" 
android:text="Button" />
</RelativeLayout>
</RelativeLayout> 
import ;
import ;
import ;
import ;
public class MainActivity extends Activity {
private static final int MESSAGE_SCROLL_TO = 1;
private static final int FRAME_OUT = 30;
private static final int DELAYED_TIME = 30;
private RelativeLayout button;
private int mcount;
private Handler handler = new Handler(){
public void handleMessage(Message msg){
switch () {
case MESSAGE_SCROLL_TO:
mcount++;
if (mcount <= FRAME_OUT) {
float fraction = mcount / (float)FRAME_OUT;
int scrollx =(int) (fraction * 100);
(scrollx, 0);
(MESSAGE_SCROLL_TO, DELAYED_TIME);
}
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
(savedInstanceState);
setContentView(.activity_main);
button = (RelativeLayout) findViewById(.button1);
(MESSAGE_SCROLL_TO, DELAYED_TIME);
}
}

The above is what the editor introduced to you using Handler to achieve elastic view sliding. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!