public class MainActivity extends Activity implements OnItemClickListener{
public TextView tv;
public ListView lv;
public ArrayList<HashMap<String, Object>> alNews;
public SimpleAdapter sadapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView) findViewById(R.id.textView1);
lv=(ListView) findViewById(R.id.listView1);
alNews=new ArrayList<HashMap<String, Object>>();
inital();
sadapter = new SimpleAdapter(this, alNews, R.layout.li_item3, new String[]{"img","title","date"}, new int[]{R.id.li_item3_Image,R.id.li_item3_Title,R.id.li_item3_DateTime});
lv.setAdapter(sadapter);
lv.setOnItemClickListener(this);
}
//初始化ArrayList
private void inital() {
// TODO Auto-generated method stub
int i = 0;
//添加3个hashmap到ArrayList中作为新闻内容
HashMap<String, Object> news1 = new HashMap<String, Object>();
news1.put("img", R.drawable.img);
news1.put("title", "巴基斯坦军方发言人:已组织一个师保护中巴经济走廊");
news1.put("date", "2017-3-15");
news1.put("id", i);i++;
alNews.add(news1);
HashMap<String, Object> news2 = new HashMap<String, Object>();
news2.put("img", R.drawable.img2);
news2.put("title", "多地争建国家中心城市 西安沈阳南京入围机会大");
news2.put("date", "2017-3-15");
news2.put("id", i);i++;
alNews.add(news2);
HashMap<String, Object> news3 = new HashMap<String, Object>();
news3.put("img", R.drawable.img3);
news3.put("title", "范冰冰李晨, 一次多久李晨的回答让范爷脸红了");
news3.put("date", "2017-3-15");
news3.put("id", i);i++;
alNews.add(news3);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
//取得被点击item的id
HashMap<String, Object> hm = alNews.get(arg2);
tv.setText(hm.get("id").toString());
}
}
simpleadapter有时候可以去除继承arrayadapter的繁琐,简单的实现比较方便。
ListView显示自定义新闻内容简单Adapter用法
最新推荐文章于 2018-09-21 18:57:50 发布