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

问题: I want to create a custom TextView which is square by default but if the text cannot fit into, the height increases automatically to accommodate the content. I tried sett...

问题:

I want to create a custom TextView which is square by default but if the text cannot fit into, the height increases automatically to accommodate the content.

I tried setting the height to wrap_content and overriding the onMeasure() like so:

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

But that did not work.

When content is less, it's fine. SquareView when content is small


But when content is more, the height should expand but it doesn't. A lot of text is clipping out enter image description here


回答1:

You could use setMinHeight to achieve this purpose

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

And set wrap_content to layout_height in layout:

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

Update for RecyclerView:

1.Get screen width inside Activity class:

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

2.Pass it to adapter and set when create item view:

@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);
}
  • 发表于 2019-04-01 20:59
  • 阅读 ( 122 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除