enter image description here这是我的list_item布局,我认为这个布局可能存在一些问题
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="@color/colorAccent"
android:textSize="18sp"
tools:text="india china tension" />
<TextView
android:id="@+id/summary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="@color/colorPrimaryDark"
android:textSize="22sp"
tools:text="Modi silent on china issue" />
</LinearLayout>
这是主要活动
package com.example.android.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating fake news reports
ArrayList<News> news = QueryWeb.extractNews();
//finding a layout reference{@link ListView}in the layout
ListView newsListView = (ListView) findViewById(R.id.list);
// Create a new adapter that takes list of earthquakes
final NewsAdapter adapter = new NewsAdapter(this, news);
// Set the adapter on the {@link ListView}
// so the list can be populated in the user interface
newsListView.setAdapter(adapter);
}
}
这是阵列适配器 package com.example.android.myapplication;
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;
/**
* Created by ammulu on 22-07-2017.
*/
public class NewsAdapter extends ArrayAdapter<News> {
/**
* Constructs a new {@link NewsAdapter}.
*
* @param context of the app
* @param news is the list of earthquakes, which is the data source of the adapter
*/
public NewsAdapter(Context context, List<News> news) {
super(context, 0, news);
}
/**
* Returns a list item view that displays information about news at the given position
* in the list of news
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if there is an existing list item view (called convertView) that we can reuse,
// otherwise, if convertView is null, then inflate a new list item layout.
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.newslist_item, parent, false);
}
// Find the news at that position
News currentNews = getItem(position);
// Find the TextView with view ID title
TextView titleView = (TextView) listItemView.findViewById(R.id.title);
//Display the title
titleView.setText(currentNews.getTitle());
// Find the TextView with view ID summary
TextView summaryView = (TextView) listItemView.findViewById(R.id.summary);
//Display the summary
summaryView.setText(currentNews.getSummary());
//Return the list item that is showing the appropriate data
return listItemView;
}
}
Json解析代码我认为问题在这里
package com.example.android.myapplication;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public final class QueryWeb {
/**
* sample json response for news query
*/
private static final String SAMPLE_JSON_RESPONSE = "{\\\"status\\\":\\\"ok\\\",\\\"source\\\": \\\"techcrunch\\\",\\\"sortBy\\\": \\\"top\\\",\"articles\": [{\\\"author\\\": \\\"Alexandra Ames\\\",\\\"title\\\": \\\"Coverage\\\",\\\"description\\\":\\\"Coverage | Sessions: Robotics - Cambridge, MA - July 17, 2017\\\",\\\"url\\\": \\\"https:\\/\\/techcrunch.com\\/events\\/sessions-robotics\\/coverage\\/\\\",\\\"urlToImage\\\": \\\"https:\\/\\/s0.wp.com\\/wp-content\\/themes\\/vip\\/techcrunch-2013\\/assets\\/images\\/techcrunch.opengraph.default.png\\\",\\\"publishedAt\\\": \\\"2017-07-14T00:02:35Z\\\"},\n" +
"{\\\"author\\\": \\\"Matthew Lynley\\\",\\\"title\\\": \\\"Dropbox CTO Aditya Agarwal is leaving\\\",\\\"description\\\": \\\"Aditya Agarwal, who came to Dropbox via its acquisition of Cove way back in 2012 and was given the CTO role last year, will be leaving the company. Agarwal..\\\",\\\"url\\\": \\\"https:\\/\\/techcrunch.com\\/2017\\/07\\/21\\/dropbox-cto-aditya-agarwal-is-leaving\\/\\\",\\\"urlToImage\\\": \\\"https:\\/\\/tctechcrunch2011.files.wordpress.com\\/2017\\/07\\/dropbox-fb-departure.jpg?w=764&h=400&crop=1\\\",\\\"publishedAt\\\":\\\"2017-07-21T17:18:11Z\\\"}],\n" ;
/**
* Create a private constructor because no one should ever create a {@link QueryWeb} object.
* This class is only meant to hold static variables and methods, which can be accessed
* directly from the class name QueryUtils (and an object instance of QueryWeb is not needed).
*/
private QueryWeb() {
}
/**
* Return a list of {@link News} objects that has been built up from
* parsing a JSON response.
*/
public static ArrayList<News> extractNews() {
// Create an empty ArrayList that we can start adding earthquakes to
ArrayList<News> newsArray = new ArrayList<>();
// Try to parse the SAMPLE_JSON_RESPONSE. If there's a problem with the way the JSON
// is formatted, a JSONException exception object will be thrown.
// Catch the exception so the app doesn't crash, and print the error message to the logs.
try {
// TODO: Parse the response given by the SAMPLE_JSON_RESPONSE string and
// build up a list of Earthquake objects with the corresponding data.
JSONObject baseJsonResponse = new JSONObject(SAMPLE_JSON_RESPONSE);
JSONArray titleArray = baseJsonResponse.getJSONArray("articles");
for(int i=0; i < titleArray.length(); i++ ){
JSONObject newRead = titleArray.getJSONObject(i);
String title = newRead.getString("title");
String summary = newRead.getString("description");
// Create a new {@link News} object with the magnitude, location, time,
// and url from the JSON response.
News news = new News( title, summary);
newsArray.add(news);
}
} catch (JSONException e) { // If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryWeb", "Problem parsing news JSON results", e);
}
// Return the list of earthquakes
return newsArray;
}
}
activty主xml布局
<?xml version="1.0" encoding="utf-8"?>
<!-- Layout for a list of news-->
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dividerHeight="1dp"/>
答案 0 :(得分:0)
此适配器表示的数据集中有多少项。
public NewsAdapter(Context context, List<News> news) {
super(context, 0, news);
}
@Override
public int getCount() {
return news.size();
}
答案 1 :(得分:0)
在某些情况下,LayoutInflater与父级无法正常工作。所以改变字符串
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.newslist_item, parent, false);
为:
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.newslist_item, null);
答案 2 :(得分:0)
好的,首先你需要在适配器中创建一个本地列表。
List<News> news = new ArrayList();
然后在你的构造函数中试试这个
public NewsAdapter(Context context, List<News> news) {
super(context, 0, news);
this.news = news
}
然后覆盖此
@Override
public int getCount() {
return news.size();
}
这是在模型类中设置值的方法。
News news = new News( title, summary);
news.setTitle(title);
news.setSummary(summary);
然后最后将它们添加到新闻类型列表
newsArray.add(news)
最后是适配器
titleView.setText(news.get(position).getTitle));
summaryView.setText(news.get(position).getSummary);