代码中有错误而无法解决问题? android列表,

时间:2012-02-24 08:22:26

标签: java android

我在本网站使用此代码直至1.3:

http://www.vogella.de/articles/AndroidListView/article.html

1.4。听者

要对列表中的选择作出反应,请将OnItemClickListener设置为ListView。

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
        Toast.makeText(getApplicationContext(),
            "Click ListItem Number " + position, Toast.LENGTH_LONG)
            .show();
    }
});

我将此代码复制到主要活动,但此行中出现错误:

listView.setOnItemClickListener(new OnItemClickListener() 

注意:实际上我并不理解第1.3步......我是Java语言的初学者。

我该怎么做,任何人都可以解释这段代码吗?

2 个答案:

答案 0 :(得分:1)

你的代码是对的。 以下错误可能是: 1. listview没有定义。 2.未导入OnItemClickListener。

答案 1 :(得分:0)

试试这个......

    listView.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

        }
    });

看看这个。我只做了你的例子。对我有用。

 package com.list;

    import android.app.Activity;
     import android.os.Bundle;
      import android.view.View;
      import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
     import android.widget.ArrayAdapter;
  import android.widget.ListView;
    import android.widget.Toast;

      public class ListActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ListView listView = (ListView) findViewById(R.id.mylist);
    String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
            "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
            "Linux", "OS/2" };

    // First paramenter - Context
    // Second parameter - Layout for the row
    // Third parameter - ID of the View to which the data is written
    // Forth - the Array of data
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, values);

    // Assign adapter to ListView
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            Toast.makeText(getApplicationContext(),
                    "Click ListItem Number " + position, Toast.LENGTH_LONG)
                    .show();
        }
    });

}

}