java - 不同行的 ListView 自定义适配器

标签 java android c

我正在使用 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/

相关文章:

java - 从 Scanner 替换文件中的一行

android - 如何在不同的 fragment 中制作不同的菜单选项?

android - 有没有办法让 Eclipse 将您的自定义 View 检测为其父布局?

java - 如何加快我的 ArrayList 搜索速度?

java - PostgreSQL :Calling of stored procedure through Java code with Hibernate

java - 如何在按键时重置处理 Canvas ?

安卓应用程序 : Apply Color Theme Dynamically at Runtime

c - 为什么即使 s 更小,以下代码也打印 "S is Bigger"?

c - 在哪里可以找到 "more"命令的源代码?

c - 尽管满足条件,循环仍然重复