Android适配器实现

时间:2017-04-28 16:35:36

标签: android listview android-adapter

我是Android新手。我遇到的一个问题是ArrayAdapter实现。阅读这么多教程,需要确保我理解正确。

这是我试图解决的问题:

require 'rails_helper'
RSpec.describe "Users", type: :request do
  let(:user) { create(:user) }

  describe "GET /users/:id" do
    it "takes a username as the id param" do
       get user_path(user.user_name)
       expect(response).to be_successful
    end
  end
end

我的观点有textview和listview

    package hfad.com.adapters;


import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity {

    //thorntech.com parsing jsonandroid using colley library
    TextView results;
    // URL of object to be parsed
    String JsonURL = "https://raw.githubusercontent.com/ianbar20/JSON-Volley-Tutorial/master/Example-JSON-Files/Example-Array.JSON";
    // This string will hold the results
    String data = "";
    // Defining the Volley request queue that handles the URL request concurrently

    ListView myList;

    RequestQueue requestQueue;

    //Adding adapter and assign it -set- to a listview



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Creates the Volley request queue
        requestQueue = Volley.newRequestQueue(this);

        // Casts results into the TextView found within the main layout XML with id jsonData
        results = (TextView) findViewById(R.id.textView);
        myList = (ListView) findViewById(R.id.listv);
        final ArrayAdapter myAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
        ListView myList = (ListView) findViewById(R.id.listv);
        myList.setAdapter(myAdapter);

        // Creating the JsonArrayRequest class called arrayreq, passing the required parameters
        //JsonURL is the URL to be fetched from
        JsonArrayRequest arrayreq = new JsonArrayRequest(JsonURL,
                // The second parameter Listener overrides the method onResponse() and passes
                //JSONArray as a parameter
                new Response.Listener<JSONArray>() {

                    // Takes the response from the JSON request
                    @Override
                    public void onResponse(JSONArray response) {


     /*        ==================================================================   */
/*  //////////////////////// Example using TextView and it works//////////////////////  */
                        //url https://reqres.in/api/users?page=2
                        try {
                            // Retrieves first JSON object in outer array
                            JSONObject colorObj = response.getJSONObject(0);
                            // Retrieves "colorArray" from the JSON object
                            JSONArray colorArry = colorObj.getJSONArray("colorArray");
                            // Iterates through the JSON Array getting objects and adding them
                            //to the list view until there are no more objects in colorArray
                            for (int i = 0; i < colorArry.length(); i++) {
                                //gets each JSON object within the JSON array
                                JSONObject jsonObject = colorArry.getJSONObject(i);

                                // Retrieves the string labeled "colorName" and "hexValue",
                                // and converts them into javascript objects
                                String color = jsonObject.getString("colorName");
                                String hex = jsonObject.getString("hexValue");

                                // Adds strings from the current object to the data string
                                //spacing is included at the end to separate the results from
                                //one another
                                data += "\n"+ "Color Number " + (i + 1) + "\n"+"Color Name: " + color +
                                        "\n"+ "nHex Value : " + hex + "nnn"+ "\n";

                            }
                            // Adds the data string to the TextView "results"
                            results.setText(data);

                        }



/*    ============================================================  */
/* ////////////////////////// Example 2 working ///////////////////////////////   */
                        //url https://raw.githubusercontent.com/ianbar20/JSON-Volley-Tutorial/master/Example-JSON-Files/Example-Array.JSON
                       /*
                       try {
                           // Retrieves first JSON object in outer array
                           JSONObject colorObj = response.getJSONObject(0);
                           // Retrieves "colorArray" from the JSON object
                           JSONArray colorArry = colorObj.getJSONArray("colorArray");
                           // Iterates through the JSON Array getting objects and adding them
                           //to the list view until there are no more objects in colorArray
                           for (int i = 0; i < colorArry.length(); i++) {
                               //gets each JSON object within the JSON array
                               JSONObject jsonObject = colorArry.getJSONObject(i);

                               // Retrieves the string labeled "colorName" and "hexValue",
                               // and converts them into javascript objects
                               String color = jsonObject.getString("colorName");
                               String hex = jsonObject.getString("hexValue");

                               // Adds strings from the current object to the data string
                               //spacing is included at the end to separate the results from
                               //one another
                               data += "\n"+ "Color Number " + (i + 1) + "\n"+"Color Name: " + color +
                                      "\n"+ "nHex Value : " + hex + "nnn"+ "\n";
                           }
                           // Adds the data string to the TextView "results"
                           results.setText(data);
                       }

                       */
                        // Try and catch are included to handle any errors due to JSON
                        catch (JSONException e) {
                            // If an error occurs, this prints the error to the log
                            e.printStackTrace();
                        }
                    }
                },
                // The final parameter overrides the method onErrorResponse() and passes VolleyError
                //as a parameter
                new Response.ErrorListener() {
                    @Override
                    // Handles errors that occur due to Volley
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Volley", "Error");
                    }
                }

        );
        // Adds the JSON array request "arrayreq" to the request queue
        requestQueue.add(arrayreq);
        }}

那么我如何在列表视图中显示我的截击响应而不是textview(按预期显示响应) 在同一视图中有textview和listview被认为是错误的吗? 如果我这样做:myAdapter.add(结果),应用程序崩溃。你说除了获取列表并将适配器设置为该列表之外我不需要任何其他内容。

1 个答案:

答案 0 :(得分:0)

我认为你不太了解Adapters的主要功能。让我向你解释一下:

ArrayAdapter类是Adapter(从BaseAdapter扩展而来),与ArraysLists一起使用,您可以在不使用的情况下使用它必须手动调用getView()方法。要使它工作,您需要在创建过程中传递3个参数:

1 - 您的context

2 - 列表每行的Layout

3 - 您的数据采用ListArray格式

<强>例如

adapter=new ArrayAdapter(this, R.layout.item_layout, items);

在这种情况下,Android本身会检查列表的大小,获取所有数据并在视图的每一行中输入,然后以列表形式返回给您。

您担心的getView()方法属于ArrayAdapter超类(BaseAdapter)并且由应用自动管理,因此请不要担心。在将列表传递给适配器之前,请记住检查列表是否为空或为空。