Android, how to populate a CharSequence array dynamically (not initializing?)

时间秒杀一切 提交于 2019-12-01 02:14:40
David Guerrero

Use a List object to manage items and when you have all the elements then convert to a CharSequence. Something like this:

List<String> listItems = new ArrayList<String>();

listItems.add("Item1");
listItems.add("Item2");
listItems.add("Item3");

final CharSequence[] charSequenceItems = listItems.toArray(new CharSequence[listItems.size()]);
Heiko Rupp

You are almost there. You need to allocate space for the entries, which is automatically done for you in the initializing case above.

CharSequence cs[];

cs = new String[2];

cs[0] = "foo"; 
cs[1] = "bar"; 

Actually CharSequence is an Interface and can thus not directly be created, but String as one of its implementations can.

You can also use List, to have a dynamic number of members in the array(list :)):

List<CharSequence>  cs = new ArrayList<CharSequence>();

cs.add("foo"); 
cs.add("bar"); 

If you want to use array, you can do:

CharSequence cs[];

cs = new String[2];

cs[0] = "foo"; 
cs[1] = "bar"; 
Romain Piel

If you want it to be dynamical, you should think in an another structure and then convert it to a CharSequence when you need. Alternatively, that thread can be useful.

You could use ArrayList instead of raw arrays since need to add items dynamically.

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