グリッドビューでクリックされたAndroidトグルボタンの位置を取得するにはどうすればよいですか?
次のサンプルコードを使用すると、その位置のトーストメッセージが表示されません。
public class HelloGridView extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ToggleButtonAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
}
そしてトグルアダプター:
public class ToggleButtonAdapter extends BaseAdapter {
private Context mContext;
public ToggleButtonAdapter(Context c) {
mContext = c;
}
@Override
public int getCount() {
return 5;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) { // reuse it if it already exists
view = (View) inflater.inflate(R.layout.items, null);
} else {
view = (View) convertView;
}
ToggleButton toggleButton = (ToggleButton) view.findViewById(R.id.toggleButton1);
TextView textView = (TextView) view.findViewById(R.id.textView1);
textView.setText("Toggle Button " + position);
/*toggleButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ToggleButton t = (ToggleButton) v.findViewById(R.id.toggleButton1);
Toast.makeText(mContext, Boolean.toString(t.isChecked()), Toast.LENGTH_SHORT).show();
}
});*/
return view;
}
}
トグルリスナーのコメントを解除して、その部分で遊んで、位置を取得する方法を教えてください。グリッドビューが構築されているときに、後で参照できるデータをトグルボタンに挿入する方法はありますか?ToggleButtonjavadocを読み取る方法が見つかりませんでした。
どうもありがとう!
編集:
おっと!レイアウトは次のとおりです。
main.xml
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
>
</GridView>
items.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:text="Some label"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"/>
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"/>
</LinearLayout>
</LinearLayout>