我如何实现一个没有ListActivity的ListView? (只使用Activity)

我是新来的Android,我真的需要这样做(我已经考虑在另一个Activity做),但任何人都可以看到一个简单的代码(只是onCreate()方法),可以做Listview没有ListActivity

谢谢

如果你有一个xml布局的活动,包括像这样的listView

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="fill_parent" 

然后在你的onCreate你可以有这样的事情

 setContentView(R.layout.the_view); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, myList); ListView lv = (ListView)findViewById(android.R.id.list); lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> a, View v,int position, long id) { Toast.makeText(getBaseContext(), "Click", Toast.LENGTH_LONG).show(); } }); 

在res / layout / main.xml文件中包含以下资源:

 <ListView android:id="@+id/id_list_view" android:layout_width="fill_parent" android:layout_height="fill_parent" /> 

your_class.java

 import android.widget.ListView; import android.widget.ArrayAdapter; public class your_class extends Activity { private ListView m_listview; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); m_listview = (ListView) findViewById(R.id.id_list_view); String[] items = new String[] {"Item 1", "Item 2", "Item 3"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items); m_listview.setAdapter(adapter); } } 

下面以编程方式创build一个简单的ListView:

 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String[] myList = new String[] {"Hello","World","Foo","Bar"}; ListView lv = new ListView(this); lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,myList)); setContentView(lv); } 

您也可以引用您的布局,从您的代码实例化布局对象,然后在Java中构buildListView。 这给你在运行时设置dynamic高度和宽度方面的一些灵活性。

请在res / layout / main.xml中包含以下资源文件

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" </ListView> </RelativeLayout> 

MainActivity.java

 public class MainActivity extends Activity { ListView listView; String[] listPlanet={"mercury","Venus","Mars","Saturn","Neptune"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); listView = (ListView)findViewById(R.id.listView)); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listPlanet); listview.setAdapter(adapter); } }