【问题标题】:Android Adapter implementationAndroid 适配器实现
【发布时间】:2017-04-28 16:35:36
【问题描述】:

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

这是我试图弄清楚的程度:

    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 和 listview

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:weightSum="1">


    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

   <ListView
       android:id="@+id/listv"
       android:layout_width="match_parent"
       android:layout_height="89dp"/>


</LinearLayout>

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

【问题讨论】:

  • 如果您使用 ArrayAdapter 来填充 listview ,则无需编写任何代码。此类中有一个默认实现。
  • 您好,感谢您花时间帮助我。我用我正在尝试的一些简单的东西更新了上面的代码。如何使用适配器在列表视图中显示凌空响应?

标签: android listview android-adapter


【解决方案1】:

我认为您对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),它是由应用程序自动管理的,所以不用担心。请记住在将列表传递给适配器之前检查您的列表是否为空或 null。

【讨论】:

  • 知道了。感谢您的帮助。请看一下我更新的代码。我添加了凌空,我得到了 api、响应、循环,然后在 textview 中显示它并且它可以工作。现在,如何将其添加到列表视图中?使用 myAdapter.add(results?data?add the object) 如何让凌空响应显示在列表视图中?
  • 这是另一个问题,您必须接受这个问题并在其他问题中提出。谢谢。
猜你喜欢
  • 2015-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多