我用清单视图在android中做了一个简单的应用程序,在选择项目时我想举杯,我尝试了如下操作,但是不起作用.
我的代码如下:
main.java
package com.example.listview;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class ListViewActivity extends Activity {
String items[]={"Car","Bird","Bike","Flower"};
String category[]={"Sports","Birds","Sports","Nature"};
int icons[]={R.drawable.car,R.drawable.bird,R.drawable.bike,R.drawable.flower};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
List <HashMap<String,String>> aList=new ArrayList<HashMap<String,String>>();
for(int i=0;i<4;i++)
{
HashMap<String,String> hm=new HashMap<String, String>();
hm.put("txt","Item : "+items[i]);
hm.put("category","Category : "+category[i]);
hm.put("icon",Integer.toString(icons[i]));
aList.add(hm);
}
String []from={"icon","txt","category"};
int []to={R.id.image,R.id.text,R.id.category};
SimpleAdapter adapter=new SimpleAdapter(getBaseContext(),aList,R.layout.list,from,to);
final ListView lv=(ListView)findViewById(R.id.listView);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
String selectedValue =(String) (lv.getItemAtPosition(position));
Toast.makeText(getApplicationContext(),selectedValue , Toast.LENGTH_LONG).show();
}
});
}
}
请提前帮助我..谢谢
解决方法:
HashMap<String, String> selectedValue = (HashMap<String, String>) (lv.getItemAtPosition(position));
ArrayList<String> list = new ArrayList<String>(selectedValue.keySet());
Toast.makeText(getApplicationContext(), selectedValue.get("txt"), Toast.LENGTH_LONG).show();
该哈希图具有存在于该列表中的密钥.该列表实际上是您提供的from数组.只需提供相应的键即可显示相应的文本.
它的工作.