如何在不扩展ListActivity的情况下处理onView for ListView?

时间:2011-10-26 14:08:34

标签: android listview

我有一个listview填充如下,它正在工作。我的问题是能够处理onclick。我没有扩展listactivity,因为我的所有活动都扩展了一个公共活动,我用它来设置所有活动中使用的公共变量/首选项等。有没有办法处理onclick而不扩展listactivity?如果没有,有没有办法导入listactivity(通过类或东西)?

    ListView lv = (ListView)findViewById(R.id.listViewGhostCams);
    SimpleAdapter adapter = new SimpleAdapter(
            this,
            list,
            R.layout.custom_row_view,
            new String[] {"pen","price","color"},
            new int[] {R.id.text1,R.id.text2, R.id.text3}
            );
    populateList();
    lv.setAdapter(adapter);

我是android / java编程的新手,所以请保持温和! : - )

谢谢, 香农

3 个答案:

答案 0 :(得分:8)

您可以使用OnItemClickListener

执行此操作
    lv.setOnItemClickListener(new OnItemClickListener(){

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            //Your code
        }

    });

答案 1 :(得分:7)

我猜你的意思是onClick on item?只需使用这个位:

lv.setOnItemClickListener(new OnItemClickListener() {

    @Override             
    public void onItemClick(AdapterView<?> parent, View
    view, int position, long id) { 
    }
});

答案 2 :(得分:0)

您可以使用onItemClickListener

 public class MainActivity extends Activity {
     ListView listView;
     String[] listPlanet={"mercury","Venus","Mars","Saturn","Neptune"};

     @Override
     protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);

         listView = (ListView)findViewById(R.id.listView));

         ArrayAdapter<String> adapter =
            new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,         listPlanet);

         listview.setAdapter(adapter);

         listView.setOnItemClickListener(new OnItemClickListener(){

          @Override
          public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)      {
                Toast.makeText(getAppicationContext(), listPlanet.get(arg2), Toast.LENGTH_SHORT).show();

       }

    });

    }

 }