ある種の選択キューが必要な場合は、フォーカス可能なオブジェクトが必要だと思います。ただし、フォーカス可能なオブジェクト(Buttonなど)では、OnItemClickListenerをGridViewにアタッチすることは機能しません(私が正しく覚えている場合)。むしろ、アダプタのgetView()で各アイテムにOnClickListenerを個別にアタッチする必要があります。
アダプタ:
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
Button button;
if (convertView == null) { // if it's not recycled, initialize some attributes
button = new Button(mContext);
// set layout params (make sure its GridView.layoutParams)
// and other stuff
}
else {
button = (Button) convertView;
}
button.setBackgroundResource(mThumbIds[position]); // mThumbIds hold Resource Ids
button.setOnClickListener(new OnClickListener() {
onClick(View v) {
// store directly to database here, or send it with the activity with sharedPreferences (below)
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences("MY_PREFERENCE", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("button_id", mThumbIds[position]);
// Commit the edits!
editor.commit();
}
});
return button;
}
}
アクティビティ側で、ボタンonClickListenerを保存します。
onClick(View v) {
// Restore preferences
SharedPreferences settings = getSharedPreferences("MY_PREFERENCE", 0);
int id = settings.getInt("button_id", -1);
// now safe all stuff to database
}
ボタンはフォーカス可能であるため、詳細が欠落している可能性がありますが、これで十分だと思います。また、.xmlで定義されたセレクターリソースを使用して選択を行うことができます。ただし、それは別の質問で対処する必要があります。
編集1:実際、私はそれについて考えたので、ドローアブル.xml(セレクター)がIDを持つことができるかどうかわかりません。後でこれを自宅で実装して試してみる必要があります。
編集2:sharedPreference部分を追加しました
編集3:sharedPreferenceのアクティビティ側クエリを追加しました。