动态TextView显示不正确。

3
我正在循环中动态生成一些TextViews,它们可以被显示,但是我无法在它们之间创建间隔。它们显示为一行而不是分开的行。
    <?xml version="1.0" encoding="utf-8"?>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    >

        <LinearLayout

            android:id="@+id/ll"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="18dp"
            android:paddingRight="18dp"
            android:paddingTop="60dp"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:focusableInTouchMode="true"
            android:orientation="vertical">

        </LinearLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>

tviewlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/light"
    android:textAlignment="gravity"
    android:padding="10dp"
    android:layout_margin="10dp"
    android:textSize="20sp" />

Java代码

LinearLayout linearLayout =  (LinearLayout) binding.ll;
                for (int i=0; i<arrSplit.length; i++)
                {
                    TextView tv = (TextView)getLayoutInflater().inflate(R.layout.tviewlayout, null);
                    tv.setText(arrSplit[i]);
                    tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                    linearLayout.addView(tv);
                }

enter image description here


如果您将任何内容放入约束布局中(在本例中为LinearLayout),则需要定义其约束条件。将LL的所有4个约束条件设置为“parent”,情况应该会更好。还要将LL的layout_widthlayout_height设置为“0dp”。这告诉Android它应该使用给定的约束条件。 - muetzenflo
1
移除 ConstraintLayout! - Hossein
1
你能提供你所得到的截图吗? - Zain
1
@Zain 我已经添加了一张图片。 - John
所以,这些训练行中的每一行都是LinearLayout中的TextView,我认为是这样的?如果是这样的话,那就是预期的了。你能展示一下你期望看到的吗,这样就不会有混淆了。 - Zain
显示剩余2条评论
2个回答

2

我建议使用RecyclerView来实现这种类型的目的。它更加高效和动态。以下是一个Kotlin示例:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/consRideInfo"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/10dp"
    android:padding="@dimen/10dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/incActionBar">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rcvList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="0dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:itemCount="3"
        tools:listitem="@layout/row_item" />

</androidx.constraintlayout.widget.ConstraintLayout>

在Activity中定义适配器

 private var adapter: GeneralAdapter<DataModel, MainActivity>? = null
 private val list: ArrayList<DataModel> = ArrayList()

在onCreate方法中

 adapter = GeneralAdapter(R.layout.row_item, list, this)
 binding.rcvList.adapter = adapter

同时创建适配器以显示

class GeneralAdapter<D, F>(
    val layoutId: Int,
    private val arrayList: ArrayList<D>,
    val listener: F
) : RecyclerView.Adapter<GeneralAdapter.GeneralHolder<D, F>>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GeneralHolder<D, F> {
        val layoutInflater = LayoutInflater.from(parent.context)
        val binding: ViewDataBinding =
            DataBindingUtil.inflate(layoutInflater, layoutId, parent, false)

        return GeneralHolder(binding, listener)
    }

    override fun getItemCount(): Int = arrayList.size

    override fun onBindViewHolder(holder: GeneralHolder<D, F>, position: Int) {
        holder.bind(arrayList[position])
    }

    class GeneralHolder<D, F>(
        private val binding: ViewDataBinding,
        val listener: F
    ) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(data: D) {
            binding.setVariable(BR.item, data)
            binding.setVariable(BR.presenter, listener)
            binding.executePendingBindings()
        }
    }
}

1
我希望为每个TextView创建间隙,以使它们看起来分离。现在所有的TextView都被蓝色背景覆盖了。
您可以为每个TextView添加像素边距:
LinearLayout linearLayout =  (LinearLayout) binding.ll;

for (int i=0; i<arrSplit.length; i++) {
    TextView tv = (TextView)getLayoutInflater().inflate(R.layout.tviewlayout, null);
    tv.setText(arrSplit[i]);
    tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tv.getLayoutParams();
    params.bottomMargin = (int) getPx(100); // adding 100dp gap between TextViews
    linearLayout.addView(tv);
}



/*
 * Convert dp value to pixel
 * */
private float getPx(float dp) {
    return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dp,
            getResources().getDisplayMetrics());
}

更新

你能演示一下如何通过RecyclerView实现相同的效果吗?

这里有一个示例:

main_activity.xml:

<?xml version="1.0" encoding="utf-8"?>

<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rvList"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" />

list_item.xml: 包含了一个用于你的 TextView 的模板。 使用 android:layout_marginBottom 来为相邻的两个 TextView 添加所需的间距。

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tvColorName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="32dp"
    android:textSize="18sp" />

Adapter:

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.CustomViewHolder> {

    private List<String> mColors;

    // Constructor
    RecyclerAdapter(List<String> colors) {
        this.mColors = colors;
    }


    @NonNull
    @Override
    public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        View listItem = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item, parent, false);
        return new CustomViewHolder(listItem);
    }

    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
        String color = mColors.get(position);
        holder.tvColorName.setText(color);
    }

    @Override
    public int getItemCount() {
        return mColors.size();
    }


    class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {

        TextView tvColorName;

        CustomViewHolder(@NonNull View listItem) {
            super(listItem);
            // caching views
            tvColorName = listItem.findViewById(R.id.tvColorName);
        }

    }


}

活动:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Building RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // Building RecyclerAdapter
        RecyclerAdapter adapter = new RecyclerAdapter(this, getColors());
        recyclerView.setAdapter(adapter);

    }
    
    
    private ArrayList<String> getColors() {
        ArrayList<String> colors = new ArrayList<>();
        colors.add("Red");
        colors.add("White");
        colors.add("Green");
        colors.add("Purple");
        colors.add("Yellow");
        colors.add("Blue");
        colors.add("Black");
        colors.add("Brown");
        colors.add("Magenta");
        colors.add("Cyan");
        colors.add("Gray");
        colors.add("Orange");
        return colors;
    }
    
}


但我建议改用RecyclerView来实现,以便具备视图回收功能。 - Zain
你能展示一下如何使用RecyclerView实现相同的效果吗? - John
@John 当然,请查看更新后的答案。 - Zain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接