gpt4 book ai didi

android - Gridview - 单击 gridview 项目以在 imageview 中显示图像

转载 作者:行者123 更新时间:2023-11-29 21:57:14 25 4
gpt4 key购买 nike

我关注这个教程 Android Lazy Loading images and text in listview from http json data现在我将 ListView 更改为 GridView 。

我的问题是

我想点击 gridview 项目,它在 imageview 中显示图像

主要 Activity

public class MainActivity extends Activity {

GridView gridView;

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

String strUrl = "http://ta.wptrafficanalyzer.in/demo1/first.php/countries/";
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);

gridView = (GridView) findViewById(R.id.lv_countries);
gridView.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View v, int positon,
long id) {
Toast.makeText(getApplicationContext(), "welcome to hello gridview", Toast.LENGTH_SHORT).show();
}
});

}

private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}

data = sb.toString();
br.close();

}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}

return data;
}

private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
@Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}

@Override
protected void onPostExecute(String result) {
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
listViewLoaderTask.execute(result);
}
}

private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{

JSONObject jObject;
@Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
CountryJSONParser countryJsonParser = new CountryJSONParser();
countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}

CountryJSONParser countryJsonParser = new CountryJSONParser();
List<HashMap<String, Object>> countries = null;

try{
countries = countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}

String[] from = { "country","flag","details"};
int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);

return adapter;
}

@Override
protected void onPostExecute(SimpleAdapter adapter) {

gridView.setAdapter(adapter);

for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);

imageLoaderTask.execute(hm);
}
}
}

private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{

@Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {

InputStream iStream=null;
String imgUrl;
imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");

URL url;
try {
url = new URL(imgUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();

File cacheDirectory = getBaseContext().getCacheDir();
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
FileOutputStream fOutStream = new FileOutputStream(tmpFile);

Bitmap b = BitmapFactory.decodeStream(iStream);
b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);

fOutStream.flush();
fOutStream.close();
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();

hmBitmap.put("flag",tmpFile.getPath());
hmBitmap.put("position",position);

return hmBitmap;

}catch (Exception e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(HashMap<String, Object> result) {
String path = (String) result.get("flag");
int position = (Integer) result.get("position");

SimpleAdapter adapter = (SimpleAdapter ) gridView.getAdapter();
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
hm.put("flag",path);

adapter.notifyDataSetChanged();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}CountryJSONParser.java

public class CountryJSONParser {

public List<HashMap<String,Object>> parse(JSONObject jObject){

JSONArray jCountries = null;
try {
jCountries = jObject.getJSONArray("countries");
} catch (JSONException e) {
e.printStackTrace();
}

return getCountries(jCountries);
}

private List<HashMap<String, Object>> getCountries(JSONArray jCountries){
int countryCount = jCountries.length();
List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> country = null;

for(int i=0; i<countryCount;i++){
try {
country = getCountry((JSONObject)jCountries.get(i));
countryList.add(country);

} catch (JSONException e) {
e.printStackTrace();
}
}

return countryList;
}

private HashMap<String, Object> getCountry(JSONObject jCountry){

HashMap<String, Object> country = new HashMap<String, Object>();
String countryName = "";
String flag="";
String language = "";
String capital = "";
String currencyCode = "";
String currencyName = "";

try {
countryName = jCountry.getString("countryname");
flag = jCountry.getString("flag");
language = jCountry.getString("language");
capital = jCountry.getString("capital");
currencyCode = jCountry.getJSONObject("currency").getString("code");
currencyName = jCountry.getJSONObject("currency").getString("currencyname");

String details = "Language : " + language + "\n" +
"Capital : " + capital + "\n" +
"Currency : " + currencyName + "(" + currencyCode + ")";

country.put("country", countryName);
country.put("flag", R.drawable.blank);
country.put("flag_path", flag);
country.put("details", details);

} catch (JSONException e) {
e.printStackTrace();
}
return country;
}

}

完成后 gridview 显示图像不正确

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

activity_man.xml

<GridView
android:id="@+id/lv_countries"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
tools:context=".MainActivity" />

ly_layout.xml

<?xml version="1.0" encoding="utf-8"?>

<ImageView
android:id="@+id/iv_flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/str_iv_flag" />

enter image description here

最佳答案

在gridview中onClickListener获取点击item的数据

gridView.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View v, int positon,
long id) {
HashMap<String, Object> hm = gridView.getAdapter().getPosition(positon);

String imgPath = (String) hm.get("flag"); //get downloaded image path
Intent i = new Intent(yourActivityContext, NewActivityToDisplayImage.class); //start new Intent to another Activity.
i.putExtra("ClickedImagePath", imgPath ); //put image link in intent.
startActivity(i);

}
});

NewActivityToDisplayImage中获取图片路径并设置为imageview。

public class NewActivityToDisplayImage extends Activity {

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

String imagePath = getIntent().getStringExtra("ClickedImagePath"); //get image path from post activity
if (imagePath != null && !imagePath.isEmpty) {
File imgFile = new File(imagePath);
if (imgFile.exists()) {

Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);

}

}

}}

关于android - Gridview - 单击 gridview 项目以在 imageview 中显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12945794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com