当内容无法容纳时,如何创建默认形状为正方形且高度可自动调整的 TextView?

How to create a TextView with default shape as square and auto-adjustable height when content cannot fit into?

我想创建一个默认为方形的自定义 TextView,但如果文本无法容纳,高度会自动增加以容纳内容。

我尝试将高度设置为 wrap_content 并像这样覆盖 onMeasure()

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int newHeight = heightMeasureSpec > widthMeasureSpec ? heightMeasureSpec : widthMeasureSpec;
    super.onMeasure(widthMeasureSpec, newHeight);
}

但这没有用。

内容少点就好了


但是当内容较多时,高度应该会扩大但不会。很多文字被剪掉了

您可以使用 setMinHeight 来达到这个目的

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int minHeight = MeasureSpec.getSize(widthMeasureSpec);
    setMinHeight(minHeight);
}

并在布局中将wrap_content设置为layout_height

<com.test.SquareTextView
        android:id="@+id/squareTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />

RecyclerView 更新:

1.Get 内部屏幕宽度 Activity class:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int screenWidth = size.x;

2.Pass 适配器并在创建项目视图时设置:

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View root = LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.my_item, viewGroup, false);
    root.setMinimumHeight(screenWidth);
    return new ViewHolder(root);
}