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 到指定的位置。
沒有留言:
張貼留言