Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

GridView 項目按下換圖:用 OnTouchListener 做即時視覺回饋

編輯:關於 Android 程式設計

用過 YY 影音這類播放軟體就會注意到一個細節:點擊 GridView 的某個項目時,圖示會在按下的瞬間換成另一張圖,放手後才跳頁。這個小小的回饋讓介面感覺「有反應」,成本卻很低。本文示範怎麼做。

實作步驟

  1. 建立一個含 GridView 的 Activity。
  2. 寫 item 布局,裡面放一個 TextView(用 compound drawable 呈現圖示)或 ImageView 加 TextView。
  3. 自訂一個繼承 BaseAdapter 的 Adapter。
  4. 在 getView 中為每個項目掛上 OnTouchListener,於 ACTION_DOWN 換圖、ACTION_UP 換回並跳頁。

MainActivity

public class MainActivity extends Activity {
    private GridView gv;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        gv = (GridView) findViewById(R.id.mygrid);
        gv.setAdapter(new AddAdapter(this));
    }

    public class AddAdapter extends BaseAdapter {
        private final LayoutInflater mInflater;
        private final ArrayList mItems = new ArrayList();

        /** 清單中的單一項目 */
        public class ListItem {
            public final CharSequence text;
            public final Drawable image;
            public final Drawable touchimage;   // 按下時要顯示的圖

            public ListItem(Resources res, int textResourceId,
                            int imageResourceId, int touchImageResourceId) {
                text = res.getString(textResourceId);
                image = imageResourceId != -1 ? res.getDrawable(imageResourceId) : null;
                touchimage = touchImageResourceId != -1 ? res.getDrawable(touchImageResourceId) : null;
            }
        }

        public AddAdapter(MainActivity launcher) {
            super();
            mInflater = (LayoutInflater) launcher.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            Resources res = launcher.getResources();
            mItems.add(new ListItem(res, R.string.item1, R.drawable.item1, R.drawable.item1back));
            mItems.add(new ListItem(res, R.string.item2, R.drawable.item2, R.drawable.item2back));
            mItems.add(new ListItem(res, R.string.item3, R.drawable.item3, R.drawable.item3back));
            mItems.add(new ListItem(res, R.string.item4, R.drawable.item4, R.drawable.item4back));
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            final ListItem item = (ListItem) getItem(position);
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.grid_item, parent, false);
            }
            final TextView textView = (TextView) convertView;
            textView.setTag(item);
            textView.setText(item.text);
            textView.setCompoundDrawablesWithIntrinsicBounds(null, item.image, null, null);

            textView.setOnTouchListener(new OnTouchListener() {
                public boolean onTouch(View arg0, MotionEvent arg1) {
                    if (arg1.getAction() == MotionEvent.ACTION_DOWN) {
                        textView.setCompoundDrawablesWithIntrinsicBounds(null, item.touchimage, null, null);
                    } else if (arg1.getAction() == MotionEvent.ACTION_UP) {
                        textView.setCompoundDrawablesWithIntrinsicBounds(null, item.image, null, null);
                        startActivity(new Intent(MainActivity.this, Page1Activity.class));
                    }
                    return true;
                }
            });
            return convertView;
        }

        public int getCount() { return mItems.size(); }
        public Object getItem(int position) { return mItems.get(position); }
        public long getItemId(int position) { return position; }
    }
}

布局檔

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <GridView android:id="@+id/mygrid"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:numColumns="2"
        android:verticalSpacing="10dip"
        android:horizontalSpacing="10dip"
        android:stretchMode="columnWidth"
        android:gravity="center" >
    </GridView>
</LinearLayout>

grid_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:drawablePadding="14dip"
    android:paddingLeft="15dip"
    android:paddingRight="15dip"
    android:gravity="center_horizontal" />

為什麼用 setCompoundDrawables 而不是 ImageView

把圖示設成 TextView 的 compound drawable,可以省掉一個子 View 與一段 findViewById,布局層級更淺、getView 更快。setCompoundDrawablesWithIntrinsicBounds 的參數順序是「左、上、右、下」,圖示要放上方就填第二格,其餘補 null。

幾個實務上的改進空間

  • selector 是更省力的替代方案:如果只是換圖而不需要跳別的頁面,直接在 res/drawable 寫一個 state_pressed 的 selector XML,讓 ImageView 引用即可,一行程式碼都不用寫。
  • 注意 ACTION_CANCEL:使用者按下後手指滑出項目範圍時會收到 ACTION_CANCEL 而非 ACTION_UP。若不處理 ACTION_CANCEL,圖示會卡在「按下」狀態看起來像壞了。
  • OnTouchListener 會吃掉 OnItemClickListener:回傳 true 表示事件已被消費,GridView 本身的點擊監聽不會觸發。若同時需要兩者,記得自行在 ACTION_UP 裡補上原本的點擊邏輯。
  • 跳頁前先復原圖示:範例已照這個順序處理。若顛倒,返回上一頁時會短暫閃現按下的圖。

總體來說,這個效果的重點不在技術難度,而在「記得處理所有可能的手指離開路徑」——按下、放手、取消,三種都要照顧到,互動才會乾淨。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved