在android的编程中,我使用setOnItemClickListener现在抛出异常。我以前从来没有遇到任何麻烦,我没有在文档中看到它列出的任何例外情况。谁能告诉我这是什么问题?
package com.name.magicwindow;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MagicWindowActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView mainMenu;
try{
mainMenu = (ListView)findViewById(R.id.main_menu_list);
try{
mainMenu.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,View view,int position,long id)
{
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),Toast.LENGTH_SHORT).show();
}
});
}catch(Exception e)
{
Toast.makeText(getApplicationContext(), "could not set listener",Toast.LENGTH_LONG).show();
}
}catch(Exception e)
{
Toast.makeText(getApplicationContext(), "could not find listview",Toast.LENGTH_LONG).show();
}
setContentView(R.layout.main);
}
}
答案 0 :(得分:2)
那个应该很简单:
在使用setContentView(R.layout.main)
之前,您必须致电findViewById()
所以你的活动知道它的内容(视图层次结构)是什么。