将图像添加到自定义baseadapter

时间:2014-06-14 12:40:31

标签: android

我有一个从sqlite数据库接收数组的基础适配器:

     mHelper = new MyDbHelperContacts(this);
    mDb = mHelper.getWritableDatabase();
      Cursor c = null;
        ArrayList<String> names=new ArrayList<String>() ; 
        c = mDb.rawQuery("SELECT realname FROM contacts",null);  
        c.moveToFirst();

        if(c.getCount()>0){
               do{
                  names.add(c.getString(0));
               }while(c.moveToNext());
             }     

并在异步中填充它:

 @Override
    protected Void doInBackground(ArrayList<String>... params) {
        mListItems.clear();
        mListSectionPos.clear();
        ArrayList<String> items = params[0];
        if (mItems.size() > 0) {

            // NOT forget to sort array
            Collections.sort(items);

            int i = 0;
            String prev_section = "";
            while (i < items.size()) {
                String current_item = items.get(i).toString();
                String current_section = 
                         current_item.substring(0, 1).toUpperCase(Locale.getDefault());

                if (!prev_section.equals(current_section)) {
                    mListItems.add(current_section);
                    mListItems.add(current_item);
                    // array list of section positions

 mListSectionPos.add(mListItems.indexOf(current_section));
                    prev_section = current_section;
                } else {
                    mListItems.add(current_item);
                }
                i++;
            }
        }

但我不知道如何为每个条目添加图像,请注意图像位于文件夹中,图像名称属于每个条目,例如对于条目管理员,/ storage / sdcard /中有图像图片/ admin_image1.jpg。 所以当我有条目名称时,我没有问题将图像绑定到特定条目。

我需要的是如何将图像添加到此适应器中,这里我发布了主要活动和适配器代码,对不起他们太久了:

Cursor mCursor;
   MyDbHelperContacts mHelper;
   SQLiteDatabase mDb;
// unsorted list items
ArrayList<String> mItems;

// array list to store section positions
ArrayList<Integer> mListSectionPos;

// array list to store listView data
ArrayList<String> mListItems;

// custom list view with pinned header
PinnedHeaderListView mListView;

// custom adapter
PinnedHeaderAdapter mAdaptor;

// search box
EditText mSearchView;

// loading view
ProgressBar mLoadingView;

// empty view
TextView mEmptyView;

@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);



     mHelper = new MyDbHelperContacts(this);
    mDb = mHelper.getWritableDatabase();
      Cursor c = null;
        ArrayList<String> names=new ArrayList<String>() ; 
        c = mDb.rawQuery("SELECT realname FROM contacts",null);  
        c.moveToFirst();

        if(c.getCount()>0){
               do{
                  names.add(c.getString(0));
               }while(c.moveToNext());
             }     






    System.out.println(names);



    // UI elements
    setupViews();

    // Array to ArrayList
    mItems = names;
    mListSectionPos = new ArrayList<Integer>();
    mListItems = new ArrayList<String>();

    // for handling configuration change
    if (savedInstanceState != null) {
        mListItems = savedInstanceState.getStringArrayList("mListItems");
        mListSectionPos = 
 savedInstanceState.getIntegerArrayList("mListSectionPos");

        if (mListItems != null && mListItems.size() > 0
                && mListSectionPos != null && 
 mListSectionPos.size() > 0) {
            setListAdaptor();
        }

        String constraint = savedInstanceState.getString("constraint");
        if (constraint != null && constraint.length() > 0) {
            mSearchView.setText(constraint);
            setIndexBarViewVisibility(constraint);
        }
    } else {
        new Poplulate().execute(mItems);
    }
}

private void setupViews() {
    setContentView(R.layout.main_act);
    mSearchView = (EditText) findViewById(R.id.search_view);
    mLoadingView = (ProgressBar) findViewById(R.id.loading_view);
    mListView = (PinnedHeaderListView) findViewById(R.id.list_view);
    mEmptyView = (TextView) findViewById(R.id.empty_view);
}


@Override
protected void onPostCreate(Bundle savedInstanceState) {
    mSearchView.addTextChangedListener(filterTextWatcher);
    super.onPostCreate(savedInstanceState);
}

private void setListAdaptor() {
    // create instance of PinnedHeaderAdapter and set adapter to list view
    mAdaptor = new PinnedHeaderAdapter(this, mListItems, mListSectionPos);
    mListView.setAdapter(mAdaptor);

    LayoutInflater inflater = (LayoutInflater) 
 getSystemService(LAYOUT_INFLATER_SERVICE);

    // set header view
    View pinnedHeaderView = 
 inflater.inflate(R.layout.section_row_view,mListView, false);
    mListView.setPinnedHeaderView(pinnedHeaderView);

    // set index bar view
    IndexBarView indexBarView = (IndexBarView) 
 inflater.inflate(R.layout.index_bar_view, mListView, false);
    indexBarView.setData(mListView, mListItems, mListSectionPos);
    mListView.setIndexBarView(indexBarView);

    // set preview text view
    View previewTextView = inflater.inflate(R.layout.preview_view,mListView, 
 false);
    mListView.setPreviewView(previewTextView);

    // for configure pinned header view on scroll change
    mListView.setOnScrollListener(mAdaptor);
}

