如何在Android / Java中以不同的方式传递参数?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何在Android / Java中以不同的方式传递参数?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2414字,纯文字阅读大概需要4分钟。
内容图文
![如何在Android / Java中以不同的方式传递参数?](/upload/InfoBanner/zyjiaocheng/723/7463a28441b94714b8ad2aa44bdc6f07.jpg)
我正在构建一个Android应用程序,其中我实现了一个名为onCheckedChanged的Activity的超类型方法(CompoundButton buttonView,boolean isChecked),如下所示:
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
LinearLayout view = (LinearLayout) findViewById(R.id.some_view);
Animation anim = expand(view, true);
view.startAnimation(anim);
}
else {
LinearLayout view = (LinearLayout) findViewById(R.id.some_view);
Animation anim = expand(view, false);
view.startAnimation(anim);
}
}
然后将此方法设置为在onCreate方法中侦听Switch,如下所示:
mySwitch = (Switch) findViewById(R.id.my_switch);
mySwitch.setOnCheckedChangeListener(this);
现在的问题是,我不仅要为some_view实现此方法,还要为其他几个视图实现此方法.由于我不想复制/粘贴此方法几次,只需更改some_view,我需要一些传递视图的方法.因为我重写了这个方法,所以我不能简单地在方法中添加一个参数.因为我为这个方法设置了一个监听器,所以我也不能在调用这个方法之前将id设置为全局变量.
所以我的问题是:如何将id传递给此方法,以便我不需要复制/粘贴方法以将其重用于多个视图?
解决方法:
实现您自己的OnCheckedChangeListener以及满足您需求的两个选项之一:
>使用此侦听器的多个实例.每对< Switcher,LinearLayout>对应一个.
>在切换一个Switcher实例时,使用包含LinearLayouts数组的此侦听器的一个实例来为所有这些实例设置动画.
这是两个选项的代码.
public class MyOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
private final View[] mViews;
public MyOnCheckedChangeListener(View... views) {
mViews = views
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
for (View v : mViews) {
LinearLayout layout = (LinearLayout) v;
if (isChecked) {
Animation anim = expand(layout, true);
layout.startAnimation(anim);
} else {
Animation anim = expand(layout, false);
layout.startAnimation(anim);
}
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// inflate layout
// option 1
mySwitch = (Switch) findViewById(R.id.my_switch);
mySwitch.setOnCheckedChangeListener(
new MyOnCheckedChangeListener(findViewById(R.id.some_view)));
myOtherSwitch = (Switch) findViewById(R.id.my_other_switch);
myOtherSwitch.setOnCheckedChangeListener(
new MyOnCheckedChangeListener(findViewById(R.id.some_other_view)));
// option 2
mySwitch = (Switch) findViewById(R.id.my_switch);
mySwitch.setOnCheckedChangeListener(
new MyOnCheckedChangeListener(new View[]{
findViewById(R.id.some_view),
findViewById(R.id.some_other_view)
}));
}
内容总结
以上是互联网集市为您收集整理的如何在Android / Java中以不同的方式传递参数?全部内容,希望文章能够帮你解决如何在Android / Java中以不同的方式传递参数?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。