关闭

ListView的学习

标签: 个人学习
96人阅读 评论(0) 收藏 举报
分类:

ListView的学习
创建ListView的步骤
1:布局里创建ListView控件
2:给ListView创建每一个的item布局
3:准备数据源
4:在Adapter里适配数据
5:给ListView设置适配器

适配器里的4个抽象方法:
getCount(); 返回数据源的个数
getItem();返回条目
getItemId();返回条目id
getView();//适配器里最重要的方法,设置数据适配的过程.
一开始获取LayoutInflater的实例,用它的实例来获取item布局的layout
然后获取控件 设置数据 返回view


最简单的listview

public class MainActivity extends AppCompatActivity {
    private List<String> mAppName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       ListView mListView = (ListView) findViewById(R.id.list_view);

        mAppName = new ArrayList<>();
        mAppName.add("QQ");
        mAppName.add("旺旺");
        mAppName.add("喵喵");

        mListView.setAdapter(new mAdapter());
    }

    class mAdapter  extends BaseAdapter{

        @Override
        public int getCount() {
            return mAppName.size();
        }

        @Override
        public Object getItem(int position) {
            return mAppName.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            /**
             * 在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById()。不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;而findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等)。 具体作用:

             1、对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;

             2、对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素。

             获得 LayoutInflater 实例的三种方式:

             1.LayoutInflater inflater = getLayoutInflater();  //调用Activity的getLayoutInflater()

             2.LayoutInflater localinflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

             3. LayoutInflater inflater = LayoutInflater.from(context);
             */
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.item_app_view,null);

            ImageView mIcon = (ImageView) convertView.findViewById(R.id.item_app_icon);
            TextView mText = (TextView)convertView.findViewById(R.id.item_app_text);

            mText.setText(mAppName.get(position));

            return convertView;
        }
    }





获取系统已安装的列表Demo和添加头布局,listView点击事件

转自:http://blog.csdn.net/maoxiao1229/article/details/38301657/#comments
方法1:ResolveInfo
获取全部应用:  
    PackageManager packageManager = getPackageManager();  
    Intent mIntent = new Intent(Intent.ACTION_MAIN, null);  
    mIntent.addCategory(Intent.CATEGORY_LAUNCHER);  
    List<ResolveInfo> listAllApps = packageManager.queryIntentActivities(mIntent, 0); 
    判断是否系统应用:  
    ResolveInfo appInfo = listAllApps.get(position);  
    String pkgName = appInfo.activityInfo.packageName;//获取包名  
    //根据包名获取PackageInfo mPackageInfo;(需要处理异常)  
    mPackageInfo = mContext.getPackageManager().getPackageInfo(pkgName, 0);  
    if ((mPackageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {  
            //第三方应用  
        } else {  
            //系统应用  
        }  
获取相关信息:  
ResolveInfo mResolveInfo ;  
获取包名: mResolveInfo.activityInfo.packageName;  
获取icon: mResolveInfo.loadIcon(packageManager);  
获取应用名: mResolveInfo.loadLabel(packageManager).toString();  


方法2:PackageInfo
获取全部应用:  
PackageManager packageManager = this.getPackageManager();   
List<PackageInfo> packageInfoList = packageInfoList .getInstalledPackages(0);    
判断是否系统应用:  
 List<PackageInfo> apps = new ArrayList<PackageInfo>();  
 for (int i = 0; i < packageInfoList.size(); i++) {  
            PackageInfo pak = (PackageInfo)packageInfoList.get(i);  
            //判断是否为系统预装的应用  
            if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {  
                // 第三方应用  
                apps.add(pak);  
            } else  
        {  
        //系统应用  
        }  
        }  
获取相关信息:  
PackageInfo mPackageInfo;  
获取包名: mPackageInfo.packageName  
获取icon: mPackageInfo.getApplicationIcon(applicationInfo);  
获取应用名: mPackageInfo.getApplicationLabel(applicationInfo);  
获取使用权限:  
mPackageInfo.getPackageInfo(packageName,PackageManager.GET_PERMISSIONS).requestedPermissions;  

跳转系统应用

 //获取包名
                String packageName = mAppInfos.get(position).activityInfo.packageName;
                //获取应用名
                String className = mAppInfos.get(position).activityInfo.name;
                //通过调用Intent中的setComponent方法,我们可以打开另外一个应用中的Activity或者服务。
                //实例化一个ComponentName需要两个参数,第一个参数是要启动应用的包名称,这个包名称是指清单文件中列出的应用的包名称:
                ComponentName componentName = new ComponentName(packageName,className);
                Intent intent = new Intent();
                intent.setComponent(componentName);
                startActivity(intent);

Demo程序:

public class MainActivity extends AppCompatActivity {

    private List<ResolveInfo> mAppInfos;
    private ListView mListView;
    private PackageManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        initListener();

    }

    private void initView() {
        mListView = (ListView) findViewById(R.id.list_view);
    }

    private void initData() {
        //给ListView添加头布局
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View inflate = inflater.inflate(R.layout.item_header_view,null);
        mListView.addHeaderView(inflate);
        //获取包管理器实例
        manager = getPackageManager();
        Intent mIntent = new Intent(Intent.ACTION_MAIN, null);
        mIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        //获取系统所有app信息
        mAppInfos = manager.queryIntentActivities(mIntent, 0);
        mListView.setAdapter(new mAdapter());
    }

    private void initListener() {
        //给listView设置条目点击事件
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //获取包名
                String packageName = mAppInfos.get(position).activityInfo.packageName;
                //获取应用名
                String className = mAppInfos.get(position).activityInfo.name;
                //通过调用Intent中的setComponent方法,我们可以打开另外一个应用中的Activity或者服务。
                //实例化一个ComponentName需要两个参数,第一个参数是要启动应用的包名称,这个包名称是指清单文件中列出的应用的包名称:
                ComponentName componentName = new ComponentName(packageName,className);
                Intent intent = new Intent();
                intent.setComponent(componentName);
                startActivity(intent);
            }
        });

    }

    class mAdapter  extends BaseAdapter{

        @Override
        public int getCount() {
            return mAppInfos.size();
        }
        @Override
        public Object getItem(int position) {
            return mAppInfos.get(position);
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.item_app_view,null);

            ImageView mIcon = (ImageView) convertView.findViewById(R.id.item_app_icon);
            TextView mText = (TextView)convertView.findViewById(R.id.item_app_text);

            //获取应用名
            String appName = mAppInfos.get(position).activityInfo.loadLabel(manager).toString();
            //获取应用图片资源路径
            Drawable drawable = mAppInfos.get(position).activityInfo.loadIcon(manager);
            //设置
            mText.setText(appName);
            mIcon.setImageDrawable(drawable);

            return convertView;
        }
    }


}


