单例模式在android中的应用
项目演示及讲解
创新互联公司主营沿河网站建设的网络公司,主营网站建设方案,重庆APP软件开发,沿河h5重庆小程序开发搭建,沿河网站营销推广欢迎沿河等地区企业咨询
爱奇艺 http://www.iqiyi.com/w_19rtfb03pp.html
土豆 http://www.tudou.com/programs/view/M1R6cIW15DY/
项目下载
http://download.csdn.net/detail/u010134178/9052163
什么是单例模式
百度“java 单例”
以下是通过一个简单的列子来说明它的用户,别看这简单的例子,在公司项目里这可是最基本的呀
1、一个图片池类
public class ImagePool { private static Context mContext; private static Bitmap mBitmap; private static ImagePool mInstance; public ImagePool(Context context) { mContext = context; mBitmap = BitmapFactory.decodeStream(context.getResources() .openRawResource(R.drawable.zheng)); } public static ImagePool getInstance(Context context) { if (null == mInstance) { mInstance = new ImagePool(context); } return mInstance; } public static ImagePool getInstance() { return mInstance; } /** * 外部数据接口 * * @return */ public Bitmap getBitmap() { return mBitmap; } /** * 设置 * * @return */ public void setBitmap(int id) { mBitmap = BitmapFactory.decodeStream(mContext.getResources() .openRawResource(id)); } }
一个Applaction层的全局变量
public class MyApplication extends Application{ @Override public void onCreate() { super.onCreate(); //init ImagePool.getInstance(getApplicationContext()); } }
在业务中的基本用法
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ImageView p_w_picpath = (ImageView) findViewById(R.id.p_w_picpathId); Button change = (Button) findViewById(R.id.changeId); Button start = (Button) findViewById(R.id.startId); Drawable drawable = new BitmapDrawable(ImagePool.getInstance() .getBitmap()); p_w_picpath.setBackgroundDrawable(drawable); change.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ImagePool.getInstance().setBitmap(R.drawable.chuan); Drawable drawable = new BitmapDrawable(ImagePool.getInstance() .getBitmap()); p_w_picpath.setBackgroundDrawable(drawable); } }); start.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, OtherActivity.class); startActivity(intent); } }); } }
好了,其实就这么简单。
网页名称:单例模式在android中的应用
网站路径:http://hbruida.cn/article/jggojp.html