2013-04-12 36 views
0

我目前有:编程设定一个TextView在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不会在屏幕上显示出来?有没有代码可以设置在手机屏幕上的位置?

+0

您是以编程方式或以XML格式创建'textView'吗?也可以用'public'替换'final'。 – TronicZomB

+0

以编程方式,如我在标题中所述:) –

+1

您添加文本视图的相对布局在屏幕上不可见。您需要使用findViewById()来获取对RelativeLayout的引用,就像您使用button和EditText一样,而不是使用新的RelativeLayout – FoamyGuy

回答

2

这是你的问题

final RelativeLayout rL = new RelativeLayout(this); 

这RelativeLayout的包含TextView中甚至没有显示在屏幕上,你正在做的是创造一个RelativeLayout的。

你应该做的反而是增加的RelativeLayout到您的XML布局文件(包含的EditText和Button和同一个执行下列操作

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

现在既然你引用一个实际的RelativeLayout,你的文字会可见, 希望我做了某种意义。

1

你有一个基地布局?你添加的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); 

    } 

} 
相关问题