2011-10-31

在 Android 處理 ListView 元件點擊與長點擊

長點擊就是點著不放,算是不同於 PC 才有的隱藏功能,主角分別為 OnItemClickListener 與 OnItemLongClickListener,不要與 OnClickListener 與 OnLongClickListener 搞混,後面兩個對象是 ListView,不是 ListView 裡的 item。

LongClickActivity
public class LongClickActivity extends ListActivity {

 private static final String TAG = "LongClickActivity";
 private static final String SEPARATOR = ".";

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.listview);
  this.setListAdapter(this.createArrayAdapter());
  ListView lv = (ListView) this.findViewById(android.R.id.list);
  // 長點擊 - 加一
  lv.setOnItemLongClickListener(new OnItemLongClickListener() {

   @Override
   public boolean onItemLongClick(AdapterView<?> parent, View view,
     int position, long id) {
    TextView tv = (TextView) view;
    tv.setText(calcText(tv, true));
    // true 表示不再丟給 onItemClick 處理,false 則會再執行 onItemClick,如果有的話
    return true;
   }
  });
  // 點擊 - 減一
  lv.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {
    TextView tv = (TextView) view;
    tv.setText(calcText(tv, false));
   }
  });
  // lv.setOnLongClickListener(...);
 }

 private String calcText(TextView tv, boolean add) {
  String s = tv.getText().toString();
  int idx = s.indexOf(LongClickActivity.SEPARATOR);
  String txt;
  String cnt;
  if (idx > 0) {
   txt = s.substring(0, idx);
   cnt = String.valueOf(Integer.parseInt(s.substring(idx + 1))
     + (add ? 1 : -1));
   txt = txt + LongClickActivity.SEPARATOR + cnt;
  }
  else {
   txt = s + LongClickActivity.SEPARATOR + (add ? "1" : "-1");
  }
  return txt;
 }

 private ArrayAdapter<String> createArrayAdapter() {
  List<String> list = new ArrayList<String>();
  for (int i = 1; i <= 10; i++) {
   list.add("第 " + i + " 關");
  }
  return new ArrayAdapter<String>(this, R.layout.list_item,
    list.toArray(new String[] {}));
 }
}
畫面設定檔請參考 捲動 ListView 到指定的位置

沒有留言:

張貼留言