我使用CardView作为Recycler Adapter的一个项目。如何缩放视图以适应Android动画中的内容大小?
首先,所有项目都不会显示全部内容,(我将它剪切并放置'... ...'代替)
但点击它后,点击的项目会缩放它的高度以适合内容高度。 (这里我设置文本的全部内容,希望该卡可以扩展,以适应它)
的样子:
我知道如何高度动画的具体目标高度但在这种情况下,我不知道如何测量显示整个内容所需的高度,每个项目应该有不同的目标高度。
我该怎么办?
我使用CardView作为Recycler Adapter的一个项目。如何缩放视图以适应Android动画中的内容大小?
首先,所有项目都不会显示全部内容,(我将它剪切并放置'... ...'代替)
但点击它后,点击的项目会缩放它的高度以适合内容高度。 (这里我设置文本的全部内容,希望该卡可以扩展,以适应它)
的样子:
我知道如何高度动画的具体目标高度但在这种情况下,我不知道如何测量显示整个内容所需的高度,每个项目应该有不同的目标高度。
我该怎么办?
你可以做的是要求View
衡量自己的身高不受限制。请注意拨打电话view.getWidth()
,只有在View
已经布置好后,您才可以这样做,因为您在onClick()
中打电话给它应该没问题。
int widthSpec = View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY);
int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(widthSpec, heightSpec);
int targetHeight = view.getMeasuredHeight();
假设你的看法与这些属性设置一个TextView:
android:layout_height="wrap_content"
android:maxLines="1"
android:ellipsize="end"
完整的例子是
// this is the height measured with maxLines 1 and height
// to wrap_content
final int startHeight = view.getHeight();
// you want to measure the TextView with all text lines
view.setMaxLines(Integer.MAX_VALUE);
int widthSpec = View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY);
int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(widthSpec, heightSpec);
// final height of the TextView
int targetHeight = view.getMeasuredHeight();
// this is the value that will be animated from 0% to 100%
final int heightSpan = targetHeight-startHeight;
// remove that wrap_content and set the starting point
view.getLayoutParams().height = startHeight;
view.setLayoutParams(view.getLayoutParams());
Animation animation = new Animation(){
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
view.getLayoutParams().height = (int) (startHeight + heightSpan*interpolatedTime);
view.setLayoutParams(view.getLayoutParams());
}
};
animation.setDuration(1000);
view.startAnimation(animation);
你可以做到这一点很简单。 设置文本时TextView的首次,这样写:
int minLineNumber = 2;
textView.setMaxLines(minLineNumber); // 2 is your number of line for the first time
,当点击是:
textView.setMaxLines(Integer.MAX_VALUE); // set the height like wrap_content
,如果你希望动画,你有某事像这样:
ObjectAnimator animation = ObjectAnimator.ofInt(
textView,
"maxLines",
textView.getLineCount());
int duration = (textView.getLineCount() - minLineNumber) * 50;
animation.setDuration(duration);
animation.start();
如果TextView中的文本太多,最好使用固定的持续时间,而不是依赖于高度。
但是,这是否启动动画? –
[OOD Waterball](https://stackoverflow.com/users/7471830/ood-waterball),我用动画编辑答案。 –
确保你没有使用maxlines属性或任何类似的 – kulvinder
检查这个问题[答案](https://stackoverflow.com/questions/15627530/android-expandable-textview-with-animation) – karthik
@kulvinder Do u意味着使用maxlines的解决方案有一些缺点? –