2012-11-19 214 views
9

我试图从代码中更改我的TextView文本。更改TextView文本

这是我的XML是什么样子:

XML: 
<TextView 
    android:id="@+id/textView1" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:gravity="center_vertical|center_horizontal" /> 

,代码:

TextView tv1 = (TextView)findViewById(R.id.textView1); 
tv1.setText("Hello"); 
setContentView(tv1); 

我我的设备上得到一个错误,并且应用程序停止。 我试图显示一个TextView(未连接到XML TextView),它工作。

+0

显示乌尔logcat的什么... –

+2

TextView中不能设置为你的父视图。你必须用一个LinearLayout来包围TextView。 – SamSPICA

+0

^正确 向我们展示您的oncreate方法,您的xml文件的名称是什么? – Hades

回答

36

你的做法是不正确。我认为这将是空指针异常。更好地发布日志猫

正确这里

setContentView(R.layout.yourlayout): 

在此行应指定要使用的布局。

然后

TextView tv1 = (TextView)findViewById(R.id.textView1); 
tv1.setText("Hello"); 

Study here正是你想知道

+0

谢谢大家回答如此之快。 Abhi感谢它现在正在工作。 –

+0

@ImriPersiado然后您可以接受答案,只需在答案左侧打勾标记:P – Abhi

+0

我是新来的,感谢您告诉我:D完成。 –

4

删除这个.. setContentView(tv1);