android系統自帶下拉刷新控件的實現

android系統自帶的下拉刷新控件SwipeRefreshLayout位于android.support.v4.widget包下,實現步驟如下:
1.在布局文件中添加該控件,該控件一般作為父控件,而且只能包含有一個子控件,并且這個子控件是能夠滑動的,比如scrollview,listview等
2.實現OnRefreshListener接口,并重寫onRefresh函數

詳細代碼如下:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/swipe_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ScrollView
    android:id="@+id/scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
        
        <TextView 
            android:id="@+id/tip_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/pull_fresh"
            android:textSize="15sp"
            />
        <TextView 
            android:id="@+id/random_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#FF000000"
            android:textSize="15sp"
            />
        
    </LinearLayout>
    
</ScrollView>

</android.support.v4.widget.SwipeRefreshLayout>

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.widget.TextView;

/**

  • MainActivity---系統下拉刷新控件的實現
  • @author seabear

*/
public class MainActivity extends Activity implements OnRefreshListener{

private SwipeRefreshLayout mSwipeRefreshLayout;
private TextView mRandomText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mSwipeRefreshLayout = (SwipeRefreshLayout)this.findViewById(R.id.swipe_refresh);
    mSwipeRefreshLayout.setOnRefreshListener(this);
    
    mRandomText = (TextView)this.findViewById(R.id.random_text);
    
}


@Override
public void onRefresh() {
    mSwipeRefreshLayout.setRefreshing(true);
    
    (new Handler()).postDelayed(new Runnable() {
        
        @Override
        public void run() {
            //3秒后停止刷新
            mSwipeRefreshLayout.setRefreshing(false);
            int num = (int)(Math.random() * 100 + 1);
            String s = mRandomText.getText().toString();
            s = s + " " + num;
            mRandomText.setText(s);
            
        }
    }, 3000);
}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容