安卓点点滴滴-------ListView和ScrollView的冲突问题

1、直接上代码xml文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
 >
 <ScrollView 
     android:id="@+id/scrollView"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     >
     <LinearLayout 
         android:layout_width="match_parent"
        android:layout_height="match_parent"
         android:orientation="vertical"
         >
         <ImageView
                android:layout_width="match_parent"
                android:layout_height="150dp"
                android:scaleType="fitXY"
                android:src="@drawable/ic_launcher" />

            <ListView
                android:id="@+id/listView"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
     </LinearLayout>
 </ScrollView>
</RelativeLayout>


出现的情况是




2、在.Java代码中写入
private ListView listView;
    private MyAdapter adapter;
    private List<Message> list;
    private ScrollView scrollView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       listView = (ListView) findViewById(R.id.listView);
       scrollView = (ScrollView) findViewById(R.id.scrollView);
       //获取数据源
       initData();
       //创建适配器
       adapter = new MyAdapter(MainActivity.this, list);
       listView.setAdapter(adapter);
    
   //设置scrollView滚动的位置
       scrollView.smoothScrollTo(0, 0);
       //给listView这是高度
       setListViewHeight(listView);
    }
   //给主件设置高度
    private void setListViewHeight(ListView listView) {
      //拿到给listVIew填充数据的adapter对象
        ListAdapter adapter = listView.getAdapter();    
        if(adapter==null){
            return;
        }
        int totalHeight = 0;//所有item 的高度
        for(int i=0;i<adapter.getCount();i++){
            //获取当前下标为i的item的view对象
            View view= adapter.getView(i, null, listView);
            //测量view
            view.measure(0, 0);
            totalHeight += view.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight()*(adapter.getCount()-1));
        listView.setLayoutParams(params);
    }


运行后的结果





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值