MergeAdapte+listView实现复杂布局

MergeAdapter对ListView的自定制非常有效,用来实现一些复杂的布局。首先先看下面两个类:

MergeAdapter.java

[java] view plain copy
/*
Copyright (c) 2008-2009 CommonsWare, LLC
Portions (c) 2009 Google, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may 
not use this file except in compliance with the License. You may obtain 
a copy of the License at 
    http://www.apache.org/licenses/LICENSE-2.0 
Unless required by applicable law or agreed to in writing, software 
distributed under the License is distributed on an "AS IS" BASIS, 
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
See the License for the specific language governing permissions and 
limitations under the License. 

*/

package com.commonsware.cwac.merge;

import android.database.DataSetObserver;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.SectionIndexer;
import java.util.ArrayList;
import java.util.List;
import com.commonsware.cwac.sacklist.SackOfViewsAdapter;

/**
* Adapter that merges multiple child adapters and views
* into a single contiguous whole.
*
* Adapters used as pieces within MergeAdapter must
* have view type IDs monotonically increasing from 0. Ideally,
* adapters also have distinct ranges for their row ids, as
* returned by getItemId().
*
*/
public class MergeAdapter extends BaseAdapter implements SectionIndexer {
private ArrayList pieces=new ArrayList();

/** 
    * Stock constructor, simply chaining to the superclass. 
*/  
public MergeAdapter() {  
    super();  
}  

/** 
    * Adds a new adapter to the roster of things to appear 
    * in the aggregate list. 
    * @param adapter Source for row views for this section 
*/  
public void addAdapter(ListAdapter adapter) {  
    pieces.add(adapter);  
    adapter.registerDataSetObserver(new CascadeDataSetObserver());  
}  

/** 
    * Adds a new View to the roster of things to appear 
    * in the aggregate list. 
    * @param view Single view to add 
*/  
public void addView(View view) {  
    addView(view, false);  
}  

/** 
    * Adds a new View to the roster of things to appear 
    * in the aggregate list. 
    * @param view Single view to add 
    * @param enabled false if views are disabled, true if enabled 
*/  
public void addView(View view, boolean enabled) {  
    ArrayList list=new ArrayList(1);  

    list.add(view);  

    addViews(list, enabled);  
}  

/** 
    * Adds a list of views to the roster of things to appear 
    * in the aggregate list. 
    * @param views List of views to add 
*/  
public void addViews(List views) {  
    addViews(views, false);  
}  

/** 
    * Adds a list of views to the roster of things to appear 
    * in the aggregate list. 
    * @param views List of views to add 
    * @param enabled false if views are disabled, true if enabled 
*/  
public void addViews(List views, boolean enabled) {  
    if (enabled) {  
        addAdapter(new EnabledSackAdapter(views));  
    }  
    else {  
        addAdapter(new SackOfViewsAdapter(views));  
    }  
}  

/** 
    * Get the data item associated with the specified 
    * position in the data set. 
    * @param position Position of the item whose data we want 
*/  
@Override  
public Object getItem(int position) {  
    for (ListAdapter piece : pieces) {  
        int size=piece.getCount();  

        if (position sections=new ArrayList();  

    for (ListAdapter piece : pieces) {  
        if (piece instanceof SectionIndexer) {  
            Object[] curSections=((SectionIndexer)piece).getSections();  

            if (curSections!=null) {  
                for (Object section : curSections) {  
                    sections.add(section);  
                }  
            }  
        }  
    }  

    if (sections.size()==0) {  
        return(null);  
    }  

    return(sections.toArray(new Object[0]));  
}  

private static class EnabledSackAdapter extends SackOfViewsAdapter {  
    public EnabledSackAdapter(List views) {  
        super(views);  
    }  

    @Override  
    public boolean areAllItemsEnabled() {  
        return(true);  
    }  

    @Override  
    public boolean isEnabled(int position) {  
        return(true);  
    }  
}  

private class CascadeDataSetObserver extends DataSetObserver {  
    @Override  
    public void onChanged() {  
        notifyDataSetChanged();  
    }  

    @Override  
    public void onInvalidated() {  
        notifyDataSetInvalidated();  
    }  
}  
 
  

}
SackOfViewsAdapter.java
[java] view plain copy
/*
Copyright (c) 2008-2009 CommonsWare, LLC
Portions (c) 2009 Google, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may 
not use this file except in compliance with the License. You may obtain 
a copy of the License at 
    http://www.apache.org/licenses/LICENSE-2.0 
Unless required by applicable law or agreed to in writing, software 
distributed under the License is distributed on an "AS IS" BASIS, 
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
See the License for the specific language governing permissions and 
limitations under the License. 

*/

package com.commonsware.cwac.sacklist;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import java.util.ArrayList;
import java.util.List;

/**
* Adapter that simply returns row views from a list.
*
* If you supply a size, you must implement newView(), to
* create a required view. The adapter will then cache these
* views.
*
* If you supply a list of views in the constructor, that
* list will be used directly. If any elements in the list
* are null, then newView() will be called just for those
* slots.
*
* Subclasses may also wish to override areAllItemsEnabled()
* (default: false) and isEnabled() (default: false), if some
* of their rows should be selectable.
*
* It is assumed each view is unique, and therefore will not
* get recycled.
*
* Note that this adapter is not designed for long lists. It
* is more for screens that should behave like a list. This
* is particularly useful if you combine this with other
* adapters (e.g., SectionedAdapter) that might have an
* arbitrary number of rows, so it all appears seamless.
*/
public class SackOfViewsAdapter extends BaseAdapter {
private List views=null;

/** 
    * Constructor creating an empty list of views, but with 
    * a specified count. Subclasses must override newView(). 
*/  
public SackOfViewsAdapter(int count) {  
    super();  

    views=new ArrayList(count);  

    for (int i=0;i views) {  
    super();  

    this.views=views;  
}  

/** 
    * Get the data item associated with the specified 
    * position in the data set. 
    * @param position Position of the item whose data we want 
*/  
@Override  
public Object getItem(int position) {  
    return(views.get(position));  
}  

/** 
    * How many items are in the data set represented by this 
    * Adapter. 
*/  
@Override  
public int getCount() {  
    return(views.size());  
}  

/** 
    * Returns the number of types of Views that will be 
    * created by getView(). 
*/  
@Override  
public int getViewTypeCount() {  
    return(getCount());  
}  

/** 
    * Get the type of View that will be created by getView() 
    * for the specified item. 
    * @param position Position of the item whose data we want 
*/  
@Override  
public int getItemViewType(int position) {  
    return(position);  
}  

/** 
    * Are all items in this ListAdapter enabled? If yes it 
    * means all items are selectable and clickable. 
*/  
@Override  
public boolean areAllItemsEnabled() {  
    return(false);  
}  

/** 
    * Returns true if the item at the specified position is 
    * not a separator. 
    * @param position Position of the item whose data we want 
*/  
@Override  
public boolean isEnabled(int position) {  
    return(false);  
}  

/** 
    * Get a View that displays the data at the specified 
    * position in the data set. 
    * @param position Position of the item whose data we want 
    * @param convertView View to recycle, if not null 
    * @param parent ViewGroup containing the returned View 
*/  
@Override  
public View getView(int position, View convertView,  
                                        ViewGroup parent) {  
    View result=views.get(position);  

    if (result==null) {  
        result=newView(position, parent);  
        views.set(position, result);  
    }  

    return(result);  
}  

/** 
    * Get the row id associated with the specified position 
    * in the list. 
    * @param position Position of the item whose data we want 
*/  
@Override  
public long getItemId(int position) {  
    return(position);  
}  

/** 
    * Create a new View to go into the list at the specified 
    * position. 
    * @param position Position of the item whose data we want 
    * @param parent ViewGroup containing the returned View 
*/  
protected View newView(int position, ViewGroup parent) {  
    throw new RuntimeException("You must override newView()!");  
}  

}
MergeAdapterDemo.java

[java] view plain copy
/*
Copyright (c) 2008-2009 CommonsWare, LLC

Licensed under the Apache License, Version 2.0 (the "License"); you may 
not use this file except in compliance with the License. You may obtain 
a copy of the License at 
    http://www.apache.org/licenses/LICENSE-2.0 
Unless required by applicable law or agreed to in writing, software 
distributed under the License is distributed on an "AS IS" BASIS, 
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
See the License for the specific language governing permissions and 
limitations under the License. 

*/

package com.commonsware.cwac.merge.demo;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.commonsware.cwac.merge.MergeAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class MergeAdapterDemo extends ListActivity {
private static final String[] items={“lorem”, “ipsum”, “dolor”,
“sit”, “amet”, “consectetuer”,
“adipiscing”, “elit”, “morbi”,
“vel”, “ligula”, “vitae”,
“arcu”, “aliquet”, “mollis”};
private MergeAdapter adapter=null;
private ArrayAdapter arrayAdapter=null;

@Override  
public void onCreate(Bundle icicle) {  
    super.onCreate(icicle);  
    setContentView(R.layout.main);  

    adapter=new MergeAdapter();  
    arrayAdapter=buildFirstList();  
    adapter.addAdapter(arrayAdapter);  
    adapter.addView(buildButton(), true);  
    adapter.addAdapter(buildSecondList());  
    adapter.addView(buildLabel());  

// adapter.addAdapter(buildSecondList());

    setListAdapter(adapter);  
}  

@Override  
public void onListItemClick(ListView parent, View v,  
                                                        int position, long id) {  
    Log.d("MergeAdapterDemo", String.valueOf(position));  
}  

private ArrayAdapter buildFirstList() {  
    return(new ArrayAdapter(this,  
                                    android.R.layout.simple_list_item_1,  
                                    new ArrayList(Arrays.asList(items))));  
}  

private View buildButton() {  
    Button result=new Button(this);  

    result.setText("Add Capitalized Words");  
    result.setOnClickListener(new View.OnClickListener() {  
        public void onClick(View v) {  
            for (String item : items) {  
                arrayAdapter.add(item.toUpperCase());  
            }  
        }  
    });  

    return(result);  
}  

private View buildLabel() {  
    TextView result=new TextView(this);  

    result.setText("Hello, world!f ddddddddddddddddddddddddddd");  

    return(result);  
}  

private ListAdapter buildSecondList() {  
    ArrayList list=new ArrayList(Arrays.asList(items));  

    Collections.shuffle(list);  

    return(new ArrayAdapter(this,  
                    android.R.layout.simple_list_item_1,  
                    list));  
}  

}

从上面的代码可以看出,用法如下:
adapter=new MergeAdapter();
arrayAdapter=buildFirstList();
adapter.addAdapter(arrayAdapter);
adapter.addView(buildButton(), true);
adapter.addAdapter(buildSecondList());
adapter.addView(buildLabel());
// adapter.addAdapter(buildSecondList());
setListAdapter(adapter);
无论多复杂的布局,都可以用addAdapter和addView的方式来自由定制,不用再去定义多个ListView了。使用的时候,只需要将MergeAdapter.java和SackOfViewsAdapter.java复制到自己的项目中就行,不需要做任何修改,使用起来非常简单

你可能感兴趣的:(android)