在初级阶段,我们常对listview的适配器都是在一个activity类中全部写满。当你接触项目多了,你会发现大神都把各种适配器放一个包里,要用直接传如相关参数到适配器的构造方法设置ListView。今天做了个简单的demo,对于菜鸟理解多态有帮助。在MainActivity中代码如下
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView) findViewById(R.id.listView1);
MyAdapter my = new MyAdapter(5, MainActivity.this);
list.setAdapter(my);
}
@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;
}
}
在MyAdapter类中继承和代码如下
public class MyAdapter extends BaseAdapter{
private LayoutInflater inflater;
private int i;
public MyAdapter(int i,Context context) {
this.i = i;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return 10;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View inflate = inflater.inflate(R.layout.item, null);
return inflate;
}
}
在MainActivity中 MyAdapter my = new MyAdapter(5, MainActivity.this);就执行了MyAdapter中的构造方法,一般只会执行到MyAdapter的构造方法,但由于BaseAdapter的特殊性,它自动调用getcount()等方法。这样就通过BaseAdapter适配器设置了ListView的相关设置。
结合子类父类和LIstView适配器相关设置,初步体验类的多态。