----------


----------

给getView增加ViewHolder优化点listView的性能
----------

      public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = new ViewHolder();
            //没有复用view的时,使用viewholder保存找到的空间,下次复用不需要再次查找.
            if(convertView == null){
                LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.item_app_view,null);
                holder.mDrawable  = (ImageView) convertView.findViewById(R.id.item_app_icon);
                holder.mAppName = (TextView)convertView.findViewById(R.id.item_app_text);
                //给复用view设置标记
                convertView.setTag(holder);
            }else{
                //取出标记中的holder
                holder = (ViewHolder) convertView.getTag();
            }
            //获取应用名
            String appName =mAppInfos.get(position).activityInfo.loadLabel(manager).toString();
            //获取应用图片资源路径
            Drawable appDrawable =  mAppInfos.get(position).activityInfo.loadIcon(manager);
            holder.mAppName.setText(appName);
            holder.mDrawable.setImageDrawable(appDrawable);

            return convertView;
        }
    }

    class ViewHolder {
        TextView mAppName;
        ImageView mDrawable;
    }



ListViewDemo异步请求网络,加载到listView中

public class RequestActivity extends AppCompatActivity{
    private List<lessonInfo> lessonInfos ;
    private static final String TAG = "RequestActivity";
    private final String STATUS;
    private final String MSG;
    private final String NAME;
    private ListView mListView;

    public RequestActivity() {
        STATUS = "status";
        MSG = "msg";
        NAME = "name";
    }

    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        new RequestAsyncTask().execute();

    }

    private void initView() {
        mListView = (ListView) findViewById(R.id.list_view);
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View footView = inflater.inflate(R.layout.item_header_view, null);
        //添加脚布局
        mListView.addFooterView(footView);
    }

    class RequestAsyncTask extends AsyncTask<Void,Integer,String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //Loading
        }
        //在异步里请求数据
        @Override
        protected String doInBackground(Void... params) {
            return request(getString(R.string.request_url));
        }
        @Override
        protected void onPostExecute(String result) {
            //Loding结束,刷新数据,处理界面
            lessonResult lessonResult = new lessonResult();
            try {
                JSONObject jsonObject = new JSONObject(result);
                String status = jsonObject.getString(STATUS);
                String msg = jsonObject.getString(MSG);
                lessonResult.setmMessage(msg);
                lessonResult.setmStatus(status);

                List<lessonInfo> lessonInfos = new ArrayList<>();
                JSONArray dataArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < dataArray.length(); i++) {
                    lessonInfo lessonInfo = new lessonInfo();
                    JSONObject tempJsonObject = (JSONObject) dataArray.get(i);
                    lessonInfo.setmName(tempJsonObject.getString("name"));
                    lessonInfos.add(lessonInfo);
                    Log.i(TAG, "onPostExecute: 11111111111111");
                }
                lessonResult.setmLessInfos(lessonInfos);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            //设置适配器
            mListView.setAdapter(new RequestAdapter(RequestActivity.this,lessonResult.getmLessInfos()));
        }
    }

    //请求网络,拿到数据
    private String request(String stringUrl) {
        try {
            URL url = new URL(stringUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setReadTimeout(30000);//设置连接超时时间
            conn.setRequestMethod("GET");//设置请求方式
            int Code = conn.getResponseCode();//获取响应吗
            if(Code == HttpURLConnection.HTTP_OK){//请求成功
                //开始下载
                InputStreamReader isr = new InputStreamReader(conn.getInputStream());
                BufferedReader br = new BufferedReader(isr);

                //用一个StringBuilder存储数据
                StringBuilder sb = new StringBuilder();
                String line ;//读取每行数据
               while ((line =br.readLine()) !=null){
                   sb.append(line);
               }
               return sb.toString();
            }else{

            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
public class RequestAdapter extends BaseAdapter {

    List<lessonInfo> infos = new ArrayList<>();
    Context mContext;

    public RequestAdapter(Context context, List<lessonInfo> info) {
        infos =info;
        mContext = context;
    }
    @Override
    public int getCount() {
        return infos.size();
    }

    @Override
    public Object getItem(int position) {
        return infos.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = new ViewHolder();

        if (convertView == null){
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.item_app_view,null);
            holder.mName = (TextView) convertView.findViewById(R.id.item_app_text);
            holder.mImageView = (ImageView) convertView.findViewById(R.id.item_app_icon);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }
        holder.mName.setText(infos.get(position).getmName());
        holder.mImageView.setVisibility(View.GONE);
        return convertView;
    }

    class ViewHolder {
        private TextView mName;
        private ImageView mImageView;
    }

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:773次
    • 积分:142
    • 等级:
    • 排名:千里之外
    • 原创:14篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章存档