2 つの TextView を持つ単純なレイアウト ファイルがあります。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_tile_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sample text"
android:textSize="18dp"
android:layout_gravity="center_horizontal"/>
<TextView
android:id="@+id/tv_tile_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="20.0"
android:textSize="26dp"
android:textStyle="bold" />
</LinearLayout>
このレイアウトをアプリのいくつかの場所に含めます。私の最後のケースでは、これを 4 回含める必要がありました。含まれている個々のレイアウトでこれら 2 つのテキスト ビューにテキストを見つけて設定するには、1 つのレイアウトの ID を見つけ、そこから 2 つのテキスト ビューの ID を見つける必要があります。含まれているすべてのレイアウトについて、3 回繰り返します。これにより、コードを維持するのが醜く恐ろしいものになります。
@Override
public void setStatsValues(String today, String week, String month, String total) {
// this is so tedious.
View layoutDay = findViewById(R.id.layout_stats_day);
View layoutWeek = findViewById(R.id.layout_stats_week);
View layoutMonth = findViewById(R.id.layout_stats_month);
View layoutTotal = findViewById(R.id.layout_stats_total);
TextView tvDayTitle = layoutDay.findViewById(R.id.tv_tile_title);
TextView tvWeekTitle = layoutWeek.findViewById(R.id.tv_tile_title);
TextView tvMonthTitle = layoutMonth.findViewById(R.id.tv_tile_title);
TextView tvTotalTitle = layoutTotal.findViewById(R.id.tv_tile_title);
TextView tvDayValue = layoutDay.findViewById(R.id.tv_tile_value);
TextView tvWeekValue = layoutWeek.findViewById(R.id.tv_tile_value);
TextView tvMonthValue = layoutMonth.findViewById(R.id.tv_tile_value);
TextView tvTotalValue = layoutTotal.findViewById(R.id.tv_tile_value);
tvDayTitle.setText("Today");
tvWeekTitle.setText("Week");
tvMonthTitle.setText("Month");
tvTotalTitle.setText("Total");
tvDayValue.setText(today);
tvWeekValue.setText(week);
tvMonthValue.setText(month);
tvTotalValue.setText(total);
}
どうすればこの怪物を避けることができますか?