访问全局资源的时候,必须要传递Context对象;全局资源代表:res文件夹下的内容;
TextView textView = new TextView(this);
textView.setText(R.string.app_name);
内部的原理是: 通过上下文获取一个资源对象Resources,此对象表示res文件夹下所有的资源。
@android.view.RemotableViewMethod
public final void setText(@StringRes int resid) {
setText(getContext().getResources().getText(resid));
}
//传递一个资源id,它就能返回对应的资源;资源对象
Resources resources = this.getResources();
//除了获取字符串资源外,还可以获取任意类型的资源!
ImageView iv = new ImageView(this);
iv.setImageResource(R.mipmap.ic_launcher);
多个组件之间实现数据的共享!
即如何管理去全局变量? 在BaseApplication里面管理全局共享的数据! 给全局变量赋值,然后直接获取值使用。
public class BaseApplication extends Application {
private static BaseApplication mBaseApplication;
private String appName;
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
findViewById(R.id.btn6).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//相当于给全局变量赋值
((BaseApplication) getApplicationContext()).setAppName("111");
//获取后可以直接使用
String appName = ((BaseApplication) getApplicationContext()).getAppName();
}
});