|
推荐关联文章:模拟新闻APP显示界面滑动优化
image
内容:
1、异步加载(此处进行耗时操作,更新UI)
2、JSON解析,获取网络资源
3、缓存LruCache的应用
4、ViewHolder 实现控件优化
5、消除listview 快速滑动出现错位现象
6、获取最大内存
7、数据流读取
8、http请求图片
9、Bitmap 使用
10、Handler使用
11、线程
代码如下:
1、布局文件设置
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.leixiansheng.news.MainActivity"> <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent"> </ListView></RelativeLayout><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center"> <ImageView android:id="@+id/image" android:src="@mipmap/ic_launcher" android:layout_width="60dp" android:layout_height="60dp" /> <LinearLayout android:orientation="vertical" android:layout_marginLeft="10dp" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/title_tv" android:text="TITLE" android:textSize="15dp" android:maxLines="1" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/content_tv" android:text="CONTENT" android:textSize="10dp" android:maxLines="3" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout></LinearLayout>2、异步获取数据
public class NewsBean { public String view; public String title; public String content;}public class MainActivity extends AppCompatActivity { private ListView listView; private static String URL = "http://www.imooc.com/api/teacher?type=4&num=30"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.list_view); new NewsAsyncTask().execute(URL); } //*&*异步加载,处理耗时任务,UI更新 class NewsAsyncTask extends AsyncTask<String, Void, List<NewsBean>> { @Override protected List<NewsBean> doInBackground(String... strings) { return getJsonData(strings[0]); } @Override protected void onPostExecute(List<NewsBean> newsBeen) { super.onPostExecute(newsBeen); NewsAdapter adapter = new NewsAdapter(MainActivity.this, newsBeen); listView.setAdapter(adapter); } } //*&*JSON解析网页获取数据 private List<NewsBean> getJsonData(String url) { List<NewsBean> newsBeanList = new ArrayList<>(); try { String jsonString = readSteam(new URL(url).openStream()); Log.i("DATA", jsonString); JSONObject jsonObject; NewsBean newsBean; try { jsonObject = new JSONObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray("data"); for (int i = 0; i < jsonArray.length(); i++) { jsonObject = jsonArray.getJSONObject(i); newsBean = new NewsBean(); newsBean.content = jsonObject.getString("description"); newsBean.title = jsonObject.getString("name"); newsBean.view = jsonObject.getString("picSmall"); newsBeanList.add(newsBean); } } catch (JSONException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } return newsBeanList; } //*&*读取数据流 private String readSteam(InputStream is) { InputStreamReader isr; String result = ""; try { String line = ""; isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); try { while ((line = br.readLine()) != null) { result += line; } } catch (IOException e) { e.printStackTrace(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; }}3、自定义适配器
public class NewsAdapter extends BaseAdapter { private List<NewsBean> newsBeanList; private LayoutInflater inflater; private ImageLoader imageLoader; public NewsAdapter(Context context, List<NewsBean> newsBeanList) { this.newsBeanList = newsBeanList; inflater = LayoutInflater.from(context); imageLoader = new ImageLoader(); } @Override public int getCount() { return newsBeanList.size(); } @Override public Object getItem(int i) { return newsBeanList.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder viewHolder = null; if (view == null) { viewHolder = new ViewHolder(); view = inflater.inflate(R.layout.item, null); viewHolder.imageView = (ImageView) view.findViewById(R.id.image); viewHolder.title = (TextView) view.findViewById(R.id.title_tv); viewHolder.content = (TextView) view.findViewById(R.id.content_tv); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } String url = newsBeanList.get(i).view; viewHolder.imageView.setImageResource(R.mipmap.ic_launcher); //*&*设置标签,避免快速滑动listview出现位置误差 viewHolder.imageView.setTag(url);// new ImageLoader().showImageByThread(viewHolder.imageView, url); imageLoader.showImageViewByAsyncTask(viewHolder.imageView,url); viewHolder.title.setText(newsBeanList.get(i).title); viewHolder.content.setText(newsBeanList.get(i).content); return view; } //*&*优化 class ViewHolder { public TextView title; public TextView content; private ImageView imageView; }}
图片加载类
public class ImageLoader { private ImageView mImageView; private String mUrl; //*&*创建缓存 private LruCache<String, Bitmap> lruCache; public ImageLoader() { //*&*获取最大内存 int maxMemory = (int) Runtime.getRuntime().maxMemory(); //设置缓存大小 int lruCacheSize = maxMemory / 4; lruCache = new LruCache<String, Bitmap>(lruCacheSize) { @Override protected int sizeOf(String key, Bitmap value) { //获取每个数据大小 return value.getByteCount(); } }; } //添加数据到缓存 public void addBitmapToLruCache(String url, Bitmap bitmap) { if (getBitmapFromLruCache(url) == null) { lruCache.put(url, bitmap); } } //从缓存中获取数据 public Bitmap getBitmapFromLruCache(String url) { return lruCache.get(url); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (mImageView.getTag().equals(mUrl)) { mImageView.setImageBitmap((Bitmap) msg.obj); } } }; public void showImageByThread(ImageView imageView, final String url) { mImageView = imageView; mUrl = url; new Thread() { @Override public void run() { super.run(); Bitmap bitmap = getBitmapFromURL(url); Message message = Message.obtain(); message.obj = bitmap; handler.sendMessage(message); } }.start(); } public Bitmap getBitmapFromURL(String urlString) { Bitmap bitmap; InputStream is = null; try { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); is = new BufferedInputStream(connection.getInputStream()); bitmap = BitmapFactory.decodeStream(is); connection.disconnect(); //模拟网速卡顿时// try {// Thread.sleep(1000);// } catch (InterruptedException e) {// e.printStackTrace();// } return bitmap; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } public void showImageViewByAsyncTask(ImageView imageView, String url) { //判断是否已经缓存 Bitmap bitmap = getBitmapFromLruCache(url); //没有缓存则从新下载 if (bitmap == null) { new NewsAsyncTask(imageView, url).execute(url); } else { imageView.setImageBitmap(bitmap); } } private class NewsAsyncTask extends AsyncTask<String, Void, Bitmap> { private ImageView imageView; private String url; public NewsAsyncTask(ImageView imageView, String url) { this.imageView = imageView; this.url = url; } @Override protected Bitmap doInBackground(String... strings) { String url = strings[0]; //从网络获取图片 Bitmap bitmap = getBitmapFromURL(url); if (bitmap != null) { //将不在缓存中的图片加入到缓存 addBitmapToLruCache(url, bitmap); } return bitmap; } @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); if (imageView.getTag().equals(url)) { imageView.setImageBitmap(bitmap); } } }}4、listview添加适配器(在2步骤中已经添加)
5、权限声明
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.leixiansheng.news"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>
补充:
本地图片加载出现错位,直接在adapter中用if()else对图片设置进行区分
if ("xxx") {//根据条件修改图片 viewHolder.imageView.setImageResource("要改变成的图片"); } else { viewHolder.imageView.setImageResource("默认图片"); }<hr>
赠人玫瑰,手有余香。您的支持是我创作最大的动力! |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?立即注册
×
|