在java源文件中指定TextView文本显示内容

在Java源文件中为TextView指定文本内容,首先需要在布局文件中为TextView赋予ID,然后通过 findViewById() 方法获取该控件对象,再调用 setText() 函数设置文本。

在java源文件中指定TextView文本显示内容

在java源文件当中指定控件的文本显示内容,我们需要得到一个控件的对象即TextView的对象,如果在java源文件中我们想要得到这个指定的控件,我们就需要,为当前的布局文件中的控件添加ID;才使得我们的控件对象可以在java源文件中找到。

核心代码:

Java源文件代码:

package com.example.first;


import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;




public class MainActivity extends Activity {
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=(TextView)this.findViewById(R.id.main_hello);
text.setText(R.string.hello_world);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}


}


布局文件代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >


    <TextView
        android:id="@+id/main_hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="好吗?"
        />
    


</RelativeLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值