Android 线性布局自适应元素的高度

Android Linear Layout adapting height to elements

我在垂直线性布局中有以下水平线性布局:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_marginTop="5dp"
    android:layout_marginBottom="5dp"
    android:background="@color/White"
    android:orientation="vertical">

    <TextView
        android:id="@+id/pokemonTeambuilderTitleTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top|start"
        android:paddingStart="10dp"
        android:paddingTop="10dp"
        android:paddingEnd="10dp"
        android:paddingBottom="5dp"
        android:text="@string/placeholder"
        android:textColor="@color/Black"
        android:textSize="16sp"
        android:textStyle="bold" />

    <LinearLayout
        android:id="@+id/pokemonTeambuilderSpritesLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

    </LinearLayout>

</LinearLayout>

我以编程方式在我的适配器中以这种方式设置元素:

 for (Pokemon pokemon : pokemonTeam.getPokemonList()) {
        String pokemonNickname = pokemon.getNickname();
        String pokemonName = pokemon.getName();
        ImageView tvPokemonSprite = new ImageView(mContext);
        int color = PokemonUtils.getDominantColorFromPokemon(pokemon.get_id(),mContext);
        tvPokemonSprite.setImageResource(PokemonUtils.getPokemonSugimoriImageById(pokemon.get_id(), mContext));
        tvPokemonSprite.setScaleType(ImageView.ScaleType.FIT_CENTER);
        PokemonUtils.setResourceAndBorderBackgroundColorToElementFromColor(tvPokemonSprite,R.drawable.circle_shape,color,PokemonUtils.lighterColor(color, DARK_FACTOR));
        TableLayout.LayoutParams layout = new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
        tvPokemonSprite.setLayoutParams(layout);
        holder.teamSpritesLinearLayout.addView(tvPokemonSprite);
    }

但是,如果我旋转 phone,元素不会完全适合线性布局,底部和顶部被切掉一半,如果水平线性布局只有 1 个口袋妖怪,而不是适应 1 个插槽,它扩展了整个视图(正如您在 charizard 中看到的那样)

将以下代码添加到 imageview:

tvPokemonSprite.setAdjustViewBounds(true)

我希望能为你工作。