作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要帮助..
我有HomeFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by Administrator on 9/7/2015.
*/
@SuppressWarnings("deprecation")
public class HomeFragment extends Fragment {
public static HomeFragment newInstance() {
HomeFragment fragment = new HomeFragment();
return fragment;
}
public HomeFragment () {
}
Boolean InternetAvailable = false;
Seocnd detectconnection;
ImageView imageView, imageView3;
ProgressBar progressBar, progressBar2, progressBar3;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "http://joehamirbalabadan.com/android/android/";
String homeJSON, catid, catname;
JSONArray jsonarray;
LinearLayout layout;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.homelayout, container, false);
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
progressBar = (ProgressBar) rootView.findViewById(R.id.loading);
progressBar.setVisibility(View.VISIBLE);
imageView = (ImageView) rootView.findViewById(R.id.imageView);
//Glide.with(getActivity()).load("http://joehamirbalabadan.com/android/android/imghome/index1.png").diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.drawable.indexloading).into(imageView);
Glide.with(getActivity())
.load("http://joehamirbalabadan.com/android/android/imghome/index1.png").diskCacheStrategy(DiskCacheStrategy.ALL)
.into(new GlideDrawableImageViewTarget(imageView) {
@Override
public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
super.onResourceReady(drawable, anim);
progressBar.setVisibility(View.GONE);
}
});
progressBar2 = (ProgressBar) rootView.findViewById(R.id.loading2);
progressBar2.setVisibility(View.VISIBLE);
layout = (LinearLayout) rootView.findViewById(R.id.linear);
getCategory();
progressBar3 = (ProgressBar) rootView.findViewById(R.id.loading3);
progressBar3.setVisibility(View.VISIBLE);
imageView3 = (ImageView) rootView.findViewById(R.id.imageView3);
//Glide.with(getActivity()).load("http://joehamirbalabadan.com/android/android/imghome/index3.png").diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.drawable.indexloading).into(imageView3);
Glide.with(getActivity())
.load("http://joehamirbalabadan.com/android/android/imghome/index3.png").diskCacheStrategy(DiskCacheStrategy.ALL)
.into(new GlideDrawableImageViewTarget(imageView3) {
@Override
public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
super.onResourceReady(drawable, anim);
progressBar3.setVisibility(View.GONE);
}
});
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getCategory() {
class DownloadJSON extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(SERVER_ADDRESS + "categories.php");
// Depends on your web service
//httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
@Override
protected void onPostExecute(String result) {
homeJSON = result;
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(result);
jsonarray = jsonObj.getJSONArray("result");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject p = jsonarray.getJSONObject(i);
ImageView thumbView = new ImageView(getActivity());
catid = p.getString("categories_id");
catname = p.getString("categories_name");
thumbView.setId(i);
thumbView.setPadding(0, 0, 10, 0);
/*Glide.with(getActivity()).load(p.getString("categories_image")).override(336, 269).diskCacheStrategy(DiskCacheStrategy.ALL).into(thumbView);*/
Glide.with(getActivity())
.load(p.getString("categories_image")).diskCacheStrategy(DiskCacheStrategy.ALL)
.override(336, 269)
.into(new GlideDrawableImageViewTarget(thumbView) {
@Override
public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
super.onResourceReady(drawable, anim);
progressBar2.setVisibility(View.GONE);
}
});
layout.addView(thumbView);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
}
DownloadJSON g = new DownloadJSON();
g.execute();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(1);
}
}
我想将 OnClickListener 添加到此代码中..
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject p = jsonarray.getJSONObject(i);
ImageView thumbView = new ImageView(getActivity());
catid = p.getString("categories_id");
catname = p.getString("categories_name");
thumbView.setId(i);
thumbView.setPadding(0, 0, 10, 0);
Glide.with(getActivity())
.load(p.getString("categories_image")).diskCacheStrategy(DiskCacheStrategy.ALL)
.override(336, 269)
.into(new GlideDrawableImageViewTarget(thumbView) {
@Override
public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
super.onResourceReady(drawable, anim);
progressBar2.setVisibility(View.GONE);
}
});
layout.addView(thumbView);
}
单击图像后,我想将 HomeFragment.java 更改为 CategoryFragment.java 并传递 catid 和 catname 到我的 CategoryFragment.java
这是我的CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by Administrator on 9/18/2015.
*/
@SuppressWarnings("deprecation")
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance(String id,String name) {
CategoryFragment fragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
fragment.setArguments(bundle);
return fragment;
}
public CategoryFragment () {
}
String cid;
String cname;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "http://joehamirbalabadan.com/android/android/";
String myJSON;
JSONArray jsonarray;
GridView productgridview;
GridViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
public static String products_id = "products_id";
public static String products_name = "products_name";
public static String products_price = "products_price";
public static String products_image = "products_image";
Boolean InternetAvailable = false;
Seocnd detectconnection;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
if(getArguments() != null) {
String catid = getArguments().getString("id");
String catname = getArguments().getString("name");
cid = catid;
cname = catname;
}
productgridview = (GridView) rootView.findViewById(R.id.productgridview);
//new DownloadJSON().execute();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getProduct();
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getProduct(){
class DownloadJSON extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle(cname);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
@Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("cid", cid));
dataToSend.add(new BasicNameValuePair("cname", cname));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(SERVER_ADDRESS + "products.php");
// Depends on your web service
//httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
httppost.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
@Override
protected void onPostExecute(String result){
myJSON=result;
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray("products");
arraylist = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
adapter = new GridViewAdapter(getActivity(), arraylist);
// Set the adapter to the GridView
productgridview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
DownloadJSON g = new DownloadJSON();
g.execute();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
最佳答案
您可以为此使用“标签”功能。
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject p = jsonarray.getJSONObject(i);
ImageView thumbView = new ImageView(getActivity());
catid = p.getString("categories_id");
catname = p.getString("categories_name");
//Here you can use HashMap, Custom Object also
String catDetailsString = catid + "," + catname;
tumbView.setTag(catDetailsString);
thumbView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String catDetails = (String) view.getTag();
String[] catDetailsArray = catDetails.split(",");
String categoryId = catDetailsArray[0];
String categoryName = catDetailsArray[1];
//Passinng Category Id and name to CategoryFragment
CategoryFragment categoryFragment = CategoryFragment.newInstance(categoryId, categoryName);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, categoryFragment)
.commit();
}
});
//Your code goes here
}
关于java - 如何在我的 for 循环线性布局 ImageView 中添加 OnClickListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33006718/
我是一名优秀的程序员,十分优秀!