Android - Button with rotating/spinning 'loading' image when pressed

天大地大妈咪最大 提交于 2019-12-04 03:56:34

You can create your own button using a RelativeLayout containing a TextView and an ImageView.

<RelativeLayout android:id="@+id/login"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    onClick="[yourLoginMethod]" >

    <TextView android:id="@+id/login_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Log In" />

    <ImageView android:id="@+id/login_loading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/login_text"
        android:visibility="gone" />

</RelativeLayout>

And then in whatever your login method is called, change the contents of the TextView, make it align parent right, and set the ImageView visibility to visible.

loginText.setText("Logging In...");
LayoutParams params = loginText.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
loginText.setLayoutParams(params);
loginLoading.setVisibility(View.VISIBLE);

And then I would also have some code that reverses those changes if the login fails.

Here's an implementation that I came up with, hopefully its reusable:

ProgressButton

At the moment, when the user clicks the button, it will display the drawable (and animate) for you but you will have to dismiss the loading animation manually once you've finished with your background task via:

_progressButton.stopLoadingAnimation();

This will dismiss any animation for you and display any previous text that was there. The only thing missing it that there is no text whilst the animation is in progress, but I think you can hack something together for that. I plan on extending this a little further so that it will allow you to call something like _progressButton.setProgress(10) and then set the percentage that is done. I may even make it thread safe.

This way you don't have to use multiple layouts and embed any textviews on top of buttons, and its all handled for you.

Create your own button, which will consists of a centered TextView and GONE ImageView. After click move TextView to the left and make ImageView with your drawable visible.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!