Java Android:如何在列表中动态设置ImageView src
我是android新手,我有个消息 我正在开发一个android应用程序,主要活动捕获一个JSON节点,并在ListView中显示所有文章, 列表中的每一项都有这篇文章的图片、标题和摘要 现在我已经为标题和描述编写了java代码,一切都很好,但我也想显示图像,我不知道如何做到这一点 下面是我的MainActivity.java:Java Android:如何在列表中动态设置ImageView src,java,android,json,android-studio,imageview,Java,Android,Json,Android Studio,Imageview,我是android新手,我有个消息 我正在开发一个android应用程序,主要活动捕获一个JSON节点,并在ListView中显示所有文章, 列表中的每一项都有这篇文章的图片、标题和摘要 现在我已经为标题和描述编写了java代码,一切都很好,但我也想显示图像,我不知道如何做到这一点 下面是我的MainActivity.java: import java.util.ArrayList; import java.util.HashMap; import org.json.JSONArray; im
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends ListActivity {
//Create a progress dialog instance
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://www.ana.fm/api/main/";
// JSON Node names
private static final String TAG_ARTICLES = "articles";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_TEASER = "teaser";
private static final String TAG_COVER_PHOTO = "cover_photo";
// contacts JSONArray
JSONArray articles = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String article_id = ((TextView) view.findViewById(R.id.article_id))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_ID, article_id);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
articles = jsonObj.getJSONArray(TAG_ARTICLES);
// looping through All Contacts
for (int i = 0; i < articles.length(); i++) {
JSONObject c = articles.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
title = Html.fromHtml(title).toString();
String teaser = c.getString(TAG_TEASER);
teaser = Html.fromHtml(teaser).toString();
String cover_photo = "http://www.ana.fm/med_photos/articles/";
cover_photo = cover_photo.concat(c.getString(TAG_COVER_PHOTO));
// tmp hashmap for single contact
HashMap<String, String> article = new HashMap<String, String>();
// adding each child node to HashMap key => value
article.put(TAG_ID, id);
article.put(TAG_TITLE, title);
article.put(TAG_TEASER, teaser);
article.put(TAG_COVER_PHOTO, cover_photo);
// adding contact to contact list
contactList.add(article);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
new GetContacts().execute();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { TAG_ID, TAG_TITLE, TAG_TEASER, TAG_COVER_PHOTO}, new int[] { R.id.article_id, R.id.title,
R.id.teaser, R.id.cover_photo});
setListAdapter(adapter);
}
}
}
import java.util.ArrayList;
导入java.util.HashMap;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.ListActivity;
导入android.app.ProgressDialog;
导入android.content.Intent;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.text.Html;
导入android.util.Log;
导入android.view.view;
导入android.widget.AdapterView;
导入android.widget.AdapterView.OnItemClickListener;
导入android.widget.ImageView;
导入android.widget.ListAdapter;
导入android.widget.ListView;
导入android.widget.simpledapter;
导入android.widget.TextView;
公共类MainActivity扩展了ListActivity{
//创建进度对话框实例
私人对话;
//获取联系人JSON的URL
专用静态字符串url=”http://www.ana.fm/api/main/";
//JSON节点名称
私有静态最终字符串标记_ARTICLES=“ARTICLES”;
私有静态最终字符串标记\u ID=“ID”;
私有静态最终字符串标记_TITLE=“TITLE”;
私有静态最终字符串标记\u striser=“striser”;
私有静态最终字符串标记\u COVER\u PHOTO=“COVER\u PHOTO”;
//联系JSONArray
JSONArray articles=null;
//ListView的Hashmap
ArrayList联系人列表;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList=新的ArrayList();
ListView lv=getListView();
//单击项目上的Listview侦听器
lv.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
String article_id=((TextView)view.findViewById(R.id.article_id))
.getText().toString();
//启动单一联系人活动
Intent in=新的Intent(getApplicationContext(),
活动类);
in.putExtra(标签ID、物品ID);
星触觉(in);
}
});
//调用异步任务以获取json
新建GetContacts().execute();
}
/**
*异步任务类通过HTTP调用获取json
* */
私有类GetContacts扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//显示进度对话框
pDialog=新建进度对话框(MainActivity.this);
setMessage(“请稍候…”);
pDialog.setCancelable(假);
pDialog.show();
}
@凌驾
受保护的Void doInBackground(Void…arg0){
//创建服务处理程序类实例
ServiceHandler sh=新的ServiceHandler();
//向url发出请求并获得响应
字符串jsonStr=sh.makeServiceCall(url,ServiceHandler.GET);
if(jsonStr!=null){
试一试{
JSONObject jsonObj=新的JSONObject(jsonStr);
//获取JSON数组节点
articles=jsonObj.getJSONArray(TAG_articles);
//通过所有触点循环
对于(int i=0;ivalue
物品放置(标签ID,ID);
物品放置(标签、标题、标题);
物品放置(标签,标签,标签);
物品摆放(标签、封面照片、封面照片);
//将联系人添加到联系人列表
联系人列表。添加(文章);
}
}捕获(JSONException e){
e、 printStackTrace();
}
}否则{
Log.e(“ServiceHandler”,“无法从url获取任何数据”);
新建GetContacts().execute();
}
返回null;
}
@凌驾
受保护的void onPostExecute(void结果){
super.onPostExecute(结果);
//关闭进度对话框
if(pDialog.isShowing())
pDialog.disclose();
/**
*将解析的JSON数据更新到ListView中
* */
ListAdapter=新的SimpleAdapter(
MainActivity.this,联系人列表,
R.layout.list_项,新字符串[]{TAG_ID,TAG_TITLE,TAG_trister,TAG_COVER_PHOTO},新int[]{R.ID.article_ID,R.ID.TITLE,
R.id.trister,R.id.cover_photo});
setListAdapter(适配器);
}
}
}
这是a
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@color/white">
<!-- Main ListView
Always give id value as list(@android:id/list)
-->
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:divider="@android:color/transparent"
android:dividerHeight="10.0sp"
/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:layout_marginBottom="20dp"
android:background="@color/light_grey">
<!-- Cover photo -->
<ImageView
android:id="@+id/cover_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
<!-- ID Label -->
<TextView
android:id="@+id/article_id"
android:visibility="gone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold" />
<!-- Title Label -->
<TextView
android:id="@+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dip"
android:paddingTop="6dip"
android:textColor="@color/black"
android:textSize="20sp"
android:textStyle="bold" />
<!-- Teaser label -->
<TextView
android:id="@+id/teaser"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="@color/medium_grey" />
</LinearLayout>
{
.
.
.
"cover_photo":"2018061675.jpg"
}
public class Person {
String name;
String surname;
String imageUrl;
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/person_cell_txtName" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/person_cell_txtSurname" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/person_cell_imageview" />
</LinearLayout>
public class MyAdapter extends ArrayAdapter<Person> {
Context context;
List<Person>myList;
public MyAdapter(Context context, int resource, List<Person> objects) {
super(context, resource, objects);
this.context = context;
this.myList = objects;
}
@Override
public int getCount() {
if(myList != null)
return myList.size();
return 0;
}
@Override
public Person getItem(int position) {
if(myList != null)
return myList.get(position);
return null;
}
@Override
public long getItemId(int position) {
if(myList != null)
return myList.get(position).hashCode();
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
//If the listview does not have an xml layout ready set the layout
if (convertView == null){
//we need a new holder to hold the structure of the cell
holder = new Holder();
//get the XML inflation service
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate our xml cell to the convertView
convertView = inflater.inflate(R.layout.person_cell, null);
//Get xml components into our holder class
holder.txtName = (TextView)convertView.findViewById(R.id.person_cell_txtName);
holder.txtSurname = (TextView)convertView.findViewById(R.id.person_cell_txtSurname);
holder.imageView = (ImageView)convertView.findViewById(R.id.person_cell_imageview);
//Attach our holder class to this particular cell
convertView.setTag(holder);
}else{
//The listview cell is not empty and contains already components loaded, get the tagged holder
holder = (Holder)convertView.getTag();
}
//Fill our cell with data
//get our person object from the list we passed to the adapter
Person person = getItem(position);
//Fill our view components with data
holder.txtName.setText(person.getName());
holder.txtSurname.setText(person.getSurname());
Picasso.with(context).load(person.getImageUrl()).fit().into(holder.imageView);
return convertView;
}
/**
* This holder must replicate the components in the person_cell.xml
* We have a textview for the name and the surname and an imageview for the picture
*/
private class Holder{
TextView txtName;
TextView txtSurname;
ImageView imageView;
}
}
ListView myListView = new ListView(getApplicationContext());
List<Person> personList = new ArrayList<>();
Person person = new Person();
person.setName("John");
person.setSurname("Doe");
person.setImageUrl("https://lh3.googleusercontent.com/-Sa9kdnhuE5E/AAAAAAAAAAI/AAAAAAAAABs/ILmJ8_sk9aY/photo.jpg");
MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.person_cell, personList);
myListView.setAdapter(adapter);