Android : Making simple code. dry… here is a solution to the problem.
Android : Making simple code. dry
I am new to Java programming. Can someone here help me keep my code dry?
Button level01 = (Button) findViewById(R.id.level01);
level01.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Prefs.setStagePref(getApplicationContext(), 1);
Intent play = new Intent(LevelActivity.this, PlayActivity.class);
startActivity(play);
}
});
Button level02 = (Button) findViewById(R.id.level02);
level02.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Prefs.setStagePref(getApplicationContext(), 2);
Intent play = new Intent(LevelActivity.this, PlayActivity.class);
startActivity(play);
}
});
Button level03 = (Button) findViewById(R.id.level03);
level03.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Prefs.setStagePref(getApplicationContext(), 3);
Intent play = new Intent(LevelActivity.this, PlayActivity.class);
startActivity(play);
}
});
I
want to make more than 20 buttons, so how do I get this code dry.
Thanks
Solution
Put your repetitive functionality in the method
private void f(int i){
Prefs.setStagePref(getApplicationContext(), i);
Intent play = new Intent(LevelActivity.this, PlayActivity.class);
startActivity(play);
}
Then change the way you handle clicks
In the “onClick” layout
<ImageButton
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:id="@+id/saveButton" android:src="@android:drawable/ic_menu_save"
android:layout_weight="1" android:background="@drawable/menu_button" android:onClick="onClick"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:id="@+id/wallpaperButton" android:src="@android:drawable/ic_menu_gallery"
android:layout_weight="1" android:background="@drawable/menu_button" android:onClick="onClick"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:id="@+id/shareButton" android:src="@android:drawable/ic_menu_share"
android:layout_weight="1" android:background="@drawable/menu_button" android:onClick="onClick"
android:focusableInTouchMode="false"/>
activity
public void onClick(View cview) throws IOException {
switch (cview.getId()) {
case R.id.saveButton:
f(1);
break;
case R.id.shareButton:
f(2);
break;
case R.id.wallpaperButton:
f(3);
break;
}
}
or
MainActivity implements OnClickListener
...
Button level1 = (Button) findViewById(R.id.level1);
level1.setOnClickListener(this);
Button level2 = (Button) findViewById(R.id.level2);
level2.setOnClickListener(this);
Button level3 = (Button) findViewById(R.id.level3);
level3.setOnClickListener(this);
...
public void onClick(View cview) throws IOException {
switch (cview.getId()) {
case R.id.level1:
f(1);
break;
case R.id.level2:
f(2);
break;
case R.id.level3:
f(3);
break;
}
}