有什么方法可以优化多个按钮及其 onClick 方法吗?

Is there any way we can optimize multiple buttons and their onClick methods?

我有一个带有 56 个按钮的 8 X 7 表格布局。根据点击按钮的索引,分数会增加。我已经用 56 个 onClick 方法编写了代码。

XML布局

<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:onClick="btn1Click"  />


<Button
    android:id="@+id/button2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:onClick="btn2Click"  /> 
.
.
.

<Button
    android:id="@+id/button56"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:onClick="btn56Click"  />

Java代码:

Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
.
.
Button button56 = (Button) findViewById(R.id.button56);

public void btn1Click(android.view.View view) {
   //do Something
}

public void btn2Click(android.view.View view) {
   //sameLines of Code as btn1Click with index = 2;
}
.
.
public void btn56Click(android.view.View view) {
   //sameLines of Code as btn1Click with index = 3;
}

有什么办法可以优化代码,让代码更容易维护,不用再为其他布局写64个onClick方法!!

您可以在 activity 上实现 onClickListener。

例如:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button1 = (Button) findViewById(R.id.button1);
        Button button2 = (Button) findViewById(R.id.button2);
                    .
                    .
        Button button56 = (Button) findViewById(R.id.button56);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);      
                    .
                    .
        button56.setOnClickListener(this);
    }

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

我认为在您的代码中执行此操作会更好。

final List<Button> mButtons = new ArrayList<>();


void onCreate(){

    for ( int i = 0 ; i< BUTTON_COUNT; i++){

         final Button btn = new Button(mContext);
         btn.setOnClickListener(new OnClickListener(){

              void onClick(View view){
                   int position = mButtons.indexOf(btn); 
                   //since you know the button position, do whatever you want with it.
              }

         });
      }

}

最好你可以使用 recyclerview。

很容易获取按钮位置,易于增加或减少浏览量

参考

http://www.androidhive.info/2016/01/android-working-with-recycler-view/