动态地将textview添加到布局

时间:2011-08-23 01:04:06

标签: java android sqlite layout

我一直在这里搜索,但我似乎找不到合适的来源/答案。

我想从我的SQLite数据库中提取数据并根据我在数据库中拥有的元素数量将其显示在布局中(使用TextViews)。

如何“动态”将TextView添加到布局中? 硬编码textview非常简单,但我不知道如何动态。 谢谢你的帮助!

这是我的班级:

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;
}

3 个答案:

答案 0 :(得分:3)

您已使用

DBAdapter DB = new DBAdapter(this);

启动Activity之前的行。所以这个关键字导致的是空指针异常。请在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);

答案 1 :(得分:1)

您可以使用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).

答案 2 :(得分:1)

您要找的是ListView。要将数据从db填充到列表中,请使用SimpleCursorAdapter

相关问题