Android适配器实现



我是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);
        }}

我的视图有一个文本视图和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>

因此,我如何在listView中显示我的射击响应,而不是文本视图(它以预期显示响应(在同一视图中有一个文本视图和listView认为错误吗?如果我这样做:myadapter.add(结果(,应用程序崩溃。您说除了获取列表并将适配器设置为该列表之外,我不需要其他任何东西。

我认为您不太了解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 SuperClass(BaseAdapter(,并且该方法由应用程序自动管理,因此不必担心。请记住,在将其传递给适配器之前,请检查您的列表是否没有空或无空。

最新更新