将一个自定义项添加到ListView

时间:2014-08-26 10:33:40

标签: android listview button android-cursor

我使用cursoradapter的listview,我需要添加一个自定义项作为查询结果的最后一项,我使用像按钮一样。即使结果为0,我也需要它。

活动oncreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lsto = (ListView) findViewById(R.id.listid);
    dbco1 = new dbClass(this);
    db = dbCo1.getReadableDatabase();       
    c = db.rawQuery( "SELECT * FROM ssnt", null);
    lao = new listAd(this, c, 1);
    lsto.setAdapter(lao);
    db.close();
    lsto.setOnItemClickListener(new OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ... }});
}

适配器类:

public class listAd extends CursorAdapter {
    LayoutInflater inf;
    String lna;

    public listAd(Context context, Cursor c, int flags) {
        super(context, c, flags);
        inf = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public void bindView(View view, Context context, Cursor cur) {
        lna = cur.getString(4);
        TextView rv = (TextView) view.findViewById(R.id.lro);
        rv.setText(lna);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View tiew = inf.inflate(R.layout.ro, parent, false);
        return tiew;
    }
}

ib.xml,要添加的布局:

<?xml version="1.0" encoding="utf-8"?>
    <ImageButton
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/bbb"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/ni"
    android:contentDescription="@string/desc"
    style="?android:attr/buttonBarButtonStyle" />

谢谢!

解决方案:使用setEmptyView()和addFooterView(),谢谢arash。

新的oncreate功能:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nv);
    setupActionBar();
            // setEmptyView wants an object, addFooterView wants an inflated layout
            // Howevere both function point to the same view, ib.xml above.
    ImageButton boo = (ImageButton) findViewById(R.id.bbb);
    lito = (ListView) findViewById(R.id.itli);
    View bo = getLayoutInflater().inflate(R.layout.ib, null);
    lito.setEmptyView(boo);
    lito.addFooterView(bo);
    dbCo = new dbClass(this);
    db = dbCo.getReadableDatabase();
    c = db.rawQuery( "SELECT * FROM ssnt", null);       
    lai = new itAd(this, c, 1);     
    lito.setAdapter(lai); 
    lito.setOnItemClickListener(new OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {                  
                      // stuff to do
          }});
}

1 个答案:

答案 0 :(得分:0)

如果它像按钮一样工作为什么当列表为空时你没有使用setEmptyView

YourList.SetEmptyView(yourView).

或FooterView,当它不是。