我有一个带有两个 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 次。要在单个包含的布局中为这两个文本视图查找和设置文本,我必须找到一个布局的 id,然后从那里找到两个文本视图的 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);
}
我怎样才能避免这种怪物?