• Android Context作用


    Context 用于访问全局信息的接口

        App的资源: strings, drawable资源等等

    工程代码:LearnContext.zip

    --------------------------------------------------------

    下面来看一个用Context来范围资源的粒子

    public class MainActivity extends Activity {
    
        String TAG = "CARLOZ";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            
            //Activity 本身就是一个 Context
            TextView tv = new TextView(MainActivity.this);
            tv.setText("hello carloz");
            tv.setText(R.string.hello_world);
            setContentView(tv);
            
            String str = (String) getApplicationContext().getResources().getText(R.string.hello_world);
            Log.d(TAG, str);
            // 输出 08-16 11:59:27.402: D/CARLOZ(13255): Hello world!
    
            ImageView iv = new ImageView(MainActivity.this);
            iv.setImageResource(R.drawable.ic_launcher);
            setContentView(iv);
        }
    }

        由上代码可以看出新建一个TextView或者ImageView至少要 一个参数 Context,Activity本身就是一个Context,所以可以复制。

        tv.setText(R.string.hello_world); 传入一个string id, 而setText API内部的代码是 getContext().getResources().getText(resid);  可以看到,获取资源需要用到Context。

       

  • 相关阅读:
    Run Shell Commands in Python
    Install Fabric 1.8.3 Manually on Ubuntu 12.04
    Setup a Simple HTTP Proxy Server
    去掉文件中的^M
    Build Web Server with Apache and Passenger
    Delete Trailing Spaces with Vim
    Specify Default JDK on Ubuntu
    总结
    问题
    HTTPS 和 HTTP
  • 原文地址:https://www.cnblogs.com/carlo/p/4734042.html
Copyright © 2020-2023  润新知