从onItemClick - Android中检索选定的菜单项文本?

时间:2012-12-06 05:16:57

标签: java android android-arrayadapter listitem

我理解这个问题已被问过好几次了。你会认为至少有一种解决方案可以帮助我,但没有这样的运气。

我有以下代码正确填充列表视图(also found here):

  public void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.main);  

    // Find the ListView resource.   
    mainListView = (ListView) findViewById( R.id.mainListView );  

    // Create and populate a List of planet names.  
    String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars",  
                                      "Jupiter", "Saturn", "Uranus", "Neptune"};    
    ArrayList<String> planetList = new ArrayList<String>();  
    planetList.addAll( Arrays.asList(planets) );  

    // Create ArrayAdapter using the planet list.  
    listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, planetList);  


    // Set the ArrayAdapter as the ListView's adapter.  
    mainListView.setAdapter( listAdapter );        
  }

但是,未能成功获取所选项目的文本。

例如,用户选择“Mars”,什么函数在函数中返回文本“Mars”:

public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {

// Retrieve selected text here?
}

1 个答案:

答案 0 :(得分:2)

public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {

   String text = parent.getItemAtPosition(pos); // This is the selected text.
}