【问题标题】:How to add new TextView with new data in cycle?如何在循环中添加带有新数据的新 TextView?
【发布时间】:2011-09-24 15:16:14
【问题描述】:

如何从数据库中添加带有新数据(名称)的新 TextView?并添加到 TableLayout 中的 tableRow?

我的桌子:

        _id name
         1   Said
         2   Bill
 etc


     Cursor cursor = database.query(TABLE_NAME,
    new String[] {STUDENT_NAME},
   null, null,null,null,null);

          cursor.moveToFirst();
                String text = cursor.getString(0);
           TextView name1 = (TextView) findViewById(R.id.edit);
                name1.setText(text);


   cursor.close();

【问题讨论】:

    标签: java android android-layout android-widget tablelayout


    【解决方案1】:

    如果你想动态添加TextViews:

    ViewGroup group = (ViewGroup) findViewById(R.id.group_you_want_to_add_to);
    try {
        if (!cursor.moveToFirst()) {
            return;
        }
    
        do {
            TextView textView = new TextView(this);
            textView.setText(cursor.getString(0));
            group.addView(textView,
               new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        } while (cursor.moveToNext());
    } finally {
        cursor.close();
    }
    

    如果你想创建一个TableRow,你最好在一个 XML 文件中定义它并在每次迭代时对其进行扩充:

    LayoutInflater inflater = LayoutInflater.from(this);
    
    // then you query a database and obtain a cursor...
    try {
        if (!cursor.moveToFirst()) {
            return;
        }
    
        do {
            TableRow row = inflater.inflate(R.id_table_row, table, null);
            ((TextView) row.findViewById(R.id.text)).setText(cursor.getString(0));
            table.addView(row);
        } while (cursor.moveToNext());
    } finally {
        cursor.close();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      • 2017-04-09
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多