我的应用程序是一个公司列表,每个公司是我的列表视图中的一行,显示:图片,名称和电话(按适配器)。一切正常!但是当我点击列表视图中的一个项目时,它应该启动another activity
,显示带有公司详细信息的页面。我有问题与onitemclick listener
(它不工作):
empresa = firm (in portuguese) lv = my listview
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent i = new Intent (getApplicationContext(), detalheEmpresas.class );
Empresas empresa = (Empresas) parent.getItemAtPosition(position);
i.putExtra("Nome", empresa.getTitle().toString());
startActivity(i); }});
my detalheEmpresas activity
public class detalheEmpresas extends Activity {
@Override
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.setContentView(R.layout.detalhes_empresa);
Intent i = getIntent();
String nome = i.getStringExtra("Nome");
TextView NOME = (TextView) findViewById(R.id.Nome);
NOME.setText(nome);
}}
我有一个非常相似的问题。通过设置单击侦听器来查看列表适配器中的自身来解决。
public class EmpresasListAdapter extends ArrayAdapter<Empresas> {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//recycling view and setting view fields.
/* Set listener to open firm detail activity on click */
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Your code to open firm detail activity
Intent i = new Intent (getApplicationContext(), detalheEmpresas.class );
Empresas empresa = (Empresas) parent.getItemAtPosition(position);
i.putExtra("Nome", empresa.getTitle().toString());
startActivity(i);
}
});
return view;
}
}
很可能与getApplicationContext…尝试使用活动上下文:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent i = new Intent (mSavedContext.getActivity(), detalheEmpresas.class ); <-------------
Empresas empresa = (Empresas) parent.getItemAtPosition(position);
i.putExtra("Nome", empresa.getTitle().toString());
startActivity(i);
}});
----------新编辑-----------------
好,不如直接给父activity添加一个click handler,这样就可以了:
public class ParentActivity extends Activity implements OnItemClickListener {
your activity code...
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent i = new Intent (getActivity(), detalheEmpresas.class );
Empresas empresa = (Empresas) parent.getItemAtPosition(position);
i.putExtra("Nome", empresa.getTitle().toString());
startActivity(i);
}
活动代码中的替换为
lv.setOnItemClickListener(new OnItemClickListener() {
lv.setOnItemClickListener(this);