如何在ListView解析News API的title,点击后跳转展示对应description?
Hey there! Let's build this feature for your Android app step by step. First, let's take a look at the sample JSON response from the news.org API you provided:
Sample JSON Response
[ { "source": { "id": "the-hindu", "name": "The Hindu" }, "author": "", "title": "Questionable remedy: on the National Medical Commission Bill", "description": "Key sections of the National Medical Commission Bill need a rethink", "url": "http://www.thehindu.com/opinion/editorial/questionable-remedy/article22354009.ece", "urlToImage": "http://www.thehindu.com/static/theme/default/base/img/og-image.jpg", "publishedAt": null }, { "source": { "id": "the-hindu", "name": "The Hindu" }, "author": "", "title": "On the ledger: on fiscal consolidation", "description": "Expenditure data underline the government’s challenge on fiscal consolidation", "url": "http://www.thehindu.com/opinion/editorial/on-the-ledger/article22354014.ece", "urlToImage": "http://www.thehindu.com/static/theme/default/base/img/og-image.jpg", "publishedAt": null } ]
Step 1: Create a News Model Class
We need a model to map the JSON data to Java objects. We'll use Gson for easy parsing, so first add this dependency to your module-level build.gradle:
implementation 'com.google.code.gson:gson:2.10.1'
Now create the News class:
public class News { private Source source; private String author; private String title; private String description; private String url; private String urlToImage; private String publishedAt; // Getters for fields we need public String getTitle() { return title; } public String getDescription() { return description; } // Inner class to map the "source" object public static class Source { private String id; private String name; // Add getters here if you need to use source data later } }
Step 2: Fetch and Parse API Data
Let's use Volley for simple network requests. Add this dependency first:
implementation 'com.android.volley:volley:1.2.1'
In your main Activity, fetch the API data and parse it into a list of News objects:
import com.android.volley.Request; 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 com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.List; public class MainActivity extends AppCompatActivity { private ListView newsListView; private List<News> newsList; private NewsAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); newsListView = findViewById(R.id.news_list_view); RequestQueue queue = Volley.newRequestQueue(this); String apiUrl = "YOUR_NEWS_ORG_API_ENDPOINT"; // Replace with your actual API URL JsonArrayRequest jsonRequest = new JsonArrayRequest(Request.Method.GET, apiUrl, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { // Parse JSON array to List<News> Gson gson = new Gson(); Type newsListType = new TypeToken<List<News>>(){}.getType(); newsList = gson.fromJson(response.toString(), newsListType); // Set up adapter for ListView adapter = new NewsAdapter(MainActivity.this, newsList); newsListView.setAdapter(adapter); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, "Failed to load news", Toast.LENGTH_SHORT).show(); } }); queue.add(jsonRequest); } }
Step 3: Build a Custom ListView Adapter
First, create a layout for each list item (layout_list_item.xml):
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/news_title_tv" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" android:textSize="18sp" android:textColor="@android:color/black"/>
Then create the NewsAdapter class to populate the ListView:
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; public class NewsAdapter extends ArrayAdapter<News> { public NewsAdapter(Context context, List<News> newsItems) { super(context, 0, newsItems); } @Override public View getView(int position, View convertView, ViewGroup parent) { News currentNews = getItem(position); // Reuse existing view if available if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.layout_list_item, parent, false); } // Set title to the TextView TextView titleTv = convertView.findViewById(R.id.news_title_tv); titleTv.setText(currentNews.getTitle()); return convertView; } }
Step 4: Handle Item Clicks for Navigation
Add a click listener to the ListView in MainActivity's onCreate method (right after setting the adapter):
newsListView.setOnItemClickListener((parent, view, position, id) -> { News selectedNews = newsList.get(position); Intent intent = new Intent(MainActivity.this, DescriptionActivity.class); intent.putExtra("NEWS_DESCRIPTION", selectedNews.getDescription()); startActivity(intent); });
Step 5: Create the Description Activity
First, make the layout (activity_description.xml):
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp"> <TextView android:id="@+id/description_tv" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="16sp"/> </ScrollView>
Then create the DescriptionActivity class to display the description:
import android.content.Intent; import android.os.Bundle; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class DescriptionActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_description); TextView descriptionTv = findViewById(R.id.description_tv); Intent incomingIntent = getIntent(); if (incomingIntent != null && incomingIntent.hasExtra("NEWS_DESCRIPTION")) { String description = incomingIntent.getStringExtra("NEWS_DESCRIPTION"); descriptionTv.setText(description); } } }
Don't forget to register this activity in your AndroidManifest.xml:
<activity android:name=".DescriptionActivity"/>
内容的提问来源于stack exchange,提问作者harkirat singh

