我正在使用 ListView 来显示一些 JSON 数据,并希望根据其类型(Artist、Release、Label...)显示每个结果。
我将使用由每种结果类型实现的接口(interface):
public interface Result {
public Int getId();
public String getThumb();
// ...
}
我想知道这些选择中哪一个是最好的解决方案(我对更好的事情持开放态度,这正是我的想法):
- 在接口(interface)中创建一个
enum ResultType
(因此继承的类必须返回它们自己的值,如getType()
中的ResultType.ARTIST
> 方法 - 使用
isInstance()
检查实例类型
我想知道什么是执行与此 C 代码(函数指针数组)等效的最佳方法,因为我想避免使用许多 if
/else
语句。
typedef struct s_func {
const char *type_name;
void* (*func_pointer)(void *result_infos);
} t_func;
static t_func type_array[] = {
{"artist", artist_function},
{"label", label_function},
// ....
{NULL, NULL}
}
void check_type(const char *type_string)
{
int i, j = 0;
char *key_value;
// compare string and array key
while (type_array && type_array[i][0]) {
key_value = type_array[i][0];
// if key match
if (type_string && strncmp(type_string, key_value, strlen(type_string)) == 0) {
type_array[i][1](); // call appropriate function;
}
i++;
}
}
我猜它会使用 HashMap
但(我可能错了)它似乎没有乱码符号。有什么简单的方法可以构建成对的 HashMap
吗?
谢谢
最佳答案
我认为您可以使用 ArrayAdapter。 看看this tutorial明白我的意思。
它需要一些操作才能处理不同种类的项目。 做一个接口(interface)MyListItem
public interface MyListItem {
public int getLayout();
public void bindToView(View v);
}
对Artist、Release、Label的展示进行不同的布局。 创建实现 MyListItem 的 Artist、Release、Label 类。
public class Artist implements MyListItem {
private String Name;
public Artist(String name){
this.name = name;
}
public int getLayout() {
return R.layout.artistlayout;
}
public void bindToView(View v) {
TextView textView = (TextView) rowView.findViewById(R.id.artistLabel);
textView.setText(name);
}
}
现在适配器只需调用正确的方法来填充所选项目的 View 。
public class MySimpleArrayAdapter extends ArrayAdapter<MyListItem> {
private final Context context;
private final MyListItem[] values;
public MySimpleArrayAdapter(Context context, MyListItem[] values) {
super(context, android.R.layout.simple_list_item_1, values);
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MyListItem item = values[position];
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(item.getLayout(), parent, false);
item.bindTo(view);
return view;
}
}
关于java - 不同行的 ListView 自定义适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14408750/