java和android非常新,但我想我需要一个布局inflater,我试图实现它但失败了,我删除了那段代码。
我可以将对象转换为字符串数组,并使用ArrayAdapter
循环布局,将字符串分配给textView
所以ArrayAdapter
是有限的
ListAdapter dribbbleFeedAdapter = new ArrayAdapter<String>(MainActivity.this, R.layout.feed_card, R.id.info_text, titleArr);
我只能传递上下文,布局,textView和字符串数组。
我想要做的是将图像和其他数据传递到该布局的视图中。所以我的问题是我如何构建适配器,以便我可以将对象的值分配给视图ID?
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// GET Json and use adapter ListView
Ion.with(this)
.load("http://api.dribbble.com/shots/everyone")
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
@Override
public void onCompleted(Exception e, JsonObject result) {
// SET Titles Array
List<String> titles = new ArrayList<String>();
// BUILD THE ARRAY
JsonArray shots = result.getAsJsonArray("shots");
for (int i = 0; i < shots.size(); i++) {
String title = shots.get(i).getAsJsonObject().get("title").getAsString();
titles.add(title);
}
String[] titleArr = new String[titles.size()];
titleArr = titles.toArray(titleArr);
// TODO: Put more data into the feed_card
//dribbbleImage.setImageResource(R.drawable.icon_1);
ListAdapter dribbbleFeedAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.feed_card, R.id.info_text, titleArr);
ListView dribbbleDataListView = (ListView) findViewById(R.id.dribbbleFeedListView);
dribbbleDataListView.setAdapter(dribbbleFeedAdapter);
}
});
}
}
答案 0 :(得分:2)
您应该编写自己的Adapter extends BaseAdapter。
就像下面的代码一样:
public class TestAdapter extends BaseAdapter {
public TestAdapter(Context context, List<Data> dataList) {
this.dataList = dataList;
this.context = context;
}
private List<Data> dataList;
private Context context;
@Override
public int getCount() {
return dataList.size();
}
@Override
public Object getItem(int position) {
return dataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(layout.your_list_item_layout, parent, false);
holder = new View();
holder.tv_title = convertView.findViewById(R.id.title);
holder.iv_data = convertView.findViewById(R.id.data);
convertView.setTag(holder);
}else {
holder = (ViewHolder)convertView.getTag();
}
Data data = dataList.get(position);
holder.tv_title.setText(data.getTitle());
return convertView;
}
private class ViewHolder {
TextView tv_title;
ImageView iv_data;
}
}