【问题标题】:text not changing in a TextView while doing Layout Inflater执行 Layout Inflater 时 TextView 中的文本未更改
【发布时间】:2013-01-17 23:58:49
【问题描述】:

在我的应用程序中加载活动时,我正在执行以下操作

setContentView(R.layout.main2);
layoutToAdd = (LinearLayout) findViewById(R.id.linearLayout1);

for(i=0; i<num;i++)
{
    LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
    View view = inflater.inflate(R.layout.camera, null);
    layoutToAdd.addView(view);
}

num的值每次都不一样。

在我的 LayoutInflater 布局中,我有一个文本视图、编辑文本和一个按钮。

现在它们根据num 中提到的次数显示,现在每次我想要更改文本和按钮名称。如何设置 TextView 和 Button 的文本。

【问题讨论】:

    标签: android layout-inflater


    【解决方案1】:

    在你膨胀布局后设置它们

    View view = inflater.inflate(R.layout.camera, null);
    TextView tv = view.findViewById(R.id.textviewid); //id defined in camera.xml
    Button b = view.findViewById(R.id.buttonid);      //id defined in camera.xml
    tv.setText();
    b.setText();
    layoutToAdd.addView(view);
    

    【讨论】:

    • 感谢您的回答。你能告诉我如何在布局充气器中找到一个特定的按钮被点击.....
    • 你可以为你的按钮设置Tag() developer.android.com/reference/android/view/…(根据num,例如view.findViewById(R.id.buttonid).setTag(new Integer(num));)当你膨胀它并在OnClickListener中获取这个标签。 public void onClick(View v){Integer buttonNum = v.getTag();}
    • thanx... 我对 Inflater 还有一个疑问。是否可以同时在水平和垂直方向上创建膨胀视图
    • TextView tv = (TextView) view.findViewById(R.id.textviewid);
    【解决方案2】:

    我的建议是,您应该创建一个仅包含 LinearLayout 的 xml 文件。

    然后编程,你应该创建 TextViews、EditTexts 和 Buttons 并将其添加到 LinearLayout。

    您可以设置这些组件的不同属性,如下所示:

    这里是设置TextView的属性的例子。对于其余的组件,你可以设置相同的。

    TextView tv=new TextView(context);
    tv.setBackgroundResource(R.drawable.textview_bg);
    tv.setPadding(20, 5, 40, 5);
    tv.setText("set your text");
    tv.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    tv.setTextColor(Color.RED);
    tv.setClickable(true);
    tv.setId(id);//where id is an integer which should be unique for each TextView
    
    layout.addView(tv); 
    

    您还需要在 for 循环中创建和添加所有这三个组件,根据您用于迭代循环的 i 提供唯一的 id!您可以为 textview 和按钮设置一个字符串数组,以便在 for 循环中设置它们的名称,这对你来说更容易在循环中传递你想要设置的字符串。

    【讨论】:

      【解决方案3】:

      您必须存储膨胀视图的引用并存储在一个列表中,然后当您想要修改时只需 list.get(2).findViewById(R.id.textbox_id)。

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-06
        • 1970-01-01
        • 1970-01-01
        • 2012-05-28
        • 2014-02-07
        • 1970-01-01
        相关资源
        最近更新 更多