当前位置: 首页 > 知识库问答 >
问题:

将图像添加到自定义基适配器

方璞
2023-03-14

我有一个从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/pictures/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个答案

刘承运
2023-03-14

请看一下AsyncImageLoader,它完全满足您的需求,但使用Executor框架对并发工作线程中的多个图像进行解码--

基本思想是发送一个Runnable,其中包含SDCard image PathImageView,给工作线程解码图像。一旦我们有了位图,因为我们不能从工作线程更新UI,我们就创建另一个Runnable,其中包含位图ImageView引用,并将其发布到UI线程的消息队列中以更新UI。

 类似资料:
  • 问题内容: 我已经构建了自己的自定义react-bootstrap Popover组件: 该组件的呈现方式如下: 现在,我想向组件中添加自定义道具,例如:我的文字,并使用新道具在弹出框中设置一些内容,例如- 但随后我在浏览器中收到此警告: 警告:标签上的未知道具。从元素中删除这些道具。 现在,我想我可以删除零件并逐个插入所有原始道具,而无需自定义道具,但是这样我就失去了“淡入淡出”效果,这也是处理

  • 我正在使用GraphStream库。目前,当我运行我的程序时,它会为我的图形打开新窗口并为我的图形打开单独的窗口。我尝试创建一个并将添加到中,之后我尝试将图形添加到我的中,但它说图形对象不是组件。 这是我的代码: 此程序为和图形打开单独的窗口。我想将我的图形显示在我的或。你知道怎么做吗?我看过这个链接,但它不能很好地解释我。

  • 问题内容: 我正在研究启用AJAX的asp.net应用程序。我刚刚向Array.prototype添加了一些方法,例如 该解决方案对我有用,可以以“漂亮”的方式重用代码。 但是,当我测试了它与整个页面一起使用时,我遇到了问题。我们有了一些自定义的Ajax扩展程序,它们开始表现出意想不到的效果:某些控件在其内容或值上显示为“未定义”。 这可能是什么原因?我是否缺少修改标准对象原型的东西? 注意:我很

  • 如果我创建一个继承JComponent的新类,我重写了JComponent的绘图Component(Graphics g)方法,通过使用g绘制一个圆圈,我应该修改什么才能使MouseListener仅在我单击组件的边界内时触发? 因为我在组件的构造函数中添加了setBounds(…)然后添加了一个MouseListener,但它会在我每次单击自定义组件所在容器中的任何位置时触发,而不仅仅是在我单击

  • 我一直在尝试向<code>PYTHONPATH</code>添加一个自定义目录。我在Mac上使用bash,如果相关的话。这就是我所做的: < li> < li> 并保存 < li> 有两个问题: < li >当我在Python IDE中运行< code>sys.path时,目标目录仍然没有出现。 < li >当我在终端中启动Python并在那里运行< code>sys.path时,确实显示了目录,

  • 我已经搜索了又搜索,除了我称之为“hack方法”的方法之外,找不到其他方法将自定义分类添加到自定义管理菜单中。 然后我注册我的帖子类型并确保它们使用 这可以工作,自定义帖子类型显示在我的自定义菜单中。 但是自定义分类法不接受同一属性的字符串,只接受true或false。 因此,要添加它,您必须创建一个子菜单页 这是一种“黑客”方式。 还有别的办法吗?如果不修改WordPress核心,我可以覆盖re