当前位置:操作系统 > 安卓/Android >>

Android程序ToDoList增加配置项页面

 
 
本文要做的事情就是在前面做的简单的ToDoList程序上增加一个配置项页面(Reference)。这个Reference页面也非常简单:

 

Image Image(1)

这个ToDoList现在有两个页面,主页面能填写待办事项,然后manu键弹出可以跳转到Reference页面,在Reference页面只有一个checkbox,来给用户确认是否要本地保存(具体的本地存储的功能没有具体实现),Reference页面还有两个按钮,保存和返回。点击保存按钮,程序会存储用户是否已经选定了本地保存,点击返回按钮,页面会跳转到ToDoList页面。

在这个程序中主要是有几个地方需要处理

1 如何在两个Activity中进行切换
这是两个页面,所以我们首先会想到需要两个layout文件,于是我们创建了一个res/layout/preferences.xml,在这个layout中定义好了一个checkbox和两个按钮。现在的问题是当我点击main.xml中的manu按钮的时候,它是会触发onOptionsItemSelected事件的,所以我们需要在这个事件中触发reference页面。这个如何做呢?

大致是有两种方法:

1 在ToDoListActivity中调用setContentView来触发preferences.xml的展现。

2 重新创建一个Activity类Reference,ToDoListActivity中使用Intent触发Reference的启动,绘制等功能。

这两种方法有什么不同呢?

第一种方法相当于html中使用js来让不同的div的意思。它的好处就是简单,对于简单的逻辑和页面完全可以这么做。它的缺点也显而易见,等于是一个Activity控制多个layout,那么在代码层面,会是所有的逻辑都存放在一个类中,对于代码的易用性和维护性都是很大的损失。对于我们这个应用,我们选择第二种方法。

所以我们的onOptionsItemSelected事件代码如下:

  public boolean onOptionsItemSelected(MenuItem item) {
 switch (item.getItemId()) {
 case R.id.manu_reference:
       Intent intent = new Intent();
       intent.setClass( this, Reference. class);
       startActivity(intent);
 }
 return true;
}
当我在manu中触发的item是manu_reference(这个已经在配置中设置了id),那么我就启动我需要的Activity。

2 Intent和Activity
Android应用程序的三种核心的组件:Activity,Service, Brocast Receiver。这三种组件互相或者内部进行交互的消息就叫做Intent。比如在我们这个程序中,就是两个Activity需要进行交互,这个时候就需要使用到了Intent了。

Intent有三种用法:

传递给Activity:startActivity(Intent), startActivityForResult()

传递给Service:startService(Intent), bindService()

传递给Broadcast:sendBroadcast(), sendOrderedBroadcast(), sendStickyBroadcast()

在这个例子中,除了从ToDoListActivity跳到Reference,也有从Reference跳到ToDoListActivity(点击返回按钮)。

  Button cancelReference = (Button)findViewById(R.id. cancel);
           cancelReference.setOnClickListener( new View.OnClickListener() {
                 
                 @Override
                 public void onClick(View v) {
                     Intent intent = new Intent();
                 intent.setClass(Reference.this, ToDoListActivity.class);
                startActivity( intent);
                }
           });
3 配置项存储
关于配置项存储这里使用的是SharePreferences。SharePreferences提供了一个接口让你能存储和获取持久化的key-value数据。你可以持久化的数据类型有:boolean,float,int,long,string。

简单来说:

创建对象使用方法:
getSharePreferences()

getPreferences()

写数据使用方法:
1 使用edit()获取写句柄

2 调用putXXXX()方法

3 调用commit

读数据使用方法:
getXXX()

在这个例子中有这样用到:

  final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            boolean isSaveLocal = prefs.getBoolean( IS_SAVE_LOCAL, false);
 
...
 
Editor editor = prefs.edit();
                     editor.putBoolean( IS_SAVE_LOCAL, isChecked);
                     editor.commit();

补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,