我有一个带有56个按钮的8 X 7 Tablelayout。根据点击按钮的索引,分数会增加。我用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方法!!
答案 0 :(得分:1)
我认为在代码中执行此操作应该会更好。
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.
}
});
}
}
答案 1 :(得分:0)
您可以在活动上实现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;
}
}
}
答案 2 :(得分:0)
最好能使用recyclerview。
它很容易获得按钮位置,并且容易增加或减少视图
参考
http://www.androidhive.info/2016/01/android-working-with-recycler-view/