34

文件说:

当您的布局的内容是动态的或不是预先确定的时,您可以使用继承 AdapterView 的布局在运行时使用视图填充布局。AdapterView 类的子类使用 Adapter 将数据绑定到其布局。

但大多数教程都在about ListViewGridView和.SpinnerGallery

我正在寻找直接从AdapterView. 我必须创建一个自定义视图,它的内容取决于适配器。

我该怎么做,必须重写哪些方法?

4

5 回答 5

24

首先,您应该绝对确定这AdapterView是您想要的,因为并非所有“动态或非预定”视图都可以通过AdapterView. 有时你最好创建你的视图扩展ViewGroup

如果你想使用AdapterView,看看这个非常好的例子。GitHub 上有很多带有适配器的自定义视图。看看这个(扩展ViewGroup

于 2013-02-08T07:48:20.183 回答
6

这可能不是您问题的完整答案,但我很可能向您展示了一个可以指导您的起点或指针:

索尼开发者教程 - 3D ListView

于 2013-02-14T04:27:31.203 回答
5

ListView扩展AbsListView而扩展AdapterView<ListAdapter>。因此,如果您绝对必须从头开始实现这样的自定义视图,您可以查看这些类的源代码:

但请注意,这是一项艰巨的任务。也许使用现有类之一并调整外观可能就足够了。

于 2013-02-07T19:31:17.870 回答
2

派生AdapterView可以工作,但它可能没有你希望的那么有益。提供的一些基础设施AdapterView是包私有的,这意味着我们无权访问它。

例如,AdapterView管理 和 的选定项AbsListView索引ListView。但是,由于诸如setNextSelectedPositionInt(int position)(这是设置的唯一途径mNextSelectedPosition)之类的方法是包私有的,因此我们无法使用它们。AbsListView并且ListView可以找到它们,因为它们在同一个包中,但我们不能。

(If you dig into the AdapterView source you'll find that setNextSelectedPositionInt() is called from handleDataChanged(). Unfortunately handleDataChanged() is also package-private and is _not_called from anywhere else within AdapterView that could be leveraged to enable setting position.)

That means that if you need to manage selected position, you'll need to recreate that infrastructure in your derived class (or you'll need to derive from ListView or AbsListView...though I suspect you'll run into similar problems deriving from AbsListView). It also means that any AdapterView functionality that revolves around item selection likely won't be fully operational.

于 2013-09-09T15:48:11.103 回答
-2

你可以创建这样的东西:

public class SampleAdapter extends BaseAdapter {

public SampleAdapter() {
  // Some constructor
}

public int getCount() {
  return count; // Could also be a constant. This indicates the # of times the getView gets invoked.
}

public Object getItem(int position) {
    return position; // Returns the position of the current item in the iteration
}

public long getItemId(int position) {
  return GridView.INVALID_ROW_ID;
}

public View getView(int position, View convertView, ViewGroup parent) {
  View view = null;

  view = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.some_layout, null);
  view.setLayoutParams(new GridView.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
view.setBackgroungColor(Color.RED);

  return view;
}

}

这可以像这样调用:

GridView sampleView = (GridView) linearLayout.findViewById(R.id.sample_layout);
sampleView.setAdapter(new SampleAdapter());
于 2013-02-04T05:51:20.930 回答