データベースからデータを取得しようとしています。データの行ごとに、新しい線形レイアウトを作成します。唯一の問題は、作成された LinearLayouts のそれぞれに id を与える方法を理解できないことです。その id を使用して、レイアウトがクリックされたときに、4 つ目や最初のものなど、それがどれであるかを知ることができます。これを試すと、IndexOutOfBoundException が発生します。これには set と getTag を使用しており、id にはカウンター変数を使用しています。
// Fill data
db.open();
// Get all of the rows from the database and create the item list
Cursor mNotesCursor = db.fetchAllNotes();
this.startManagingCursor(mNotesCursor);
int counter = 0;
while (mNotesCursor.moveToNext()) {
String titleText = (mNotesCursor.getString(mNotesCursor
.getColumnIndex("title")));
String bodyText = mNotesCursor.getString(mNotesCursor
.getColumnIndex("body"));
String dateText = mNotesCursor.getString(mNotesCursor
.getColumnIndex("date"));
final LinearLayout cardsLayout = new LinearLayout(this);
cardsLayout.setOrientation(LinearLayout.VERTICAL);
cardsLayout.setBackgroundDrawable(getResources().getDrawable(
R.drawable.card_container_background));
cardsLayout.setTag(counter);
LinearLayout.LayoutParams layouLinearParams = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
RelativeLayout titleLayout = new RelativeLayout(this);
titleLayout.setPadding(4, 4, 4, 4);
// Title text
TextView tvTitle = new TextView(this);
tvTitle.setText(titleText);
// Text Font Attributes
tvTitle.setTextColor(getResources().getColor(R.color.textColor));
tvTitle.setTypeface(robotoLight);
tvTitle.setTextSize(25);
titleLayout.addView(tvTitle);
titleLayout.setLayoutParams(layouLinearParams);
RelativeLayout.LayoutParams titleRelativeParams = (RelativeLayout.LayoutParams) tvTitle
.getLayoutParams();
titleRelativeParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
tvTitle.setLayoutParams(titleRelativeParams);
// Date text
TextView tvDate = new TextView(this);
tvDate.setText(dateText);
// Text Font Attributes
tvDate.setTextColor(getResources().getColor(R.color.textColor));
tvDate.setTypeface(robotoLight);
tvDate.setTextSize(15);
titleLayout.addView(tvDate);
RelativeLayout.LayoutParams dateRelativeParams = (RelativeLayout.LayoutParams) tvDate
.getLayoutParams();
dateRelativeParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
tvDate.setLayoutParams(dateRelativeParams);
// Body Text
TextView tvBody = new TextView(this);
tvBody.setText(bodyText);
// Text Font Attributes
tvBody.setTypeface(robotoLight);
tvTitle.setTextColor(getResources().getColor(R.color.textColor));
tvBody.setTextSize(20);
tvBody.setPadding(4, 4, 4, 4);
cardsLayout.addView(titleLayout);
cardsLayout.addView(tvBody);
root.addView(cardsLayout);
cardsLayout.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(NotesListActivity.this, NoteEdit.class);
i.putExtra(NotesDbAdapter.KEY_ROWID, (Integer)cardsLayout.getTag());
startActivityForResult(i, ACTIVITY_EDIT);
}
});
}
this.stopManagingCursor(mNotesCursor);
db.close();
}