【问题标题】:Creating a View with different types of adapters depending on the row根据行创建具有不同类型适配器的视图
【发布时间】:2013-12-18 11:23:17
【问题描述】:

我正在尝试复制此 Google Now 卡片界面。我不担心卡片的感觉,但我更关心视图是如何构建的。

我正在考虑使用一个适配器来返回与行相对应的不同布局。但是正如您所看到的,两个视图都包含彼此不相关的信息。

是否可以有一个具有不同行适配器的 ListView?

或者我如何使用自定义视图来实现这一点?

【问题讨论】:

  • 一个列表视图和一个自定义适配器,根据情况扩展不同的视图(xml)是最好的方法。
  • 是的,你必须这样做,只会膨胀不同的 xmls
  • 自定义视图可以解决这个问题,不,你不能有多个适配器用于单个视图。以防万一,它将替换其他适配器。
  • @KaHeL "自定义视图可以解决" ,怎么样?你有任何现有的例子来解决这种事情吗?
  • 这更像是下面的答案。膨胀视图,然后将其传递给适配器本身。返回整个视图,因为它的行根据其位置进行了修改。这可以做到,但需要做很多工作。我会把它作为我的答案发布。

标签: android android-listview android-custom-view


【解决方案1】:

您需要使用单个适配器并根据列表中的位置扩展不同的视图来执行此操作。这个问题的一个很好的答案在这里:

Android ListView with different layouts for each row

【讨论】:

  • 如何使用单个适配器处理不同类型的信息?假设我正在使用“运动”对象为顶部卡片充气,并使用“天气”对象为底部卡片充气,这对于适配器将如何工作?这是我的主要问题
  • 我从来没有这样做过。但猜测您可能希望使用其构造函数将 2 个数据源传递到您的自定义适配器,然后,您可以根据您正在膨胀的布局从您需要的任何数据源中获取数据。您可能必须在 getView 方法中操作位置变量才能从每个数据源中获取正确的项目,但我认为这应该不是什么大问题
【解决方案2】:

首先您需要为此创建一个 CustomAdapter:

public class CustomAdapter extends BaseAdapter {
    ArrayList<View> views;
    Context context;

    public CustomAdapter(Context context, ArrayList<View> views){
        this.views = views;
        this.context = context;
    }

    @Override
    public int getCount() {
        return views.size();
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View rowView = views.get(i);
        /*set the views of the rowView here but take note use try catch since you can't be sure if the view will be present or not this is the part where I do not advice it to have different custom views per row but it's all yours to do your tricks*/

        return rowView;
    }
}

这里是我创建的示例方法:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);

        ArrayList<View> views = new ArrayList<View>();

        CustomAdapter adapter = new CustomAdapter(MainActivity.this,views);
        ListView custom_list = (ListView)findViewById(R.id.list_custom);
        custom_list.setAdapter(adapter);

        LayoutInflater inflater = (LayoutInflater)   getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view1 = inflater.inflate(R.layout.view1, null);
        View view2 = inflater.inflate(R.layout.view2, null);

        views.add(view1);
        views.add(view2);
        adapter.notifyDataSetChanged();
}

如果需要,请执行您的解决方法,但基本上就是这样。膨胀视图,将其传递给您的 arrayList,然后将其设置在您的 listView 上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 2014-03-21
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多