Android日记之2011\12\26

做过项目的童鞋们应该会遇到过这样的情况,我有的参数实在类A中获得的,但是我在类B需要这个参数来做一些事情。一般来说有一个做法是设定全局变量,通过调用全局变量来获得该参数,这也是我在学习的过程中学到的方法。
但是,这种全局变量往往会带来一个问题就是当我这个数据不需要使用时,或者说是我这个数据需要重新获得值的时候,往往会获得以前的值或者就是值没清楚干净。这样就会给程序带来问题。
好在我近期看到一个例子,用接口来传参,感觉很神奇,当时做了些的笔记。但是今天自己用的时候发现又有些遗忘了,所以现在拿出来记录一笔。
大致的过程是这样的,我有一个Activity类,一个普通类来控制一个Dialog,还有一个接口,有Activity类控制显示Dialog,再由Dialog来控制Activity退出。
话不多说,上代码:
接口:
public interface MyInterface {
void CloseActivity(boolean isClose);
}
Activity类,显示Dialog:
public class InterfaceDemoActivity extends Activity{
/** Called when the activity is first created. */
private Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
MyDialog md = new MyDialog(InterfaceDemoActivity.this, mi);
md.ShowDialog();
}
});
}

MyInterface mi = new MyInterface() {

public void CloseActivity(boolean isClose) {
// TODO Auto-generated method stub
if(isClose){
InterfaceDemoActivity.this.finish();
}
}
};
}
普通类,控制Dialog:
public class MyDialog {

private Context mContext;
private AlertDialog alert;
private MyInterface mMI;

public MyDialog(Context context,MyInterface mi){
this.mContext = context;
this.mMI = mi;

CreatDialog();
}

private void CreatDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this.mContext);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyDialog.this.mMI.CloseActivity(true);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
alert = builder.create();
}

public void ShowDialog(){
alert.show();
}
}

其实,看过Android的Dialog的文档的童鞋可以发现我的普通类里面完全用的就是文档中Dialog的例子,可以直接在Activity类中用,那为什么我这边还要多此一举呢?原因是面向对象中,类的单一原则,一个类只干一件事。我既然在Activity类中控制了Dialog的显示,那我索性就新建一个类来控制Dialog的操作。但是我的普通类没法直接控制Activity类的关闭,那我就索性用接口来给Activity类传个boolean值,告诉它你可以关闭了。当然,接口的传值还可以用在别的方面,这就要自己在实际的操作中去摸索了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值