Android AdapterView?

问题描述:

Documents说:Android AdapterView?

当你的布局的内容是动态的或不预先确定的,你 可以使用该子类适配器视图来填充版面 ,享有在运行时的布局。 AdapterView类的子类使用 适配器将数据绑定到其布局。

但大多数教程是关于ListViewGridViewSpinnerGallery

我期望直接从AdapterView扩展一个子类。我必须创建一个自定义视图,它的内容依赖于适配器。

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

首先,您应该确定AdapterView是您想要的,因为并非所有的“动态或非预定义”视图都可以通过AdapterView实现。有时你最好创建延伸ViewGroup的视图。

如果你想使用AdapterView,看看this really nice example。在GitHub上有适配器的很多自定义视图。 Check out this one (extends ViewGroup)

你可以这样创造的东西:

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()); 
+3

谢谢,但我的问题不是关于“如何为视图创建适配器”,我的问题是关于“如何创建一个定制视图,它的内容由适配器决定?”(该视图称为“AdapterView ' –

+4

这不是他的@StudentStudent所问的。 – QAMAR

ListView延伸AbsListView这又延伸AdapterView<ListAdapter>。所以,如果你绝对必须从头开始实现这样一个自定义视图,你可以看看这些类的源代码:

但要注意,这是一项相当艰巨的任务。也许用一个现有的类来调整外观可能就足够了。

这可能不是一个总的回答你的问题,但我向您展示最有可能的出发点或指针,可以指导:

Sony Developer Tutorials - 3D ListView

AdapterView派生可以工作,但它可能不会如你所期望的那样有益。由AdapterView提供的一些基础设施是包私有的,这意味着我们无法访问它。

例如,AdapterView管理所选项目索引AbsListViewListView。但是,因为像setNextSelectedPositionInt(int position)(这是设置mNextSelectedPosition的唯一路径)的方法是包私有的,所以我们无法找到它们。 AbsListViewListView可以找到他们,因为他们在同一个包中,但我们不能。

(如果你深入到AdapterView源你会发现setNextSelectedPositionInt()handleDataChanged()调用。不幸的是handleDataChanged()还包私人和为_not_called从内部AdapterView其他地方可能被利用,使设定位置。)

这意味着如果您需要管理选定的职位,您需要在派生类中重新创建基础架构(或者您需要从ListViewAbsListView派生出来......尽管我怀疑您会遇到类似的问题来自AbsListView)。这也意味着围绕物品选择的任何功能都可能无法完全运作。