繁体   English   中英

在Android中以编程方式设置textview

[英]Programmatically set a textview in Android

我目前有:

final TextView tv = new TextView(this); 
final RelativeLayout rL = new RelativeLayout(this);
final EditText editText = (EditText)findViewById(R.id.editText);   
final Button b1 = (Button)findViewById(R.id.b1);    

 b1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            rL.addView(tv);
            tv.setText(editText.getText());
            editText.setText("");

        }
    });

在我的onCreate方法中,但是当输入文本并按下我的按钮时,textView不会显示在屏幕上吗? 是否有代码可以设置手机屏幕上的设置位置?

这是你的问题

final RelativeLayout rL = new RelativeLayout(this);

包含TextView的RelativeLayout甚至不会显示在屏幕上,您要做的只是创建一个RelativeLayout。

相反,您应该做的是将RelativeLayout添加到XML布局文件中(相同的文件包含EditText和Button,然后执行以下操作

final RelativeLayout rL = (RelativeLayout)findViewById(R.id.myRelativeLayout);
...
rL.addView(tv);

现在,由于您引用的是实际的RelativeLayout,因此您的文本将可见。 希望我有一定的道理。

您有基本布局吗? 您正在将EditText添加到RelativeLayout,但是您需要将RelativeLayout添加到一些已经存在的布局中。

首先,增加一些基本布局。 然后在该布局上执行findViewById。 用它来调用addView(editText);

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/base_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
</RelativeLayout>



public class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout);

        RelativeLayout rl = (RelativeLayout)findViewById(R.layout.base_layout);
        rl.addView(yourTextView);

    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM