问题
For now, I have a database with a single table having a single column of type TEXT. I want to be able to retrieve the data from that table and for each string from the table I want to insert it into it's own TextView. I want the TextViews to be arranged in vertical LinearLayout fashion. I know retrieved data is presented in an activity using ListView but I want separate TextView for each because I later want to set each TextView clickable and give each one some function. Please help me with the code and tell me if any project files need to be included in the question.
回答1:
try this
Fetch data from Database
in Cursor
and pass this cursor in below method it will return
a view
which you can pass in setContentView(view)
public LinearLayoutCompat defaultPage(Cursor mCursor) {
LinearLayoutCompat layout = new LinearLayoutCompat(this);
layout.setLayoutParams(new LinearLayoutCompat.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT));
layout.setGravity(Gravity.CENTER);
layout.setOrientation(LinearLayoutCompat.VERTICAL);
for(int i=0;i<mCursor.getCount();i++) {
mCursor.moveToPosition(i);
AppCompatTextView defaultText = new AppCompatTextView(this);
defaultText.setText(mCursor.getString(mCursor.getColumnIndex("TOUR_COLUMN_NMAE")));
defaultText.setTextSize(20);
defaultText.setTypeface(null, Typeface.BOLD);
defaultText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// Toast.makeText(mContext, "Work in progress", Toast.LENGTH_SHORT).show();
}
});
layout.addView(defaultText);
}
return layout;
}
来源:https://stackoverflow.com/questions/44334532/how-to-set-each-item-retrieved-from-sqlite-database-into-a-textview-of-its-own