2013-06-25 62 views
0

我在我的Android程序中使用了ListView如何在列表視圖中添加onItemClickListener以顯示該行的圖像

我有一些行,我一旦點擊了一行,我想打開一個新的活動。我怎樣才能做到這一點?

我的代碼:

public class MainActivity extends Activity { 

private ListView listView1; 
Weather weather_data[] =null; 
@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    final Weather weather_data[] = new Weather[] 
    { 
     new Weather(R.drawable.a, "Mercedes Benz"), 
     new Weather(R.drawable.b, "Xuv 500"), 
     new Weather(R.drawable.c, "Audi"), 
     new Weather(R.drawable.d, "Benz"), 
     new Weather(R.drawable.e, "Ferrari"), 
     new Weather(R.drawable.a, "Mercedes Benz"), 
     new Weather(R.drawable.b, "Xuv 500"), 
     new Weather(R.drawable.c, "Audi"), 
     new Weather(R.drawable.d, "Benz"), 
     new Weather(R.drawable.e, "Ferrari") 
    }; 

    WeatherAdapter adapter = new WeatherAdapter(this,R.layout.listview_item_row,weather_data); 

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

    View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null); 
    listView1.addHeaderView(header); 
    listView1.setAdapter(adapter); 

    listView1.setOnItemClickListener(new OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View v, int position,long id) 
    { 

     //int Integer = ((ImageView)v).getId(); 
     // Launching new Activity on selecting single List Item 
     Weather wea=(Weather) weather_data[position]; 
     String product=wea.title; 
     Intent intent = new Intent(getApplicationContext(),SecondActivity.class); 
     // sending data to new activity 
     intent.putExtra("index", product); 
     startActivity(intent); 
     } 
}) 
+2

您的代碼面臨的問題是什麼。 – Thalaivar

回答

0

調整下面的代碼在你的onItemClick()方法。

if(position == ROW_NO_1){ 
    Intent intent = new Intent(YOUR_CONTEXT,FirstActivity.class); 
    // sending data to new activity 
    intent.putExtra("index", VALUE_OF_THIS_ROW_ITEM); 
    startActivity(intent); 
} else if(position == ROW_NO_2){ 
    Intent intent = new Intent(YOUR_CONTEXT,SecondActivity.class); 
    // sending data to new activity 
    intent.putExtra("index", VALUE_OF_THIS_ROW_ITEM); 
    startActivity(intent); 
} else if(position == ROW_NO_3){ 
    Intent intent = new Intent(YOUR_CONTEXT,ThirdActivity.class); 
    // sending data to new activity 
    intent.putExtra("index", VALUE_OF_THIS_ROW_ITEM); 
    startActivity(intent); 
} 

注:它只是一個提示。你可以根據你的需要制定你的代碼。

順便問你目前面臨什麼問題?