我在layout和OnClick()方法中有100个按钮。
如果我使用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;
}
}发布于 2013-08-05 18:55:57
如果URL直接依赖于ID,那么尝试这样做:
public void webClick(View v)
{
Intent intent = new Intent(this, Webview.class);
intent.putExtra("weblink","file:///android_asset/chapter/chapter" + v.getId() + ".html");
startActivity(intent);
}编辑过的
在URL不直接依赖于ID的情况下,请尝试将按钮ID映射到URL,如下所示:
Map<Integer, String> urls = new HashMap();
urls.put(R.id.button1, "file:///android_asset/chapter/chapter100.html");
// ... 1 to 100 ...修改上面的代码如下:
public void webClick(View v)
{
Intent intent = new Intent(this, Webview.class);
intent.putExtra("weblink", urls.get(v.getId()));
startActivity(intent);
}编辑#2
如果您的按钮标签中已经有URL,建议(不是我的,而是@pad提出的)使用它来计算URL:
public void webClick(View v)
{
Intent intent = new Intent(this, Webview.class);
intent.putExtra("weblink", "file:///android_asset/chapter/chapter" + v.getText().replaceAll("Chapter ","") + ".html"); // Assuming your text is like "Chapter 50"
startActivity(intent);
}发布于 2013-08-05 19:00:44
对于更多的按钮,在循环中动态创建按钮,并分配onclick事件,如..
在xml文件中创建一个LinearLayout。
现在在该LinearLayout中添加所有按钮,如..
String[] urls={url1,url2.....url100}; // here write your all URLs
Button button[]= new Button[100];
LinearLayout mainlinear=(LinearLayout) findViewById(R.id.main_layer);
for (int i = 0; i < 100; i++) {
button[i] = new Button(this);
button[i].setText(i);
button[i].setTag(i+":"+URL); // URL = What you need to pass when button is click
button[i].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TextView selected = (TextView) v;
String tag = selected.getTag().toString();
//Here you need to write your code when button is pressed.
Intent intent = new Intent(this, Webview.class);
intent2.putExtra("weblink",urls[i]);
startActivity(intent2);
}
}
mainlinear.addView(button[i]);发布于 2013-08-05 19:01:57
我认为这应该是可行的:
public void webClick(View v)
{
String stringID = String.valueOf(v.getId());
String[] temp = stringID.split("utton");
stringID = "file:///android_asset/chapter/chapter" +temp[1]+ ".html"
Intent intent = new Intent(this, Webview.class);
intent.putExtra("weblink",stringID);
startActivity(intent);
}https://stackoverflow.com/questions/18056367
复制相似问题