【问题标题】:How to manage OnClickListener on multiples buttons automatically created如何在自动创建的多个按钮上管理 OnClickListener
【发布时间】:2015-05-26 10:30:08
【问题描述】:

我有很多以编程方式创建的按钮,每个按钮对应一个特定的操作,我需要能够根据单击的按钮来识别和检索用户输入。界面如下:

我有 70 件类似的物品。

我读过

Dynamically creating Buttons and setting onClickListener

Implementing OnClickListener for dynamically created buttons in Android

但我不知道什么是正确的方法。例如,如果用户点击ButtonText is now set...,我必须能够检索到EditText 的值,并且知道这个分钟数对应与Andar carrito compra

tag 分配给Button 是否正确,以便识别屏幕上的索引,然后在视图层次结构中向上检索EditText 值?

这是我目前的代码:

for (int i = 1; i < types.length; i++) {

        //  ... more views created
        // ...... 

        Button enterBt2 = new Button(this);
        // Set layout params and stuff for the button
        enterBt2.setTag(i);
        enterBt2.setOnClickListener(getOnClickDoSomething(enterBt2));
        // ....
}

还有OnClickListener

View.OnClickListener getOnClickDoSomething(final Button button)  {
    return new View.OnClickListener() {
        public void onClick(View v) {
            Log.e(TAG, "O " + ExerciseRecord.TYPE.values()[((int) button.getTag())]);
            // Obtain the value of the EditText with
            LinearLayout ll = (LinearLayout) button.getParent();
            ll.getChildAt(0); //The EditText
        }
    };
}

这是最好的方法吗?

【问题讨论】:

    标签: java android android-layout onclicklistener


    【解决方案1】:

    为按钮分配标签是正确的,以便识别 屏幕上的索引,然后在视图层次结构中向上, 检索 EditText 值?

    这是一个选项。或者你可以有一个实现接口的类,添加一个以字符串为参数的构造函数。例如。

    public class MyOnClickListener implements View.OnClickListener {
        final String mValue;
        public MyOnClickListener(String value) {
               mValue = value;
        }
    
         public void onClick(View v) {
            Log.e(TAG, "O " + mValue);
            // Obtain the value of the EditText with button.getParent()....
         }
    }
    

    【讨论】:

      【解决方案2】:

      这是一种可能的方法。 视图上的标签本身就是一个对象,因此理论上,您可以将编辑文本作为标签,以便您更轻松地检索它,但您可能会遇到一些内存泄漏问题 - 我自己做了。

      另一种方法,我认为这是一种矫枉过正,是创建一个 Button 的子类并添加您需要的任何信息。

      【讨论】:

        【解决方案3】:

        您应该创建一个组件来管理标题、编辑文本和按钮的行为。

        希望此链接对您有所帮助: http://mobile.cs.fsu.edu/creating-a-simple-compound-component-in-android/

        问候

        【讨论】:

          猜你喜欢
          • 2020-06-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-11-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-02
          相关资源
          最近更新 更多