我是非常新的android和java。Android的onclicklistener添加到JSONArray gridview
我的JSON有3個數據。
名, 圖像, 網址
我想我的片段,其爲GridView控件能夠點擊的JSON數組項目(點擊並打開URL數據的URL)。
如何添加onclicklistener到數組列表?
下面是我的代碼
public class OneFragment extends Fragment{
public OneFragment() {
// Required empty public constructor
}
//Web api url
public static final String DATA_URL = "https://www.xxxx.com/test/json.php";
//Tag values to read from json
public static final String TAG_IMAGE_URL = "image";
public static final String TAG_NAME = "name";
public static final String TAG_URL = "url";
//GridView Object
private GridView gridView;
//ArrayList for Storing image urls and titles
private ArrayList<String> images;
private ArrayList<String> names;
private ArrayList<String> url;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void getData(){
//Showing a progress dialog while our app fetches the data from url
//final ProgressDialog loading = ProgressDialog.show(getActivity(), "Please wait...","Fetching data...",false,false);
//Creating a json array request to get the json from our api
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//Dismissing the progressdialog on response
//loading.dismiss();
//Displaying our grid
showGrid(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
);
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding our request to the queue
requestQueue.add(jsonArrayRequest);
}
private void showGrid(JSONArray jsonArray){
//Looping through all the elements of json array
for(int i = 0; i<jsonArray.length(); i++){
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = jsonArray.getJSONObject(i);
//getting image url and title from json object
images.add(obj.getString(TAG_IMAGE_URL));
names.add(obj.getString(TAG_NAME));
url.add(obj.getString(TAG_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Creating GridViewAdapter Object
GridViewAdapter gridViewAdapter = new GridViewAdapter(getActivity(),images,names);
//Adding adapter to gridview
gridView.setAdapter(gridViewAdapter);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//setContentView(R.layout.activity_main);
View view = inflater.inflate(R.layout.fragment_json, container, false);
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_one, container, false);
images = new ArrayList<>();
names = new ArrayList<>();
//Calling the getData method
getData();
gridView = (GridView) view.findViewById(R.id.gridView);
return view;
}
}
能否請你的GridViewAdapter類添加到您的文章,請。我所做的是將一個監聽器添加到適配器中,當你調用它時,你實現了監聽器。 –