android简单的点击刷新

本文介绍了如何在Android应用中实现点击Actionbar上的刷新图标进行数据刷新的功能。通过创建耗时任务并在完成时恢复原始图标,内容包括相关布局文件的设置和使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们要实现的就是actionbar中刷新的图标,点击之后进行刷新,刷新完成后又回到原先的图标;

首先创建一个耗时任务:

class FakeTask extends AsyncTask<Void,Void,Void>{

    @Override
    protected Void doInBackground(Void... params) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {

        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showLoadingIndicator(true);
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        showLoadingIndicator(false);
    }
}


public void showLoadingIndicator(boolean show){
    if(show){
        refreshItem.setEnabled(false);
        refreshItem.setActionView(R.layout.progress);
    }else {
        refreshItem.setActionView(null);
        refreshItem.setEnabled(true);
    }
}


然后就是对actionbar中图标的点击事件进行处理:

public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if(item==refreshItem){
        new FakeTask().execute();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

布局也只有两个文件而已:

首先是progressbar的布局

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="@android:style/Widget.ActionButton"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ProgressBar
        android:layout_width="32dp"
        android:layout_height="32dp"
        style="?android:attr/indeterminateProgressStyle"
        android:layout_gravity="center"/>
</FrameLayout>
再者是menu中的图片

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">
    <item
        android:id="@+id/menu_refresh"
        android:title="@string/refresh"
        app:showAsAction="always"
        android:icon="@drawable/ic_action_refresh"/>
</menu>
这样的话 点击就可以实现图片与progresbar的交替出现

0.0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值