首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在android中动态声明n个数的EditTexts?

如何在android中动态声明n个数的EditTexts?
EN

Stack Overflow用户
提问于 2013-02-01 14:47:27
回答 2查看 1.1K关注 0票数 1

我的应用程序中有一个包含fieldname、fieldtype列的SQLite数据库。fieldname由EditText名称组成etc ...ex: etsearch,etsave,etcancel等。字段类型为EditText。

我动态添加fieldname值。我需要在java类中声明这些EditTexts,因为我正在使用java代码创建布局。

我创建了一个数组列表,并将fieldname值添加到其中。我对如何使用for循环声明EditTexts感到困惑。

我的代码:

代码语言:javascript
运行
复制
public class MainActivity extends Activity 
{
LinearLayout ll;
LinearLayout llgrower;
Cursor cursor;
ArrayList<String> edittexts;


@Override
protected void onCreate(Bundle savedInstanceState) 
{

    super.onCreate(savedInstanceState);
    ll = new LinearLayout(this);
    llgrower= new LinearLayout(this);

    ll.addView(llgrower);
    this.setContentView(ll);

    cursor = DataBase.getdata("query to get fieldname,fieldtype");

    try 
    {
        if (cursor.moveToFirst())
        {
            do
            {
                edittexts.add(cursor.getString(0));

            } while (cursor.moveToNext());
        }

    } 
    catch (Exception e) {}

    for (int i=0;i<edittexts.size();i++)
    {

    }

}

}

EN

回答 2

Stack Overflow用户

发布于 2013-02-01 14:53:30

这里是如何做到这一点的基础。

代码语言:javascript
运行
复制
LinearLayout layout = (LinearLayout) findViewById(R.id.layout); // this is whatever view you want to add them to
EditText editText;

for(int i=0;i<nunberOfEditTexts;i++){

    editText = new EditText(this);

    ...

    // set the properties of the EditText

    ...

    // add to the view
    layout.addView(editText);


}

您可能希望查看LayoutParams以了解如何调整EditTexts的大小和定位。

祝好运

票数 2
EN

Stack Overflow用户

发布于 2013-02-01 14:56:12

代码语言:javascript
运行
复制
 private void addEditText(int count) {
    int id = 999;

    EditText et;        
    RelativeLayout.LayoutParams params;             

    for(int i=0; i<count; i++) {
        et= new EditText(this);
        et.setId(id);

        params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 10, 0, 0);
        params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);

        if(i > 0) {
            params.addRule(RelativeLayout.BELOW, id - i);
        }
        //ASSIGN VALUE FOR YOUR EDITTEXT FROM db HERE.
        layoutSpinnerContainer.addView(spinner, params);

        id++;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14641119

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档