Context的作用:用来访问全局信息的接口,通过Context进行资源的访问。
1、Context获取字符串资源:
public class MainActivity extends AppCompatActivity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
// tv.setText("Hello Android!");
// public final void setText(CharSequence text) { setText(text, mBufferType); }
tv.setText(R.string.hello_android); //strings.xml
//public final void setText(@StringRes int resid) { setText(getContext().getResources().getText(resid)); }
setContentView(tv);
System.out.println(getResources().getText(R.string.hello_android));
}
}
2、Context获取图标资源:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView iv = new ImageView(this);
iv.setImageResource(R.mipmap.ic_launcher);
setContentView(iv);
}
}