導言:咱們在用到ScrollView時,有時候須要它的顯示區高度能夠調整,好比一段話放到ScrollView中,當這段話只有一行時,咱們設置ScrollView的高度爲20;有兩行時,咱們設置ScrollView的高度爲40;有三行或更多行時,設置ScrollView的高度爲60(超過三行後,自動出滾動條)java
方法:將ScrollView放到一個LinearLayout中,將ScrollView的高度設置成match_parent,在代碼中動態設置LinearLayout的高度,達到ScrollView高度動態經過Java代碼設置的效果。android
效果圖:ide
點擊前佈局
點擊後.net
代碼:xml
MainActivity.java:blog
public class MainActivity extends AppCompatActivity {
Button btn;
LinearLayout ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
ll = (LinearLayout) findViewById(R.id.ll);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) ll.getLayoutParams();
int llHeight = ll.getHeight();
if (llHeight == 80) {
lp.height = 120;
} else {
lp.height = 80;
}
ll.setLayoutParams(lp);
}
});
}
}
佈局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_gravity="center"
android:text="調整" />
<LinearLayout
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="80dp">
<ScrollView
android:id="@+id/sv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dddddd">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="aaaaaaaaaaaaaa\naaaaaaaaaaaaaaaa\naaaabbbbbbbbbbbbb\nbbbbbbbbbbbbbb\nbbbbbbbcccccccccccccccc\nccccccccccccc\nccccccccccccccccccccccccccccccc
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" />
</ScrollView>
</LinearLayout>
</LinearLayout>utf-8
————————————————
版權聲明:本文爲CSDN博主「weixin_38125090」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處連接及本聲明。
原文連接:https://blog.csdn.net/weixin_38125090/article/details/79135443get