如何在android中的xml文件中显示listview内容

时间:2014-05-26 09:10:25

标签: java android xml listview

我有2个xml文件

  1. MainActivity.xml 2.Example.xml
  2. 我在Example.xml中有listview。我在Example.java中编写的代码。但是数据没有显示在listview中。请仔细阅读我的代码

    的example.xml

    <?xml version="1.0" encoding="utf-8"?>
    <ViewSwitcher xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/profileSwitcher"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <ListView
            android:id="@+id/listPasscode"
            android:layout_height="wrap_content"
            android:layout_width="match_parent">
        </ListView>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Test"/>
    
    
    </LinearLayout>
        </ViewSwitcher>
    

    Example.java

    public class ListViewAndroidExample extends Activity {
        ListView listView ;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
    
            listView = (ListView) findViewById(R.id.listPasscode);
    
            // Define a new Adapter
            // First parameter - Context
            // Second parameter - Layout for the row
            // Third parameter - ID of the TextView to which the data is written
            // Forth - the Array of data
    
            // Array of strings...
            String[] countryArray = {"India", "Pakistan", "USA", "UK"};
    
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
              android.R.layout.simple_list_item_1, android.R.id.text1, countryArray);
    
            // Assign adapter to ListView
            listView.setAdapter(adapter);
    
            setContentView(R.layout.activity_list_view_android_example);
    
        }
    
    }
    

    xml和java文件之间是否正确链接?如果不建议我

1 个答案:

答案 0 :(得分:2)

试试这个..

在初始化setContentView

之前添加ListView
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_list_view_android_example);
    listView = (ListView) findViewById(R.id.listPasscode);

修改

改变这个..

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, countryArray);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countryArray);