以编程方式创建没有 xml 布局的列表视图
我发现这个示例创建了一个自定义列表视图:
public class UsersListActivity extends ListActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] statesList = {"listItem 1", "listItem 2", "listItem 3"};
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
statesList));
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"You selected : "+((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
但是,他们为每行使用 xml 布局。这是好的做法吗?如果我想以编程方式创建自己的布局并在适配器中使用它怎么办?
我想使用 xml 布局会更容易,但很高兴知道
I found this example to create a custom listview:
public class UsersListActivity extends ListActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] statesList = {"listItem 1", "listItem 2", "listItem 3"};
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
statesList));
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"You selected : "+((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
However, they are using a xml layout for each row. Is this good practice? What if I wanted to create my own layout programmatically and utilize it in the adapter?
I guess it would be easier just to use the xml layout, but it would be nice to know
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样更改适配器
change adapter like this
如果您不想要自定义视图,这是使用默认 Android 布局的最佳实践。如果您想使用自定义列表,您可以随时从 xml 中扩充它并根据列表项呈现数据。
This is the best practice to use the default android layout, if you do not want your customized view. and if you wanted to use your customized list you can always inflate it from xml and render the data according to list item.