如何在100个按钮中处理onClick()?

4 java refactoring android

我有100个按钮的布局和OnClick()所有方法.

如果我使用switch我需要case R.id.button1, ..., case R.id.button100为所有100个按钮做.如何缩短此代码?

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;
    }
 }
Run Code Online (Sandbox Code Playgroud)

mor*_*ano 5

如果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);
}
Run Code Online (Sandbox Code Playgroud)

EDITED

如果您的URL不直接依赖于ID,请尝试使用URLS映射按钮ID,如下所示:

Map<Integer, String> urls = new HashMap();

urls.put(R.id.button1, "file:///android_asset/chapter/chapter100.html");
// ... 1 to 100 ...
Run Code Online (Sandbox Code Playgroud)

并修改上面的代码,如下所示:

public void webClick(View v) 
{
    Intent intent = new Intent(this, Webview.class);
    intent.putExtra("weblink", urls.get(v.getId()));
    startActivity(intent);
}
Run Code Online (Sandbox Code Playgroud)

编辑#2

如果在你的按钮的标签中你已经有了URL,那么sugestion(不是我的,但由@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);
}
Run Code Online (Sandbox Code Playgroud)