【问题标题】:how to handle a collection of similar buttons and methods如何处理类似按钮和方法的集合
【发布时间】:2015-11-08 08:53:49
【问题描述】:

我正在尝试在 Android Studio 中开发一个在 Eclipse 中运行良好的程序。但是按钮、侦听器和方法的新颖复杂性阻碍了我:我有一个类似按钮的集合,具有类似的操作。它们仅在索引值上有所不同。我试图创建一个名为 bouton 的对象类,扩展按钮并拥有一个带有参数 j 的实例方法。但它不起作用。到目前为止,有效的是为每个按钮重复代码,如下所示,有两个按钮。代码已部分准备好用于 for 循环,但我的尝试无济于事。

package com....;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    // public static Button boutons[];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        actionBouton1();
        actionBouton2();
    }


    private void actionBouton1() {
        String buttonID = "bouton" + 1;
        int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
        final Button btnGenerique = (Button) findViewById(resID);
        final TextView monMessage = (TextView) findViewById(R.id.affichage);
        View.OnClickListener monEcouteur = new View.OnClickListener(){
            @Override
            public void onClick(View v){
                monMessage.setText("you clicked button "+1);
            }
        };
        btnGenerique.setOnClickListener(monEcouteur);
    }


    private void actionBouton2() {
        String buttonID = "bouton" + 2;
        int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
        final Button btnGenerique = (Button) findViewById(resID);
        final TextView monMessage = (TextView) findViewById(R.id.affichage);
        View.OnClickListener monEcouteur = new View.OnClickListener(){
            @Override
            public void onClick(View v){
                monMessage.setText("you clicked button "+2);
            }
        };
        btnGenerique.setOnClickListener(monEcouteur);
    }

}// fin class MainActivity



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="btn 1"
        android:id="@+id/bouton1"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="100dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="btn 2"
        android:id="@+id/bouton2"
        android:layout_alignTop="@+id/bouton1"
        android:layout_toRightOf="@+id/bouton1"
        android:layout_toEndOf="@+id/bouton1"
        android:singleLine="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/affichage"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="200dp" />

</RelativeLayout>

【问题讨论】:

  • 所以要动态添加按钮?
  • 我不明白你在做什么。你能澄清一下吗?
  • 嗨。我现在不确定为什么要获得 res ID 的所有负担: int resID = getResources().getIdentifier(buttonID, "id", getPackageName());您可以通过执行 (Button)findViewById(R.id.buttonId); 来获取代码上的按钮实例
  • 我想创建一个类似按钮的集合(可能是一个arrayList)。回答 MarkSkayff :我准备了一个未来的 for 循环,这就是我开始使用 int resID = 等的原因。

标签: android button for-loop methods


【解决方案1】:

向多个按钮添加事件有几个最佳实践。

首先,我想评论一下,您不需要在 Activity 中为每个单独的按钮和按钮事件创建特定的方法。您可以只创建一个名为 buttonEvents 或其他方法的方法,然后在其中附加所有事件。

第一种建议方法

只需一次附加并定义所有事件:

Button button = (Button)findViewById(R.id.buttonId)
button.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
             // Perform action on click
         }
     });

所以基本上这些是每个按钮和事件附加的“两行”代码。

第二种建议方法

您可以像这样在 Activity 类上实现 OnClickListener 并 @Override onClick 方法:

public class SomeClassOfMine extends Activity implements OnClickListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 //... some other code here to init the layout
    Button btn1 = (Button)findViewById(R.id.button1);
    Button btn2 = (Button)findViewById(R.id.button2);
    btn1.setOnClickListener(this);
    btn2.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch(v.getId()){
        case R.id.button1:
            break;
        case R.id.button2:
            break;
    }

最后一个问题在于 onClick 方法。您在执行 v.getId() 的开关中看到。该方法为您提供非常具体的按钮资源 ID。所以在 switch 中你可以区分几个按钮事件。

拥有一个Button的ArrayList

如果你有一个按钮的 ArrayList,你可以像这样使用 Java foreach 而不是 for:

// Say you have this below initialized somewhere ...
ArrayList<Button> myButtons; 

// The foreach or for..in construction
for (Button but : myButtons){
   but.setOnClickListener(new View.OnClickListener(){
       //@Override
       public void onClck(View v){
         // Do something for this button
       }
});

【讨论】:

  • 非常感谢!这看起来很棒。由于我是 Android Studio(以及 Java)的新手,它会让我忙一两天。
  • 好的,我添加了一个 ArrayList
  • 我很喜欢你的 cmets。他们很有启发性和帮助。我确实为他们投票,但目前我还没有足够的信誉来投票。谢谢
  • 啊,好的,安迪,没问题。是的,我知道投票的信用限制。
猜你喜欢
  • 2021-08-08
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-22
相关资源
最近更新 更多