Android学习笔记

1.获得全局Context
全局Application

public class MyApplication extends Application {
    private static Context mContext;
    private static MyApplication mApp;
    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
        mApp = this;
    }

    /*** * 获取Context对象 * @return */
    public static Context getContext(){
        return mContext;
    }

    /**** * 获取Application对象 * @return */
    public static MyApplication getApp(){
        return mApp;
    }
}

Activity基类

public class BaseActivity extends AppCompatActivity {
    public Context mContext;
    public BaseActivity(){
        mContext = MyApplication.getContext();
    }
}

使用

public class MainActivity extends BaseActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void click(View view){
        switch (view.getId()){
            case R.id.btn:
                Toast.makeText(mContext, "点击了按钮", Toast.LENGTH_SHORT).show();
                break;
            case R.id.rl_parent:
                Toast.makeText(mContext, "点击了相对布局", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}

你可能感兴趣的:(Android学习笔记)