谁能给出一个正确的例子,说明如何将 URL 中的图像和文本显示到 viewPager 中。我找不到任何可以从中得到想法的完整示例。我是 android 的新手,我们将不胜感激。
最佳答案
我们可以把它分成几部分
<强>1。从url中获取Json数据
you can use volley plugin to get json data from url, for adding plugin to android studio do the following
在 android studio 中,打开 Gradle Scripts 下的 build.gradle(Module:app) 文件,在 dependencies 中添加以下行并同步 Gradle
compile 'com.android.volley:volley:1.0.0'
<强>2。将响应值设置为 View (即图像 url 到 imageview,文本值到 edittext/textview 等)
you can use Picasso plugin to set an image to Imageview from url. you need to add the following line in build.gradle (Module:app) file .it is same as the procedures we done to add volley plugin. and sync the gradle
compile 'com.squareup.picasso:picasso:2.5.2'
让我们假设您的 Json Data In url 如下所示
{
"image_url": "https://www.gstatic.com/webp/gallery/4.sm.jpg",
"text_value": "some text"
}
在您的 java 页面中执行此操作:-
String url = "your_url_to_the_json_data";
// Request a string response,
// you will get response from url as string
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// you will get the response as string here
//String response holds the response from url
Log.d("response from url",response);
try
{
//converting string response to json object
JSONObject jsonObject = new JSONObject(response);
String my_text_value=jsonObject.getString("text_value");
String my_image_url=jsonObject.getString("image_url");
// now you got your text and image urls in the above strings
//now set it your imageview and edittext
my_edittext.setText(my_text_value);
//An external plugin named picasso is used to set image to an imageview from pic url
Picasso.with(this).load(my_image_url).into(my_imageview);
}
catch (JSONException e) {
Toast.makeText(getActivity(), "json exception",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//this part will work if there is any error
System.out.println("Something went wrong!");
error.printStackTrace();
}
})
{
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//you can pass parameters ,if you want to
//in this case its not needed
//params.put("parameter1", value1);
// params.put("parameter2",value2);
return params;
}
};
// Add the request to the queue
Volley.newRequestQueue(this).add(stringRequest);
不要忘记用您的值更改以下值
* `String url = "your_url_to_the_json_data";`
change `"your_url_to_the_json_data"` with your url
* `my_edittext.setText(my_text_value);`
change `my_edittext` to your edittext or textView object
* `Picasso.with(this).load(my_image_url).into(my_imageview);`
change `my_imageview` to your imageview object
关于android - 如何使用 JSON 从 url 将图像和文本显示到 viewpager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41277508/