【发布时间】:2013-08-05 10:49:51
【问题描述】:
我在布局中有 100 个按钮和所有这些按钮的 OnClick() 方法。
如果我使用switch,我需要为所有 100 个按钮使用case R.id.button1, ..., case R.id.button100。如何缩短这段代码?
public void webClick(View v)
{
switch(v.getId())
{
case R.id.button1:
Intent intent = new Intent(this, Webview.class);
intent.putExtra("weblink","file:///android_asset/chapter/chapter1.html");
startActivity(intent);
break;
case R.id.button2:
Intent intent2 = new Intent(this, Webview.class);
intent2.putExtra("weblink","file:///android_asset/chapter/chapter2.html");
startActivity(intent2);
break;
// ...
case R.id.button100:
Intent intent100 = new Intent(this, Webview.class);
intent100.putExtra("weblink","file:///android_asset/chapter/chapter100.html");
startActivity(intent100);
break;
}
}
【问题讨论】:
-
使用索引选择按钮数组元素,改变字符串(章节[x])并选择意图数组。或者创建一个包含其中每一个的类并创建该类的数组。
-
为什么选择章节需要 100 个按钮?
-
@pad 我有 100 个章节,所以我需要 100 个按钮
-
为什么没有一键换章的文本框?
-
一句话——
Listview。一百个按钮是可用性的噩梦。
标签: java android refactoring