private TextWatcher filterTextWatcher = new TextWatcher() {
    public void afterTextChanged(Editable s) {
        String str = s.toString();
        if (mAdaptor != null && str != null)
            mAdaptor.getFilter().filter(str);
    }

    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
    }

    public void onTextChanged(CharSequence s, int start, int before,
            int count) {

    }
};

public class ListFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        // NOTE: this function is *always* called from a background thread,
        // and
        // not the UI thread.
        String constraintStr = 
 constraint.toString().toLowerCase(Locale.getDefault());
        FilterResults result = new FilterResults();

        if (constraint != null && constraint.toString().length() > 0) {
            ArrayList<String> filterItems = new ArrayList<String>();

            synchronized (this) {
                for (int i = 0; i < mItems.size(); i++) {
                    String item = mItems.get(i);
                    if 
 (item.toLowerCase(Locale.getDefault()).startsWith(constraintStr)) {
                        filterItems.add(item);
                    }
                }
                result.count = filterItems.size();
                result.values = filterItems;
            }
        } else {
            synchronized (this) {
                result.count = mItems.size();
                result.values = mItems;
            }
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint,FilterResults 
 results) {
        ArrayList<String> filtered = (ArrayList<String>) results.values;
        setIndexBarViewVisibility(constraint.toString());
        // sort array and extract sections in background Thread
        new Poplulate().execute(filtered);
    }

}

private void setIndexBarViewVisibility(String constraint) {
    // hide index bar for search results
    if (constraint != null && constraint.length() > 0) {
        mListView.setIndexBarVisibility(false);
    } else {
        mListView.setIndexBarVisibility(true);
    }
}

// sort array and extract sections in background Thread here we use
// AsyncTask
private class Poplulate extends AsyncTask<ArrayList<String>, Void, Void> {

    private void showLoading(View contentView, View loadingView,
            View emptyView) {
        contentView.setVisibility(View.GONE);
        loadingView.setVisibility(View.VISIBLE);
        emptyView.setVisibility(View.GONE);
    }

    private void showContent(View contentView, View loadingView,
            View emptyView) {
        contentView.setVisibility(View.VISIBLE);
        loadingView.setVisibility(View.GONE);
        emptyView.setVisibility(View.GONE);
    }

