android 简单的两步实现Play上的文本伸缩功能

时间:2020-12-03 15:45:03

经常上google play下载软件,看到它的伸缩式的软件介绍很感兴趣。功能截图如下:

android 简单的两步实现Play上的文本伸缩功能

点击文本会下拉更多详细介绍,实现这一功能很简单,废话不多说,直接上代码

 

 private boolean isExpanded = false;
private int lastHeight = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expand_in_context);

final ViewGroup expandableContainer = (ViewGroup) findViewById(R.id.expandable_container);

findViewById(R.id.expandable_text).setOnClickListener(
new View.OnClickListener() {

@Override
public void onClick(View v) {
if (isExpanded) {
ViewGroup.LayoutParams params
= (ViewGroup.LayoutParams) expandableContainer
.getLayoutParams();

params.height
= lastHeight;

expandableContainer.setLayoutParams(params);
expandableContainer.invalidate();
}
else {
lastHeight
= expandableContainer.getHeight();

ViewGroup.LayoutParams params
= (ViewGroup.LayoutParams) expandableContainer
.getLayoutParams();

params.height
= ViewGroup.LayoutParams.WRAP_CONTENT;

expandableContainer.setLayoutParams(params);
expandableContainer.invalidate();
}

isExpanded
= !isExpanded;

}
});

}

布局只需要这样:

 <FrameLayout
android:id="@+id/expandable_container"
android:layout_width
="wrap_content"
android:layout_height
="200dp"
android:layout_below
="@+id/above"
android:layout_margin
="15dp"
>

<TextView
android:id="@+id/expandable_text"
android:layout_width
="match_parent"
android:layout_height
="match_parent"
android:ellipsize
="end"
android:text
="@string/loremipsum"
android:clickable
="true"/>
</FrameLayout>

父布局限定了可限示的高度,可以使文本不用一次性全部显示,为屏幕节省空间。等用户点击查时才一次性显示全部给用户,再一次点击则隐藏掉。。原理很简单。