2013-04-04 138 views
2

我一直在努力使用一些教程來將一個listview選項傳遞給一個新的活動,並使其成爲標題(我將在稍後使用它來完成其他任務)。我已成立了由什麼是最好的一個OnClickListener把裏面將一個變量從一個列表視圖傳遞給另一個活動

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

String[] items = { "Archery", "Badminton", "Cricket", "Dodgeball", "Equestrian", "Football", "Golf", "Handball", "Ice Hockey", "Ju Jitsu", "Karate", "Lacrosse", "Mountain Biking", "Netball" }; 

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

listView1.setAdapter(adapter); 

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

    ????? 

} 
}); 

感謝

編輯:額外的代碼

final TextView changetitle = (TextView) findViewById(R.id.detailedsocietyname); 
changetitle.setText(name); 
+0

格蘭所需的值你能張貼你所得到的logcat的? – jcw 2013-04-04 13:23:38

回答

2

對於所有你需要得到被選爲該項目:

final String selected = items[position]; 

或者作爲doctoror驅動器已建議

final String selected = (String) parent.getSelectedItem(); 

然後,你將需要該字符串作爲一個額外的最後傳遞給你的新活動

Intent i = new Intent(getApplicationContext(), MyClass.class); 
i.putExtra("name", selected); 
startActivity (i); 

然後在你的下一個活動

Intent in = getIntent(); 
    String name = in.getStringExtra(("name"));//gets name from intent 
+1

或更好:final String selected =(String)parent.getSelectedItem(); – 2013-04-04 12:04:31

+0

@DoctororDrive - 我不知道你可以這樣做,謝謝 – jcw 2013-04-04 12:06:16

+0

非常感謝,但它給我一個錯誤,由於代理Doctoror Drive的'父母'給了...我知道這是示例代碼,但是什麼'parent'代表 – Ryaller 2013-04-04 12:21:25

0

public void onItemClick(AdapterView<?> parent, View view,int position, long id)添加此代碼。

Intent i = new Intent(getApplicationContext(), NextClass.class); 
i.putExtra("selectedItem", items[position]); 
startActivity (i); 

在NextClass Activitiy獲得價值:

String SelectedItem = getIntent().getStringExtra("selectedItem"); 
0

公共無效onItemClick(適配器視圖父,觀景,INT位置,長ID)

String str = items[position]; 
Intent in = new Intent(getApplicationContext(), NextClass.class); 
in.putExtra("itemkey", str); 
startActivity (in); 

}

0

添加以下給你你有的活動listview

以下是variable將包含value要傳遞給other activity

Oncreate聲明聲明它

// Activity_1 

public final static String send_to_other_activity="ListViewSelected_ID"; 

下面的代碼添加到listView1.setOnItemClickListener

Intent i= new Intent(Recipe_List.this,Recipe_View.class); 
i.putExtra(send_to_other_activity, string.valueof(position)); 
// itz (key-value) pair on the left key thru which u will access it on other place. on the right value that you want to pass 
// Iam passing posiion to other activity here 
startActivity(i); 

現在在其他activity從提取此值通過添加以下語句其他活動的oonCreate

//Activity_2 

getdata_from_list =getIntent().getStringExtra(Activity_1.send_to_other_activity); 

現在你已經在getdata_from_list

相關問題