    private void showEmptyText(View contentView, View loadingView,
            View emptyView) {
        contentView.setVisibility(View.GONE);
        loadingView.setVisibility(View.GONE);
        emptyView.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onPreExecute() {
        // show loading indicator
        showLoading(mListView, mLoadingView, mEmptyView);
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(ArrayList<String>... params) {
        mListItems.clear();
        mListSectionPos.clear();
        ArrayList<String> items = params[0];
        if (mItems.size() > 0) {

            // NOT forget to sort array
            Collections.sort(items);

            int i = 0;
            String prev_section = "";
            while (i < items.size()) {
                String current_item = items.get(i).toString();
                String current_section = current_item.substring(0, 
 1).toUpperCase(Locale.getDefault());

                if (!prev_section.equals(current_section)) {
                    mListItems.add(current_section);
                    mListItems.add(current_item);
                    // array list of section positions

 mListSectionPos.add(mListItems.indexOf(current_section));
                    prev_section = current_section;
                } else {
                    mListItems.add(current_item);
                }
                i++;
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        if (!isCancelled()) {
            if (mListItems.size() <= 0) {
                showEmptyText(mListView, mLoadingView, mEmptyView);
            } else {
                setListAdaptor();
                showContent(mListView, mLoadingView, mEmptyView);
            }
        }
        super.onPostExecute(result);
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    if (mListItems != null && mListItems.size() > 0) {
        outState.putStringArrayList("mListItems", mListItems);
    }
    if (mListSectionPos != null && mListSectionPos.size() > 0) {
        outState.putIntegerArrayList("mListSectionPos", mListSectionPos);
    }
    String searchText = mSearchView.getText().toString();
    if (searchText != null && searchText.length() > 0) {
        outState.putString("constraint", searchText);
    }
    super.onSaveInstanceState(outState);
}
 }

这是适配器:

 // Customized adaptor to populate data in PinnedHeaderListView
 public class PinnedHeaderAdapter extends BaseAdapter implements OnScrollListener, 
 IPinnedHeader, Filterable {

private static final int TYPE_ITEM = 0;
private static final int TYPE_SECTION = 1;
private static final int TYPE_MAX_COUNT = TYPE_SECTION + 1;

LayoutInflater mLayoutInflater;
int mCurrentSectionPosition = 0, mNextSectionPostion = 0;

// array list to store section positions
ArrayList<Integer> mListSectionPos;

// array list to store list view data
ArrayList<String> mListItems;

// context object
Context mContext;

public PinnedHeaderAdapter(Context context, ArrayList<String> 
 listItems,ArrayList<Integer> listSectionPos) {
    this.mContext = context;
    this.mListItems = listItems;
    this.mListSectionPos = listSectionPos;

    mLayoutInflater = (LayoutInflater) 
 mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

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

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

@Override
public boolean isEnabled(int position) {
    return !mListSectionPos.contains(position);
}

@Override
public int getViewTypeCount() {
    return TYPE_MAX_COUNT;
}

@Override
public int getItemViewType(int position) {
    return mListSectionPos.contains(position) ? TYPE_SECTION : TYPE_ITEM;
}

@Override
public Object getItem(int position) {
    return mListItems.get(position);
}

@Override
public long getItemId(int position) {
    return mListItems.get(position).hashCode();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;

    if (convertView == null) {
        holder = new ViewHolder();
        int type = getItemViewType(position);

        switch (type) {
        case TYPE_ITEM:
            convertView = mLayoutInflater.inflate(R.layout.row_view, 
 null);
            break;
        case TYPE_SECTION:
            convertView = 
 mLayoutInflater.inflate(R.layout.section_row_view, null);
            break;
        }
        holder.textView = (TextView) 
 convertView.findViewById(R.id.row_title);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.textView.setText(mListItems.get(position).toString());
    return convertView;
}

@Override
public int getPinnedHeaderState(int position) {
    // hide pinned header when items count is zero OR position is less than
    // zero OR
    // there is already a header in list view
    if (getCount() == 0 || position < 0 || mListSectionPos.indexOf(position)  
  != -1) {
        return PINNED_HEADER_GONE;
    }

    // the header should get pushed up if the top item shown
    // is the last item in a section for a particular letter.
    mCurrentSectionPosition = getCurrentSectionPosition(position);
    mNextSectionPostion = getNextSectionPosition(mCurrentSectionPosition);
    if (mNextSectionPostion != -1 && position == mNextSectionPostion - 1) {
        return PINNED_HEADER_PUSHED_UP;
    }

    return PINNED_HEADER_VISIBLE;
}

public int getCurrentSectionPosition(int position) {
    String listChar = mListItems.get(position).toString().substring(0,   
  1).toUpperCase(Locale.getDefault());
    return mListItems.indexOf(listChar);
}

public int getNextSectionPosition(int currentSectionPosition) {
    int index = mListSectionPos.indexOf(currentSectionPosition);
    if ((index + 1) < mListSectionPos.size()) {
        return mListSectionPos.get(index + 1);
    }
    return mListSectionPos.get(index);
}

@Override
public void configurePinnedHeader(View v, int position) {
    // set text in pinned header
    TextView header = (TextView) v;
    mCurrentSectionPosition = getCurrentSectionPosition(position);
    header.setText(mListItems.get(mCurrentSectionPosition));
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount,  
 int totalItemCount) {
    if (view instanceof PinnedHeaderListView) {
        ((PinnedHeaderListView) 
 view).configureHeaderView(firstVisibleItem);
    }
}

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
    // TODO Auto-generated method stub
}

@Override
public Filter getFilter() {
    return ((MainActivity) mContext).new ListFilter();
}

public static class ViewHolder {
    public TextView textView;
}
 }

和xml:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" 
android:orientation="vertical">

<EditText
    android:id="@+id/search_view"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:drawableLeft="@drawable/ic_search"
    android:hint="@string/search_hint"
    android:singleLine="true" />

<FrameLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <include
        layout="@layout/loading_empty_view"
         />

     <com.example.listviewfilter.ui.PinnedHeaderListView
        android:id="@+id/list_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scrollingCache="false" />
</FrameLayout>

</LinearLayout>

任何提示都会非常感激

1 个答案:

答案 0 :(得分:0)

看看AsyncImageLoader,它完全符合您的要求,但使用Executor Framework解码并发工作线程中的多个图像 - &gt; laggy Listview with ImageView and Executor Framework

基本思路是将Runnable(包含SDCard image PathImageView)发送到工作线程以解码图像。一旦我们拥有了位图,因为我们无法从工作线程更新UI,我们会创建另一个包含RunnableBitmap引用的ImageView,并将其发布到用户界面中线程的消息队列来更新UI。