IT月光

导航

SrcollView分页加载数据(MainActivity)

package com.baidu.mylistscroll;

import java.util.ArrayList;
import java.util.List;

import com.baidu.adapter.MyAdapter;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;

public class MainActivity extends Activity {
    private ListView lv;
    private List<String> list;
    private ScrollView scrollView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list = new ArrayList<String>();
        init();
    }
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        
        super.onWindowFocusChanged(hasFocus);
        setListViewHeightBasedOnChildren(lv);
    }
    private void init() {
        //找到相应的控件
        lv = (ListView) findViewById(R.id.lv);
        scrollView = (ScrollView) findViewById(R.id.ss);
        getData();
    }
    private void getData() {
        for(int i=0;i<40;i++){
            list.add("第"+i+"条目");
        }
        MyAdapter adapter=new MyAdapter(MainActivity.this,list);
        lv.setAdapter(adapter);
        lv.setOnTouchListener(new View.OnTouchListener() {  
            
            @Override  
            public boolean onTouch(View v, MotionEvent event) {  
                if(event.getAction() == MotionEvent.ACTION_UP){  
                    scrollView.requestDisallowInterceptTouchEvent(false);  
                }else{  
                    scrollView.requestDisallowInterceptTouchEvent(true);  
                }  
                return false;  
            }  
        });  
    }
//设置定义高度的方法
    private void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
        return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(0, 0);
        totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = 600/*totalHeight
        + (listView.getDividerHeight() * (listAdapter.getCount() - 1))*/;
        listView.setLayoutParams(params);
    }

}

posted on 2016-04-14 09:30  IT月光  阅读(139)  评论(0编辑  收藏  举报