As I have seen on previously asked questions, inside the custom adapter class (say, MyAdapter extends ArrayAdapter) they always use an inflated xml list-item layout. What I
ListView
extends AbsListView
which in turn extends AdapterView
which extends view group. So all the child of ListView
would be added to ViewGroup
. So to set the layout param, you can
use ViewGroup.LayoutParam while setting layout param for listLayout
.
Or try AbsListView.LayoutParams
for setting layout param for listLayout
Please try it and let me know if it worked.
Following code is working fine..
public class MainActivity1 extends Activity {
String[] wordlist = new String[] { "a", "b", "c" };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView list = new ListView(this);
list.setAdapter(new MyAdapter(this, wordlist));
setContentView(list);
}
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, String[] strings) {
super(context, -1, -1, strings);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout listLayout = new LinearLayout(MainActivity1.this);
listLayout.setLayoutParams(new AbsListView.LayoutParams(
AbsListView.LayoutParams.WRAP_CONTENT,
AbsListView.LayoutParams.WRAP_CONTENT));
listLayout.setId(5000);
TextView listText = new TextView(MainActivity1.this);
listText.setId(5001);
listLayout.addView(listText);
listText.setText(super.getItem(position));
return listLayout;
}
}
}
The problem was that by default Eclipse imports ViewGroup.LayoutParams
which are incompatible with the AbsListView.LayoutParams
which need to be used for setting layout param for view returned from the getView()
method.
Please check and let me know how it went..
To add to the above answer, setting id with a constant number is not a good idea.
Replace, listLayout.setId(5000);
with,listLayout.setId(View.generateViewId());
In case you are targeting API 16 and below, refer this.