我可以在ActionBarActivity中动态填充ListView吗?

时间:2015-01-18 23:49:56

标签: java android listview android-listview listadapter

我看到了一些在ListActivity中填充ListView的示例。我想要一个动态填充的ListView,但是在带有操作栏的活动中。

所以不是(如我所见的例子):

public class EditHolidaysActivity extends ListActivity {

我有:

public class EditHolidaysActivity extends ActionBarActivity {

但是无法解析setListAdapter方法。我可以用什么方法来填充ListView?以下是xml和java的片段:

    ...
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Anni"
        android:id="@+id/chkbxAnniversary"
        android:checked="false"
        android:onClick="saveAnniPref"/>

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>

爪哇:

public class EditHolidaysActivity extends ActionBarActivity {
    public static final String PREFS_NAME = MainActivity.PREFS_NAME;
    private final static String TEXT_DATA_KEY = "textData";
    private CommentsDataSource datasource;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_holidays);

        datasource = new CommentsDataSource(this);
        datasource.open();

        List<Comment> values = datasource.getAllComments();

        // use the SimpleCursorAdapter to show the
        // elements in a ListView
        ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
                android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);
    }

谢谢!

1 个答案:

答案 0 :(得分:2)

这样的事情:

public class EditHolidaysActivity extends ActionBarActivity {
public static final String PREFS_NAME = MainActivity.PREFS_NAME;
private final static String TEXT_DATA_KEY = "textData";
private CommentsDataSource datasource;
private ListView lstView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_holidays);

    lstView = (ListView)findViewById(R.id.list);

    datasource = new CommentsDataSource(this);
    datasource.open();

    List<Comment> values = datasource.getAllComments();

    // use the SimpleCursorAdapter to show the
    // elements in a ListView
    ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
            android.R.layout.simple_list_item_1, values);
    lstView.setAdapter(adapter);
}