1.引入
想做一个有两个ListView的布局,上面和下面各一个,于是最初直接写了两个ListView进去,开始他们互不干扰,直到第一个的数据超过屏幕高度,发现根本不能滚动,下面的永远也看不见了。
然后查了一些资料未果,就差用固定高度了,直到想到ScrollView,但ScrollView只能有一个控件,于是可以将两个ListView放进LinearLayout里。不过如果不做任何操作,只会有一个item显示出来。
参考多方资料,最后选了一个我认为最简单的方法。
最后效果如下(可滚动):
2.实现步骤
1.需要自定义ListView,只需加一句代码,够简单:
三个构造函数不用管,重写onMeasure方法
public class MyListView extends ListView{
public MyListView(Context context) {
super(context);
}
public MyListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
至于MeasureSpec什么意思,百度最好。
2.布局:
ScrollView是在LinearLayout里的:
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<com.example.dlistview.MyListView
android:id="@+id/lv_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dividerHeight="2dp"
android:background="#32cd32">
</com.example.dlistview.MyListView>
<TextView
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="40dp"
android:padding="5dp"
android:gravity="center"
android:text="看下面"
android:textColor="#fff"
android:background="#56abe4"
/>
<com.example.dlistview.MyListView
android:id="@+id/lv_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="#228822"
android:divider="#fff"
android:dividerHeight="2dp"
></com.example.dlistview.MyListView>
</LinearLayout>
</ScrollView>
3.java代码:只是给listView准备数据进行适配。
private ListView lv1,lv2;
private String []data = {"1","2","3","4","5","6"};
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv1 = (ListView)findViewById(R.id.lv_1);
lv2 = (ListView)findViewById(R.id.lv_2);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,data);
lv1.setAdapter(adapter);
lv2.setAdapter(adapter);
}
3.注意
此例子有一个小问题:每次开始都会进入第一个ListView,即如果listView前面还有控件的话,也会跳过,必须手动滑倒顶端,由于本例前面没有控件,所以不存在。
解决方法:
在初始化时将ScrollView滚动到顶端:
sv = (ScrollView)findViewById(R.id.sv);
sv.smoothScrollTo(0,0);