其他




我们知道在Android中通过布局文件来描述软件的界面,而通常在Activity中都是使用setContentView()来将布局显示出来。

但是如果我们在非Activity的情况下,而且需要对布局中的控件进行设置等操作,该如何处理呢?这就需要使用到动态加载布局 LayoutInflater


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


当一个Activity在PAUSE时,被kill之前,它可以调用onSaveInstanceState()来保存当前activity的状态信息。
用来保存状态信息的Bundle会同时传给两个method,即onRestoreInstanceState() and onCreate().



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


singleTask时:


在默认情况下,当您通过Intent启到一个Activity的时候,就算已经存在一个相同的正在运行的Activity,系统都会创建一个新的Activity实例并显示出来。
为了不让Activity实例化多次,我们需要通过在AndroidManifest.xml配置activity的加载方式(launchMode)以实现单任务模式,如下所示:

 

<activity android:label="@string/app_name"
   android:launchmode="singleTask"
   android:name="Activity1"/>

 

launchMode为singleTask的时候,通过Intent启到一个Activity,如果系统已经存在一个实例,系统就会将请求发送到这个实例上,
但这个时候,系统就不会再调用通常情况下我们处理请求数据的onCreate方法,而是调用onNewIntent方法,如下所示:


 protected void onNewIntent(Intent intent) {

   super.onNewIntent(intent);

   setIntent(intent);//must store the new intent unless getIntent() will return the old one

   processExtraData();

 }


不要忘记,系统可能会随时杀掉后台运行的Activity,
如果这一切发生,那么系统就会调用onCreate方法,而不调用onNewIntent方法,
一个好的解决方法就是在onCreate和onNewIntent方法中调用同一个处理数据的方法,如下所示:

 public void onCreate(Bundle savedInstanceState) {

   super.onCreate(savedInstanceState);

   setContentView(R.layout.main);

   processExtraData();

 }

 protected void onNewIntent(Intent intent) {

   super.onNewIntent(intent);

   setIntent(intent);//must store the new intent unless getIntent() will return the old one

   processExtraData()

 }

 private void processExtraData(){

   Intent intent = getIntent();

   //use the data received here

 }



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

//int random = getRandomNum(100000,999999);表示随机生成一个六位数
public int getRandomNum(int min, int max){
    Random random = new Random();
    int tmp = Math.abs(random.nextInt());
    return tmp % (max - min + 1) + min;
}


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


moveTaskToBack

模拟现在的主流应用
最后按Back键时不是强制退出应用或直接结束根Activity,而是采取类Home键效果,此时可以直接通过此函数实现,非常实用。

此方法直接将当前Activity所在的Task移到后台,同时保留activity顺序和状态。

@Override
public void onBackPressed(){   
   moveTaskToBack(true);
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值