【问题标题】:android: how to create dynamic view elements on Button Clickandroid:如何在Button Click上创建动态视图元素
【发布时间】:2011-10-21 17:26:01
【问题描述】:

这看起来是一个简单的问题,但我 2 天以来一直在苦苦挣扎。 我想在 Button Click 上动态创建一个 textView。 这是代码示例

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game_main);
Button bn = (Button) findViewById(R.id.button2);
bn.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
       TextView tv1 = new TextView(getApplicationContext());
       tv1.setText("Show Up");
       layout.addView(tv1);
        }   
});
}

我可以看到按钮,但是在单击按钮时,我在布局中看不到文本视图。 代码有问题吗?

【问题讨论】:

  • 你能粘贴你初始化layout变量的那部分代码吗?
  • 请发布layout文件

标签: android textview


【解决方案1】:

据我所见,布局没有定义,在布局上尝试 findViewById 然后在其上设置一个子元素,然后它应该可以工作

【讨论】:

  • 最终 LinearLayout 布局 = (LinearLayout) findViewById(R.id.root);
【解决方案2】:

您好,请阅读我的earlier post,它包含示例代码。 (在 UI 中有一个 edittext 和一个按钮,单击按钮后,新的 textview 会显示输入的文本。) 我想这会对你有所帮助。

我用工作代码更新了答案。

仅onCreate()方法中的代码:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dinamic_textview);
    final LinearLayout layout = (LinearLayout) findViewById(R.id.root_layout);
    final Button bn = (Button) findViewById(R.id.btnaddnewtext);
    bn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            TextView tv1 = new TextView(v.getContext());
            tv1.setText("Show Up");
            layout.addView(tv1);
        }
    });
}

布局xml:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:id="@+id/root_layout">
    <Button 
        android:id="@+id/btnaddnewtext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Add"  
    />
</LinearLayout>

【讨论】:

  • 继续我的问题,我只在 OnCreate 方法中有布局初始化代码
  • 您好,我附上了上面的工作示例,逻辑仅在 onCreate 方法中。我只是将 getApplicationContext 更改为 v.getContext() 因为这将返回实际视图。我初始化布局,因为我看不到它在哪里。
【解决方案3】:

从 layout.xml 中获取您希望 TextView 在其中显示的布局。

然后像这样将您的 TextView 添加到该布局中:-

LinearLayout myLayout = (LinearLayout)findViewById(R.id.mLayout);
Button bn = (Button) findViewById(R.id.button2);
bn.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {
       TextView tv1 = new TextView(getApplicationContext());
       tv1.setText("Show Up");
       myLayout .addView(tv1);
        }   
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 2022-11-28
    • 2011-02-12
    • 1970-01-01
    • 2014-12-22
    相关资源
    最近更新 更多