獲取TextView對象
通過findViewById(控件id)方法
此方法返回一個View對象,需要強制類型轉換
View類是所有UI類控件的基類
語法:
public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceStete) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv_show = (TextView) findViewById (R.id.tv_show);
}
}
//獲取TextView對象
TextView tv_show = (TextView) findViewById (R.id.tv_show);
等同於 TextView tv_show = (TextView) this.findViewById (R.id.tv_show);
//獲取文本內容
string text = tv_show.getText().toString();
//輸出內容
Log.i("wxy",text);
第一個參數"wxy"可以爲任意字符串。
//吐司(toast)輸出
Toast.makeText(this,text,Toast.LENGTH_SHORT).show();
toast.makeText爲對象,後續一定要加.show()方法。
//設置文本新內容
tv_show.setText("你好!");
setText的參數爲字符串,可以採用硬字符串,也可以採用資源引用的方法。
資源引用方法如下:
tv_show.setText(getResources().getString(R.string.app_name));
tv_show.setTextColor(getResources().getColor(R.color.blue));
總結:
使用TextView顯示文本信息
在resources標籤下可以定義常量標籤
通過findViewById()方法獲取控件對象,此方法返回的是一個View對象,需要強制類型轉換
獲取某個控件對象之前,一定要引用相應的佈局
動態獲取資源常量值需要獲取Resources對象,Resources對象通過getResources()獲得