Я пытаюсь создать фрагмент, который динамически излагает серию пользовательских представлений. Основное содержание этого макета - RelativeLayout, вложенное в LinearLayout (чтобы центрировать его по горизонтали), вложенное в ScrollView.
RelativeLayout имеет несколько TextViews и 9 патчей ImageView, предназначенных для масштабирования с добавлением динамически добавленных пользовательских представлений. Однако изображение (достижения_bgImageView ниже) заканчивается размером экрана и не учитывает размер его родительского RelativeLayout даже после того, как я добавил соответствующее количество пользовательских представлений. Изображение масштабируется отлично, когда я вручную устанавливаю размер достижений_mainLayout (см. Прокомментированные строки ниже), но ничего не делает, если я попытаюсь позволить этому RelativeLayout wrap_content обрабатывать собственный размер.
ScrollView IS, соблюдая размер RelativeLayout, поскольку все содержимое присутствует, это просто изображение, которое не растягивается, чтобы соответствовать содержимому в этой точке.
Любая помощь будет оценена... Мои расчеты вручную не кажутся достаточно хорошими, чтобы учитывать разные устройства, несмотря на то, что я учитываю плотность экрана, и я вручную вынуждаю RelativeLayout к постоянной ширине.
Стоит отметить, что измеренный размер RelativeLayout всегда равен высоте экрана, независимо от того, больше или меньше сумма его содержимого или меньше этой высоты. Поэтому, по сути, WRAP_CONTENT просто не выполняет то, что он должен делать. У меня нет ссылки на любой край RelativeLayout, поэтому круговые зависимости не должны быть проблемой.
fragment_achievements.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<RelativeLayout
android:layout_width="320dp"
android:layout_height="wrap_content"
android:id="@+id/achievements_mainLayout">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/achievements_bgImageView"
android:src="@drawable/bkg_achievements9"
android:adjustViewBounds="true"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_centerHorizontal="true"
android:scaleType="fitXY"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name Field"
android:id="@+id/achievements_nameTextView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="28dp"
android:layout_marginTop="30dp"/>
<ImageView
android:layout_width="52dp"
android:layout_height="52dp"
android:id="@+id/achievements_avatarImageView"
android:layout_below="@+id/achievements_nameTextView"
android:layout_alignLeft="@+id/achievements_nameTextView"
android:src="@drawable/achieve_avatar"
android:layout_marginTop="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Top Moment:"
android:id="@+id/textView2"
android:layout_alignBottom="@+id/achievements_avatarImageView"
android:layout_toRightOf="@+id/achievements_avatarImageView"
android:layout_marginBottom="16dp"
android:layout_marginLeft="4dp"
android:textSize="12dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Me Overall:"
android:id="@+id/textView3"
android:layout_alignTop="@+id/textView2"
android:layout_alignLeft="@+id/textView2"
android:layout_marginTop="16dp"
android:textSize="12dp"/>
<TextView
android:layout_width="52dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="153"
android:id="@+id/achievements_totalPointsTextView"
android:gravity="center"
android:layout_alignTop="@+id/achievements_avatarImageView"
android:layout_alignRight="@+id/achievements_bgImageView"
android:layout_alignEnd="@+id/achievements_bgImageView"
android:layout_marginRight="31dp"
android:textColor="#f7a033"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Moment"
android:id="@+id/achievements_topMomentTextView"
android:layout_alignTop="@+id/textView2"
android:layout_toRightOf="@+id/textView2"
android:layout_marginLeft="5dp"
android:textSize="12dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="153"
android:id="@+id/achievements_overallTextView"
android:layout_alignTop="@+id/textView3"
android:layout_toRightOf="@+id/textView3"
android:layout_marginLeft="5dp"
android:textSize="12dp"/>
</RelativeLayout>
</LinearLayout>
</ScrollView>
AchievementFragment.java
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = null;
fragmentView = inflater.inflate(R.layout.fragment_achievements, container, false);
ImageView avatarImageView = (ImageView)fragmentView.findViewById(R.id.achievements_avatarImageView);
...
// Basic Achievement List Setup
RelativeLayout mainLayout = (RelativeLayout)fragmentView.findViewById(R.id.achievements_mainLayout);
AchievementRow currentRow = null;
List achievementTypeList = CampaignManager.sharedManager().sortedAchievementTypeList();
int achievementCount = achievementTypeList.size();
for (int i = 0; i < achievementCount; i++) {
AchievementType achievementType = (AchievementType)achievementTypeList.get(i);
// Every third achievement creates a new row.
if ((i % 3) == 0) {
AchievementRow row = (AchievementRow)inflater.inflate(R.layout.widget_achievementrow, null);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if (currentRow == null) {
layoutParams.addRule(RelativeLayout.BELOW, avatarImageView.getId());
layoutParams.setMargins(10, 70, 10, 0);
} else {
layoutParams.addRule(RelativeLayout.BELOW, currentRow.getId());
layoutParams.setMargins(10, 10, 10, 0);
}
layoutParams.addRule(RelativeLayout.ALIGN_LEFT, backgroundImageView.getId());
layoutParams.addRule(RelativeLayout.ALIGN_RIGHT, backgroundImageView.getId());
row.setLayoutParams(layoutParams);
row.setId(i+1);
mainLayout.addView(row);
currentRow = row;
}
// Now setup the Button
AchievementButton achievementButton = currentRow.buttonForIndex(i % 3);
achievementButton.achievementType = achievementType;
achievementButton.setOnClickListener(achievementButtonListener);
achievementButton.setVisibility(View.VISIBLE);
CacheManager.sharedManager().fetchAchievementThumbnail(getActivity(), achievementButton, achievementType);
}
// This is the manual scaling of mainLayout
// float scale = getResources().getDisplayMetrics().density;
// float headerHeight = scale * 150.0f;
// float rowHeight = scale * 78.0f;
// ViewGroup.LayoutParams mainLayoutParams = mainLayout.getLayoutParams();
// mainLayoutParams.height = (int)(headerHeight + (Math.ceil(achievementCount / 3.0) * rowHeight));
return fragmentView;
}