Android下拉重新整理以及GridView使用方法詳解_Android

來源:互聯網
上載者:User

GridView是類似於ListView的控制項,只是GridView可以使用多個列來呈現內容,而ListView是以行為單位,所以用法上是差不多的。
主布局檔案,因為要做下拉重新整理,所以加了一個ProgressBar,GridView的numColumns屬性是指每一行有多少列

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:tools="http://schemas.android.com/tools"  android:layout_width="match_parent"  android:layout_height="match_parent"  tools:context="com.example.girdlayoutdemo.MainActivity" >  <ProgressBar    android:id="@+id/pb"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_centerHorizontal="true" />  <GridView    android:layout_below="@id/pb"    android:id="@+id/gv"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:layout_margin="5dp"    android:gravity="center"    android:numColumns="2" >  </GridView></RelativeLayout>

每個Item的布局檔案,這裡比較簡單的一張圖片加一段文字

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:orientation="vertical" >  <ImageView    android:id="@+id/item_iv"    android:layout_width="fill_parent"    android:layout_height="0dp"    android:layout_weight="3" />  <TextView    android:id="@+id/item_tv"    android:layout_width="match_parent"    android:layout_height="0dp"    android:layout_weight="1" /></LinearLayout>

主活動代碼:

public class MainActivity extends Activity {  private GridView gv;  private ProgressBar pb;  private List<Map<String, Object>> list;  private SimpleAdapter adapter;  private GestureDetector gsDetector;  private Handler handler = new Handler() {    @Override    public void handleMessage(Message msg) {      switch (msg.what) {      case 1:        pb.setVisibility(View.GONE);        Toast.makeText(MainActivity.this, "重新整理成功", 200).show();        break;      default:        break;      }    }  };  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    pb = (ProgressBar) findViewById(R.id.pb);    gv = (GridView) findViewById(R.id.gv);    pb.setVisibility(View.GONE);    initData();    adapter = new SimpleAdapter(this, list, R.layout.item_layout,        new String[] { "image", "text" }, new int[] { R.id.item_iv,            R.id.item_tv });    gv.setAdapter(adapter);    gsDetector = new GestureDetector(this, new Mlistener());    gv.setOnTouchListener(new OnTouchListener() {      @Override      public boolean onTouch(View v, MotionEvent event) {        // Log.e("MainActivity", event.getX()+"");        return gsDetector.onTouchEvent(event);      }    });  }  private void initData() {    list = new ArrayList<Map<String, Object>>();    for (int i = 0; i < 20; i++) {      Map<String, Object> map = new HashMap<String, Object>();      map.put("image", R.drawable.gift_item_default);      map.put("text", "一隻冰瑩豬豬");      list.add(map);    }  }  class Mlistener implements OnGestureListener {    @Override    public boolean onDown(MotionEvent e) {      return false;    }    @Override    public void onShowPress(MotionEvent e) {    }    @Override    public boolean onSingleTapUp(MotionEvent e) {      return false;    }    @Override    public boolean onScroll(MotionEvent e1, MotionEvent e2,        float distanceX, float distanceY) {      return false;    }    @Override    public void onLongPress(MotionEvent e) {    }    @Override    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,        float velocityY) {      if (e2.getY() - e1.getY() > 0 && gv.getFirstVisiblePosition() == 0) {        pb.setVisibility(View.VISIBLE);        Animation animation = new ScaleAnimation(1f, 1f, 0, 1f);        animation.setDuration(300);        pb.startAnimation(animation);        new Thread(new Runnable() {          @Override          public void run() {            try {              Thread.sleep(2000);              Message msg = new Message();              msg.what = 1;              handler.sendMessage(msg);            } catch (InterruptedException e) {              // TODO Auto-generated catch block              e.printStackTrace();            }          }        }).start();      }      return false;    }  }}

解析:
 在onCreate方法中先擷取兩個組件,然後把progressBar設定為隱藏,下拉的時候再顯示,重新整理完畢再隱藏。然後為GridView設定資料來源,這裡方便起見用SimpleAdapter,然後給GridView設定ontouchListener,並在onTouch方法中把觸摸事件交給我們自訂的GestureDetector對象來處理,在GestureDetector的onFling方法中處理下拉事件,在裡面判斷是否下拉以及GridView是否在最頂端,如果是,顯示progressBar控制項並開一個線程來處理重新整理,這裡做類比就睡眠2000毫秒,最後用message對象返回一個訊息給Handler,Handler在主線程中更新GridView。

@Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    pb = (ProgressBar) findViewById(R.id.pb);    gv = (GridView) findViewById(R.id.gv);    pb.setVisibility(View.GONE);    initData();    adapter = new SimpleAdapter(this, list, R.layout.item_layout,        new String[] { "image", "text" }, new int[] { R.id.item_iv,            R.id.item_tv });    gv.setAdapter(adapter);    gsDetector = new GestureDetector(this, new Mlistener());    gv.setOnTouchListener(new OnTouchListener() {      @Override      public boolean onTouch(View v, MotionEvent event) {        // Log.e("MainActivity", event.getX()+"");        return gsDetector.onTouchEvent(event);      }    });  }

class Mlistener implements OnGestureListener {    @Override    public boolean onDown(MotionEvent e) {      return false;    }    @Override    public void onShowPress(MotionEvent e) {    }    @Override    public boolean onSingleTapUp(MotionEvent e) {      return false;    }    @Override    public boolean onScroll(MotionEvent e1, MotionEvent e2,        float distanceX, float distanceY) {      return false;    }    @Override    public void onLongPress(MotionEvent e) {    }    @Override    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,        float velocityY) {      if (e2.getY() - e1.getY() > 0 && gv.getFirstVisiblePosition() == 0) {        pb.setVisibility(View.VISIBLE);        Animation animation = new ScaleAnimation(1f, 1f, 0, 1f);        animation.setDuration(300);        pb.startAnimation(animation);        new Thread(new Runnable() {          @Override          public void run() {            try {              Thread.sleep(2000);              Message msg = new Message();              msg.what = 1;              handler.sendMessage(msg);            } catch (InterruptedException e) {              // TODO Auto-generated catch block              e.printStackTrace();            }          }        }).start();      }      return false;    }  }

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.