【问题标题】:How to handle onClick() in 100 buttons?如何处理 100 个按钮中的 onClick()?
【发布时间】: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


【解决方案1】:

如果 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);
}

已编辑

如果您的网址不直接依赖于 ID,请尝试将按钮 ID 与网址映射,如下所示:

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);
}

【讨论】:

  • 可能需要在 ID 周围进行替换以去除“按钮”
  • id 是自动生成的,因此无法预测
  • 也许您可以使用按钮名称中的整数,但 id 将无法正常工作。 button1.getText()
  • @morgano:如果我使用它,它会导航到 file:///android_asset/chapter/chapter2131230722.html
  • @user2648429 回答得到改善。
【解决方案2】:

如果您需要更多数量的按钮,请在循环中动态创建按钮并分配 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]);

【讨论】:

  • 我对 android 和 java 很陌生。你能告诉我我该怎么做吗?因为我喜欢这种方法
【解决方案3】:

您可能想要使用 ListView。如果您想要按钮,请使用 ListView,它在每个项目的布局中都有一个按钮。

然后,您设置一个 onItemClickListener。您将获得该按钮的位置(第一个的位置为 0,第二个的位置为 1,等等)。然后写一个链接:

String link= "file:///android_asset/chapter/chapter" + (position +1) + ".html";

您的其余代码将是相同的 (intent.putExtra("weblink", link);)

【讨论】:

    【解决方案4】:

    我的建议是在这种情况下使用 ListView 或 GridView 并将文件名保存在 ArrayList 中。然后你做这样的事情:

    List<String> urlList = new ArrayList<String>();
    urlList.add("file:///android_asset/chapter/chapter1.html");
    urlList.add("file:///android_asset/chapter/chapter2.html");
    // and so on
    
    ListView listView = (ListView)findViewById(R.id.listView);
    ArrayAdapter adapter = new ArrayAdapter(this, android.R.id.simple_list_item_1, urlList);
            listView.setOnItemClickListener(new OnItemClickListener() {
    
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
    
                        Intent intent = new Intent(this, Webview.class);
                        intent.putExtra("weblink", urlList.get(position));
                        startActivity(intent);
    
                }
            });
    

    这将是一个很好的实现,因为您可以避免使用 100 个按钮和 OnClickListener 来保存一些资源。

    编辑:这段代码应该正在运行,只需将它放在 onCreate() 中进行一些测试。您所要做的就是在您的 layout.xml 中定义一个 ListView,而不是像这样的 100 个按钮:

    <?xml version="1.0" encoding="utf-8"?>  
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
      android:orientation="vertical"  
      android:layout_width="match_parent"  
      android:layout_height="match_parent">  
    
        <ListView android:layout_width="match_parent"   
          android:layout_height="match_parent"   
          android:id="@+id/listView">  
        </ListView>  
    
    </LinearLayout>
    

    如果您真的想将其与 Buttons 一起使用,请遵循 morgano 的建议。

    【讨论】:

    • @steve_benett:我是 android 和 java 的新手。你能告诉我我该怎么做吗?
    【解决方案5】:

    我认为这应该可行:

    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);
                }
    

    【讨论】:

    • 您可以添加一个 if 语句,以查看 temp[1] 是否在您拥有的按钮数量之间包含一个数字(这里是字符串)。
    • 如果函数名称webClickandroid:onClick="webClick"中所有按钮的布局中,那么我看不出它不应该的原因。
    • 错误:打开跟踪文件,没有这样的文件或目录。但我在目录中有文件。路径正确
    • 我修改了答案,这样试试。这可能是因为我在putExtra() 方法中连接了地址。我把这个放在方法之外,将它附加到一个字符串变量,然后将此变量作为第二个参数传递给方法。尝试在LOG中输出地址,看看是否有问题。
    【解决方案6】:
    public void webClick(View v) 
    {
        Intent intent = new Intent(this, Webview.class);
    
        switch(v.getId())
        {
            case R.id.button1:
                intent.putExtra("weblink","file:///android_asset/chapter/chapter1.html");
                startActivity(intent);
                break;
    
            case R.id.button2:
                intent.putExtra("weblink","file:///android_asset/chapter/chapter2.html");
                startActivity(intent);
                break;
    
            case R.id.button3:
                intent.putExtra("weblink","file:///android_asset/chapter/chapter3.html");
                startActivity(intent);
                break;
    .
    .
    .
    .
    
            case R.id.button100:
                intent.putExtra("weblink","file:///android_asset/chapter/chapter100.html");
                startActivity(intent);
                break;
            default:
                break;
         }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      • 2011-08-30
      • 2017-10-29
      • 1970-01-01
      相关资源
      最近更新 更多