这里我写了一些代码来导航到不同的链接,使用android中的不同按钮。无论如何,我的代码比我编码的还要多。如果可能,请帮我减少代码。这里是我的代码:如何减少以下java代码?
Button tv = (Button) findViewById(R.id.my1);
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("link1"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
});
Button tv1 = (Button) findViewById(R.id.my2);
tv1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("link2"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
});
Button tv2 = (Button) findViewById(R.id.my3);
tv2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("link3"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
});
既然你对三个不同的'Button'做了完全相同的事情,为什么不写一个带'Button'参数并且调用它三次的方法呢? – ajb 2015-02-23 06:00:37
对不起,我必须显示3个按钮,他们应该导航到三个不同的链接 – 2015-02-23 06:02:20
然后,你不应该在你的代码示例中放置相同的链接(好吧,感谢编辑它)。无论如何,所有这一切意味着你为你的方法添加另一个参数来传递链接。 – ajb 2015-02-23 06:03:14