Android以编程方式添加textview

Lpc*_*ark -2 xml android dynamic textview android-scrollview

所以从调试和评论出来的事情我得出结论,这个程序的问题是在addTextView()方法中.我完全不知道问题出在哪里.我的猜测是在我尝试添加到TextView的布局中.非常感谢你提前帮助.

public class Books extends Activity{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.books);
        addTextView("Hello World");
    }


    public void addTextView(String text)
    {
        ScrollView viewport = (ScrollView)findViewById(R.id.books);
        TextView textview= (TextView)new TextView(this);
        textview.setText(text);
        //textview.setLayoutParams(new ScrollView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        viewport.addView(textview, new ScrollView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    }

    public void addButton(String text)
    {
        ScrollView scrollview = (ScrollView)findViewById(R.id.books);
        Button btnTag = (Button)new Button(Books.this);
        btnTag.setLayoutParams(new ScrollView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        btnTag.setText(text);
        scrollview.addView(btnTag);
    }

}
Run Code Online (Sandbox Code Playgroud)

ata*_*ulm 7

ScrollViews只能有一个子节点,通常是LinearLayout.当你打电话给scrollview.addView(blah blah)你时,你会向ScrollView添加更多的孩子,这是不允许的.

有关ScrollView的文档,请参见此处.

-

另外,在StackOverflow上发布有关您遇到的错误的问题时,请说明:

  • 您遇到的错误(在Android中,这将在LogCat视图中找到)
  • 你的预期结果(你想做什么)
  • 相关代码(在这种情况下,你应该包括你的布局XML文件 - 而ScrollView错误肯定你会得到的错误之一,它可能不是第一个需要修复的,以便继续前进).

它会帮助每个人,包括未来偶然发现这个问题的人.