将列表<data>传递给自定义适配器

时间:2015-09-29 11:46:29

标签: java android twitter getview

我通过编写以下代码创建了自定义适配器列表:

public class TweetListActivity extends ListActivity {

private ListView tweetListView;
private ArrayAdapter tweetItemArrayAdapter;
private final List<Tweet> tweets = new ArrayList<Tweet>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tweet_list);
    for (int i = 1; i < 21; i++)

    {
        Tweet tweet = new Tweet();
        tweet.setTitle("A nice header for Tweet # " + i);
        tweet.setBody("Some random body text for the tweet # " + i);
        tweets.add(tweet);
    }
    tweetItemArrayAdapter = new TweetAdapter(this,tweets);

    setListAdapter(tweetItemArrayAdapter);
}
}

TweetAdapter的代码如下

public class TweetAdapter extends ArrayAdapter<Tweet> 
{
    private List<Tweet> tweetslocal;
    private Context context;
    private LayoutInflater inflater;

public TweetAdapter(Activity activity, List<Tweet> tweets) {
    super(activity, R.layout.row_tweet, tweets);
    inflater = activity.getWindow().getLayoutInflater();
    tweetslocal = tweets;
}

@Override
public Tweet getItem(int arg0) {
    return tweetslocal.get(arg0);
}

@Override
public long getItemId(int arg0) {
    return arg0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = inflater.inflate(R.layout.row_tweet, parent, false);
    TextView tweetTitle = (TextView) row.findViewById(R.id.tweetTitle);
    Tweet tweet = tweetslocal.get(position);
    tweetTitle.setText(tweet.getTitle());
    TextView tweetBody = (TextView) row.findViewById(R.id.tweetBody);
    tweetBody.setText(tweet.getBody());
    return row;
}
}

但是,我没有得到理想的输出。该列表显示所有带有标题20的推文,而不是从tweet1到tweet 20的增量推文。

2 个答案:

答案 0 :(得分:1)

查看您的代码,我发现您已将推文列表传递给TweetAdapter

TweetAdapter中,声明Tweet的列表:

    private List<Tweet> tweets;

然后,确保您的构造函数如下所示:

    public TweetAdapter(Context ctx, List<Tweet> tweets) {
        this.context = ctx; //Context == activity
        this.tweets = tweets;
    }

现在,在您的getView()中,您可以执行此操作:

final Tweet currentTweet = tweets.get(position);

希望这有帮助!

答案 1 :(得分:0)

如果你的TweetAdapter中的数组名为tweets,那么获取这样的推文对象:

public View getView(int position, View convertView, ViewGroup parent){

    Tweet tweet = tweets.get(position);
    // TODO using tweet.
}

你是说这个吗?