[英]dynamically add textview to layout
我一直在這里搜索,但是似乎找不到正確的來源/答案。
我想根據我在數據庫中的元素數量,從SQLite數據庫中提取數據並在布局中顯示它(使用TextViews)。
如何“即時”將TextViews添加到布局? 對textviews進行硬編碼非常簡單,但是我不知道如何動態地進行編碼。 謝謝你的幫助!
這是我的課:
package android.GUI;
public class Shifts extends Activity implements OnClickListener {
String dbTime;
DBAdapter DB = new DBAdapter(this);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shifts);
LinearLayout layout = (LinearLayout) findViewById(R.id.shifts);
TextView text = new TextView(this);
DB.open();
Cursor c = DB.getAllShifts();
if (c.moveToFirst()) {
do {
} while (c.moveToNext());
layout.addView(text);
text.setText(showDB(c));
}
DB.close();
}
public String showDB(Cursor c) {
dbTime = c.getString(1) + "\n" + c.getString(2);
return dbTime;
}
你用過
DBAdapter DB = new DBAdapter(this);
Activity
開始之前的那一行。 因此,此關鍵字引起的是空指針異常。請在db.open();
之前的onCreate()
方法上寫此行db.open();
動態添加:
TextView tv = new TextView(this);
tv.setText("TaskID");
TextView tv1 = new TextView(this);
task = new EditText(this);
task.setMaxWidth(100);
task.setMinHeight(100);
tv1.setText("Task");
id = new EditText(this);
id.setMaxHeight(10);
TextView tv2 = new TextView(this);
name = new EditText(this);
name.setMaxHeight(1);
tv2.setText("Name");
LinearLayout l = new LinearLayout(this);
l.setOrientation(LinearLayout.VERTICAL);
l.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
setContentView(l);
l.addView(tv);
l.addView(id);
l.addView(tv1);
l.addView(task);
l.addView(tv2);
您可以使用ListView和SimpleCursorAdapter,它們會自動為數據庫記錄創建視圖。 http://thinkandroid.wordpress.com/2010/01/09/simplecursoradapters-and-listviews/
或者,如果您仍然想自己管理它,則可以使用以下方法:
// In onCreate method.
// E.g. your topmost view is LinearLayour with id 'layout'.
LinearLayout layout = findViewById(R.id.layout);
TextView text = new TextView(this);
text.setText("Hello, I'm dynamically added text view");
layout.addView(text).
您正在尋找的是ListView 。 要將數據庫中的數據填充到列表中,請使用SimpleCursorAdapter
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.