我想创建一个列表视图并用字符串数组填充它,所以我用ArrayAdapter对它进行了调整。这是我的代码。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String str[]={"A","S","S","P","S","S","P","Bl","Ra","M","a","a","c","s","s","ds"};
ArrayAdapter<String> ad=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,str);
ListView lv= (ListView)findViewById(R.id.lv);
lv.setAdapter(ad);
}
}
我想知道如果BaseAdapter是ArrayAdapter的超类,那么如何使用BaseAdapter制作相同的程序?
答案 0 :(得分:1)
您必须像这样实施BaseAdapter
:
public class CustomAdapter extends BaseAdapter {
private String[] data;
public CustomAdapter(String[] data) {
this.data = data;
}
@Override
public int getCount() {
return data.length;
}
@Override
public Object getItem(int position) {
return data[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater li = (LayoutInflater) convertView.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = li.inflate(android.R.layout.simple_list_item_1, null);//set layout for displaying items
TextView txt = (TextView) view.findViewById(android.R.id.text1);//get id for Text view
txt.setText(data[position]);
return view;
}
}