Creating a ListView with custom list items programmatically in Android - no xml list item layout

為{幸葍}努か 提交于 2019-11-30 11:47:27

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..

Tony

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!