Android: 마이크로보 Listview와 다중 스레드 기능(JSON, 데이터 다운로드, 이미지 로드, Listview, 비동기 작업) 모방
public class WatchingActivity extends Activity implements OnClickListener, OnItemClickListener
{
private ListView mListView;
private HashMap<URL, Bitmap> mCacheMap = new HashMap<URL, Bitmap>();
private View errorView;
private View loadingview;
private RelativeLayout errorlayout;
private Button btn_netRetry;
private View headview;
private View footview;
private View btn_footviewloading;
private TextView btn_loadmore;
private int mPage = 1;
private BaseAdapter mAdapter;
private ArrayList<ItemData> mDataList = new ArrayList<ItemData>();
private View headviewad;
private View imageBtn_refresh;
/*
*
*
*
*
*
*
*
*
*
*
* ListView
*
*/
/**
* 1. , ? ===========> ,
* 2. , ------------------->layout
* 3. result --------------->
* 4.mListView.setOnItemClickListener(this); ListView ?========>
* 5. ?
* 6. ?========>
* 7.include ==============>
* 8. =============> relative xml
* 9.setonItemClick position 1 ?============> headview ,position 1
*
*/
class ItemData
{
String imageUrl;
String title;
String from;
String time;
String content;
public ItemData(String imageUrl, String title, String from,
String time, String content)
{
super();
this.imageUrl = imageUrl;
this.title = title;
this.from = from;
this.time = time;
this.content = content;
}
}
class ViewHolder
{
ImageView imageView;
TextView textView_title;
TextView textView_from;
TextView textView_time;
ProgressBar progressBar_imageLoading;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_watching);
setUI();
}
private void setUI()
{
LayoutInflater inflater = getLayoutInflater();
headview = inflater.inflate(R.layout.headview, null);
footview = inflater.inflate(R.layout.footview, null);
btn_footviewloading = footview.findViewById(R.id.footview_loading);
btn_loadmore = (TextView) footview.findViewById(R.id.btn_loadmore);
headviewad = headview.findViewById(R.id.imageView_headview_ad);
imageBtn_refresh = findViewById(R.id.imageBtn_refresh);
btn_netRetry = (Button) findViewById(R.id.btn_netRetry);
loadingview = findViewById(R.id.loadingview);
errorView = findViewById(R.id.errorview);
mListView = (ListView) findViewById(R.id.listView_watching);
mListView.addHeaderView(headview);// : setAdapter , listview
mListView.addFooterView(footview);
loadTask();
//
btn_netRetry.setOnClickListener(this);
//
btn_loadmore.setOnClickListener(this);
// ListView
headviewad.setOnClickListener(this);
//
btn_netRetry.setOnClickListener(this);
// listview
mListView.setOnItemClickListener(this);
}
//
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.btn_netRetry:
errorView.setVisibility(View.GONE);
mPage = 1;
loadTask();
break;
case R.id.btn_loadmore:
btn_loadmore.setVisibility(View.INVISIBLE);
btn_footviewloading.setVisibility(View.VISIBLE);
loadTask();
break;
case R.id.imageView_headview_ad:
Toast.makeText(WatchingActivity.this, Contant.HEADVIEW_TOAST, Toast.LENGTH_LONG).show();
break;
case R.id.imageBtn_refresh:
loadTask();
break;
default:
break;
}
}
// listview
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
{
if(view.getId() == R.id.watching_item)//
{
Intent intent = new Intent(WatchingActivity.this, ContentActivity.class);
ItemData data = mDataList.get(position - 1);
String fromtime = data.from +" " + Contant.TIME_YEAR + data.time;
intent.putExtra(Contant.KEY_INTENTER_TITLE, data.title);
intent.putExtra(Contant.KEY_INTENTER_FROMTIME, fromtime);
intent.putExtra(Contant.KEY_INTENTER_CONTENT, data.content);
startActivity(intent);
}
}
//
private void loadTask()
{
URL dataUrl = null;
try
{
dataUrl = new URL(Contant.URL_DATA + mPage + Contant.URL_DATA_FILEFORM);
//
LoadDataTask loadDataTask = new LoadDataTask();
loadDataTask.execute(dataUrl);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
}
//
class LoadDataTask extends AsyncTask<URL, Void, String>
{
@Override
protected void onPreExecute()
{
loadingview.setVisibility(View.VISIBLE);
}
@Override
protected String doInURL... params)
{
InputStream is = null;
ByteArrayBuffer strBuf = new ByteArrayBuffer(59658);// ByteArrayBuffer, String
try
{
HttpURLConnection conn = (HttpURLConnection) params[0].openConnection();
conn.setConnectTimeout(Contant.HTTP_TIME_OUT);
conn.setReadTimeout(Contant.HTTP_TIME_OUT);
//
if(conn.getResponseCode() != HttpURLConnection.HTTP_OK)
{
//
return null;
}
//
is = conn.getInputStream();
byte[] buf = new byte[1024];
int len = 0;
while (-1 != (len = is.read(buf)))
{
strBuf.append(buf, 0, len);// ByteArrayBuffer
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (is != null)
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return new String(strBuf.buffer());//bytebuffer
}
// ,
@Override
protected void onPostExecute(String result)
{
loadingview.setVisibility(View.GONE);
// result
if(TextUtils.isEmpty(result.trim()))
{
btn_loadmore.setVisibility(View.GONE);
errorView.setVisibility(View.VISIBLE);
mListView.setVisibility(View.GONE);
// return;
}
else
{
btn_loadmore.setVisibility(View.VISIBLE);
btn_footviewloading.setVisibility(View.INVISIBLE);
mListView.setVisibility(View.VISIBLE);
// json
ArrayList<ItemData> dataList = parse(result);
//
setListData(dataList);
}
}
}
//
private void setListData(ArrayList<ItemData> dataList)
{
// mAdapter , mAdapter , set ( )
if(null == mAdapter)
{
createAdapter(dataList);//
mListView.setAdapter(mAdapter);
}
else
{
mAdapter.notifyDataSetChanged();// listview
}
}
// json
private ArrayList<ItemData> parse(String result)
{
try
{
JSONArray jsonArray = new JSONArray(result);
mPage++;// ,
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String imageUrl = Contant.URL_HOST + jsonObject.getString(Contant.KEY_JSON_IMGURL);
String title = jsonObject.getString(Contant.KEY_JSON_TITLE);
String from = jsonObject.getString(Contant.KEY_JSON_FROM);
String time = jsonObject.getString(Contant.KEY_JSON_TIME);
String content = jsonObject.getString(Contant.KEY_JSON_CONTENT);
ItemData itemData = new ItemData(imageUrl, title, from, time,content);
mDataList.add(itemData);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return mDataList;
}
// Adapter, LiseView
private void createAdapter(final ArrayList<ItemData> dataList)
{
mAdapter = new BaseAdapter()
{
@Override
public View getView(int position, View convertView,ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.watch_layout, null);
holder = new ViewHolder();
holder.imageView = (ImageView) convertView.findViewById(R.id.imgView_watch_newspic);
holder.textView_title = (TextView) convertView.findViewById(R.id.txtView_watch_title);
holder.textView_from = (TextView) convertView.findViewById(R.id.txtView_from);
holder.textView_time = (TextView) convertView.findViewById(R.id.txtView_time);
holder.progressBar_imageLoading = (ProgressBar) convertView.findViewById(R.id.progressBar_imageloading);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
ItemData itemData = dataList.get(position);
//
try
{
URL url = new URL(itemData.imageUrl);
if(mCacheMap.containsKey(url))
{
holder.imageView.setImageBitmap(mCacheMap.get(url));
}
else
{
LoadImageTask imageTask = new LoadImageTask(holder.imageView,holder.progressBar_imageLoading);
imageTask.execute(url);
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
holder.textView_title.setText(itemData.title);
holder.textView_from.setText(itemData.from);
holder.textView_time.setText(itemData.time);
return convertView;
}
@Override
public long getItemId(int position)
{
return 0;
}
@Override
public Object getItem(int position)
{
return null;
}
@Override
public int getCount()
{
return dataList.size();
}
};
}
//
class LoadImageTask extends AsyncTask<URL, Void, Bitmap>
{
private ImageView imageView;
ProgressBar progressBar_imageLoading;
public LoadImageTask(ImageView imageView, ProgressBar progressBar_imageLoading)
{
this.imageView = imageView;
this.progressBar_imageLoading = progressBar_imageLoading;
}
@Override
protected void onPreExecute()
{
progressBar_imageLoading.setVisibility(View.VISIBLE);
}
//
@Override
protected Bitmap doInURL... params)
{
InputStream is = null;
Bitmap bitmap = null;
try
{
//
HttpURLConnection conn = (HttpURLConnection) params[0].openConnection();
conn.setConnectTimeout(Contant.HTTP_TIME_OUT);
conn.setReadTimeout(Contant.HTTP_TIME_OUT);
if(conn.getResponseCode() != HttpURLConnection.HTTP_OK)
{
return null;
}
// url bitmap
is = conn.getInputStream(); // :is = params[0].openStream()
bitmap = BitmapFactory.decodeStream(is);
mCacheMap.put(params[0], bitmap);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(null != is )
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap)
{
if(bitmap == null)
{
//
}
else
{
progressBar_imageLoading.setVisibility(View.INVISIBLE);
imageView.setImageBitmap(bitmap);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.watching, menu);
return true;
}
}
기타 최적화 및 확장:
1. 그림을 불러오는 방법은 그림을 설정하는 방법과 같이 컨트롤 대상을 비동기 작업에 전송합니다
2.불활성 로드
기타 관련 사항:
1. 헤드뷰 숨기기
<LinearLayout android:id="@+id/item_root"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:orientation="vertical" >
<LinearLayout android:id="@+id/item_container"
<TextView android:id="@+id/tv_1" />
<TextView android:id="@+id/tv_2" />
</LinearLayout>
</LinearLayout >
숨기려는view는 루트 디렉터리의view id가 될 수 없습니다.
본고는'하늘에 흔적은 없지만 나는 날아간다'블로그에서 나온 것으로 작가에게 연락하세요!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
콘텐츠 SaaS | JSON 스키마 양식 빌더Bloomreach Content를 위한 JSON Form Builder 맞춤형 통합을 개발합니다. 최근 Bloomreach Content SaaS는 내장 앱 프레임워크를 사용하여 혁신적인 콘텐츠 유형 필드를 구축할...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.