如何在水平列表视图中显示从 Web 服务检索到的 Json 文本和图像?

How to display the Json text and image retrieved from web service in horizontal list view?

我正在开发 Android 应用程序,我想在其中以水平列表视图显示从 Web 服务检索到的 json 格式文本和图像。我正在将 json 格式的数据存储到 ArrayList

activity_main.xml

  <android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:numColumns="auto_fit"
    android:horizontalSpacing="4dp"
    android:stretchMode="columnWidth"
    android:id="@+id/gallery_child_list"
    android:background="#E4E4E4"
    android:verticalSpacing="4dp" />

主要活动

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from activity_main.xml
    setContentView(R.layout.activity_main);
    // Execute DownloadJSON AsyncTask
    new DownloadJSON().execute();
}

// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(MainActivity.this);
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();
        // Retrieve JSON Objects from the given URL address
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("YOUR_URL");
            HttpResponse response = client.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            String json = EntityUtils.toString(resEntity);
            JSONObject jObject = new JSONObject(json);
            // Locate the array name in JSON
                HashMap<String, String> map = new HashMap<String, String>();
            JSONObject jsonobject = jObject.optJSONObject("online");
            for (int i = 0; i < jObject.length(); i++) {
                    map.put("date", jsonobject.getString("men"));
                    map.put("flag", jsonobject.getString("kids"));
                    map.put("flag", jsonobject.getString("women"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
                } catch (Exception e1) {
                e1.printStackTrace();
            }
        return null;
    }
        @Override
    protected void onPostExecute(Void args) {
        viewPager = (ViewPager) findViewById(R.id.pager);
        adapter = new ViewPagerAdapter(MainActivity.this, arraylist);
        viewPager.setAdapter(adapter);
        // Close the progressdialog
        mProgressDialog.dismiss();
        adapter.notifyDataSetChanged();

    }
}

viewpageradapter

public class ViewPagerAdapter extends PagerAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();

public ViewPagerAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
    this.context = context;
    data = arraylist;
    imageLoader = new ImageLoader(context);
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == ((RelativeLayout) object);
}

@Override
public int getCount() {
    return data.size();
}

        @Override
public Object instantiateItem(ViewGroup container, int position) {

    // Declare Variables
    ImageView imgflag;

    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View itemView = inflater.inflate(R.layout.viewpager_item, container,false);

    // Locate the ImageView in viewpager_item.xml
    imgflag = (ImageView) itemView.findViewById(R.id.flag);
            // Capture position
            resultp = data.get(position);
            // Capture position and set results to the ImageView
            // Passes flag images URL into ImageLoader.class
            imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), imgflag);
            // Add viewpager_item.xml to ViewPager
            ((ViewPager) container).addView(itemView);

    return itemView;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    // Remove viewpager_item.xml from ViewPager
    ((ViewPager) container).removeView((RelativeLayout) object);

}
}

首先是如何显示水平的ListView。我想推荐你使用 RecyclerView 来使 listView 显示更流畅。那么如何水平显示recyclerView呢?这是我一步一步的教程。

首先,在xml文件中应该是这样的:

  <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:scrollbars="vertical" />

其次,在Activity的onCreate中应该是这样的:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerViewItem = (RecyclerView) findViewById(R.id.recyclerView);
    LinearLayoutManager itemslayoutManager = new LinearLayoutManager(getApplicationContext());
    itemslayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    recyclerViewItem.setLayoutManager(itemslayoutManager);
    SampleAdapter sampleAdapter = new SampleAdapter(List<SampleData>);
    recyclerViewItem.setAdapter(sampleAdapter);
    return true;
    }

要解析 JSON,您应该使用名为的库:Retrofit 而不是 AsyncTask 试试这个: Retrofit