簡體   English   中英

Android-將布局視圖添加到ListView

[英]Android - add Layout views into ListView

問題是,我不會使用包含圖像,描述和兩個按鈕的元素制作ListView。 我在我自己的BaseAdapter擴展中制作它們,但是包含ListView的片段正在關閉(logcat中沒有錯誤..)。 我發現,當我不返回布局類型元素時,ListView運行良好。 因此,我的示例帶有“線性示例布局”,但無法正常工作。是否有可能在ListView中顯示布局?

這是我的代碼:創建部分:

lv = (ListView) getView().findViewById(R.id.main_wall_ambajes_lv);
AmbajAdapter aa = new AmbajAdapter(getActivity().getApplicationContext(), StaticData.ambajes);
lv.setAdapter(aa);

我的適配器的getView方法:

public View getView(int position, View convertView, ViewGroup parent) {

    LinearLayout ll = new LinearLayout(getActivity());
    ll.setOrientation(LinearLayout.VERTICAL);
    ImageView iv = new ImageView(getActivity());
    iv.setImageBitmap(placeholderBitmap);
    ll.addView(iv);
    ll.addView(iv);
    ll.addView(iv);
    ll.addView(iv);
    return ll;
}

我不知道您為什么沒有任何錯誤,但是我不認為您以正確的方式進行操作。

通常,您在布局文件夾的xml文件中創建布局,並且僅在getView()對其進行充氣,例如,如下所示:

private LayoutInflater mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
@Override
public View getView(int position, View view, ViewGroup parent) {
    if (view == null) {
        view = mInflater.inflate(R.layout.your_custom_layout, parent, false);
    }

    //your code for setting the image or other things goes here
    //for example if you have a textView
    TextView textView = (TextView) view.findViewById(R.id.my_textview_id);
    textView.setText("my custom text for this cell");

    return (view);
}

your_custom_layout只是布局的xml文件。

請注意 ,出於性能原因,由於單元回收的緣故,我只會在視圖為null時對其進行膨脹,並且只讀取一次LayoutInflater上下文並將其放在mInflater 但是,為了獲得最佳性能,應使用ViewHolder ,但這超出了您的問題范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM