我正在尝试从我的数据库中获取一些数据,并为每一行数据创建一个新的线性布局。唯一的问题是我不知道如何给每个创建的 LinearLayouts 一个 id,并使用该 id,以便在单击布局时,我知道它是哪一个,例如第四个或第一个。当我尝试这个时,我得到一个 IndexOutOfBoundException。我为此使用了 set 和 getTag,并且我使用了 id 的 counter 变量:
// 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();
}