Android移动开发之【Android实战项目】通过Java代码设置TextView

在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>

发布了665 篇原创文章 · 获赞 194 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/weixin_43838785/article/details/104498209