MainActivity.java
package com.example; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; //用ListView需引用ListView包 import android.widget.ArrayAdapter; //用ArrayAdapter需引用ArrayAdapter包 import android.widget.ListView; import android.os.Build; public class MainActivity extends ActionBarActivity { private ListView listview; //定义一个String类型的数组来作为显示在ListView上的数据 private String[] userlist = new String[]{"孙悟空","猪八戒","沙和尚"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获取UI上的listview组件 listview = (ListView) findViewById(R.id.listview); //定义ArrayAdapter并添加三个参数 ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,userlist); //listview绑定adapter listview.setAdapter(adapter); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()) .commit(); } } }
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.MainActivity" tools:ignore="MergeRootFrame" > <ListView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
原文地址:http://623411589.blog.51cto.com/9215003/1585648