1. 程式人生 > >Android高階UI PullToRefresh下拉重新整理

Android高階UI PullToRefresh下拉重新整理

配置該第三方庫步驟

1. 下載

下載的是eclipse的library工程,在android studio需要將其作為module加入。

2. 新增到android studio中

file->new->import module->選擇該library project下的資料夾library

file->Project structure->選擇app->選擇dependencies->選擇加號->選擇module dependency->選擇我們上面新增的這個module即可

使用步驟

1. 佈局檔案(attr.xml中包含所有屬性)

<com.handmark.pulltorefresh.library.PullToRefreshScrollView
        xmlns:ptr="http://schemas.android.com/apk/res-auto" //注意
        android:id="@+id/pull_to_refresh_scrollview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ptr:ptrMode="both"                           //上拉重新整理,下拉重新整理均可以
        ptr:ptrDrawable
="@drawable/question_correct_24dp">
//重新整理時左側旋轉的圖片 <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:background="#333333" > <TextView android:layout_width
="match_parent" android:layout_height="wrap_content" android:text="相識不過八年" android:textSize="10pt"/>
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="愛你不過四載"/> <TextView android:layout_width="match_parent" android:layout_height="100pt"/> </LinearLayout> </com.handmark.pulltorefresh.library.PullToRefreshScrollView>

2. java程式碼

public class PullToRefreshActivity extends AppCompatActivity {
    private PullToRefreshScrollView pullToRefreshScrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pull_to_refresh);

        pullToRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pull_to_refresh_scrollview);//獲取佈局控制元件

        //下拉重新整理:OnRefreshListener  下拉、上拉重新整理:OnRefreshListener2
        pullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {

                new GetDataTask().execute();//執行非同步任務

            }
        });

    }

    //下拉重新整理時執行的非同步任務
    private class GetDataTask extends AsyncTask<Void, Void,String[]>{

        @Override
        protected String[] doInBackground(Void... params) {
            try {
                Thread.sleep(4000);//睡眠
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return new String[0];
        }

        protected void onPostExecute(String[] result){
            pullToRefreshScrollView.onRefreshComplete(); //已經完成
            super.onPostExecute(result);
        }
    }
}