效果图:
MainActivity中
public class MainActivity extends Activity {
private ListView lv_test;
private View vHead;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv_test = (ListView)findViewById(R.id.lv_test);
// 头布局
vHead= View.inflate(this, R.layout.item_main, null);
ImageView iv_img= (ImageView) vHead.findViewById(R.id.iv_img);
// 头布局放入listView中
lv_test.addHeaderView(vHead);
// 绑定适配器
String [] arrarStr={"刘备","关羽","张飞","马超","黄忠"};
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrarStr);
lv_test.setAdapter(adapter);
myOnClick();
}
private void myOnClick() {
lv_test.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "position:"+position, Toast.LENGTH_SHORT).show();
}
});
}
}
布局文件
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="android.zhh.com.MainActivity">
android:id="@+id/lv_test"
android:layout_width="match_parent"
android:layout_height="wrap_content">
item_main.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
android:id="@+id/iv_img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@mipmap/liuss"
/>
源码下载: