嘿,我正在android工作室的應用程序工作。我有一個列表視圖,當我做出選擇時,我想在另一個活動中將該選擇添加到另一個列表視圖。什麼是最簡單/最好的方法來做到這一點?我試過putExtra沒有任何運氣。任何例子或想法都會很棒。感謝你們。如何將數據從一個活動發送到另一個listview?
感謝大家的例子,他們已經讓我明白了很多美好的意圖系統。我一直在嘗試每個人都發布的不同例子,而且我一直陷入困境。我們的目標很簡單,就是有我從Walmart.java文件列表視圖中選擇在GiftsSelected.java列表視圖我有另一個地方打開相應的活動所以顯示的項目我並不需要它立即打開新的活動。 這裏是我的代碼:
這是Walmart.java
public class Walmart extends ActionBarActivity {
private String[]giftarray = {
"Apple" ,
"Bananas",
"Bed",
"Beef",
"Bottle",
"Bread",
"Broccoli",
"Carrots",
"Cat",
"Chicken",
"Chocolate",
"Computer",
"Cow",
"Crow",
"Dog",
"Dolphin",
"Dove",
"Drawer",
"Egg",
"Fish",
"Fork",
"Fridge",
"Giraffe",
};
Intent a = new Intent(Walmart.this,GiftsSelected.class);
private ListView giftListView;
private ArrayAdapter arrayAdapter;
ArrayList<String> list = new ArrayList<String>();
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){}
public boolean onContextItemSelected(MenuItem item){
return true;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_walmart);
getSupportActionBar().hide();
giftListView = (ListView) findViewById(R.id.gift_list1);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_gallery_item, giftarray);
giftListView.setAdapter(arrayAdapter);
giftListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = "Item added to registry";
list.add(item2);
a.putStringArrayListExtra("list",list);
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
這是我的GiftsSelected.java代碼:
public class GiftsSelected extends ActionBarActivity {
private ListView giftListView;
private ArrayAdapter arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
ArrayList<String> list = new ArrayList<String>();
//This makes my app crash which makes me think I did this wrong...
list = getIntent().getStringArrayListExtra("list");
String[] giftarray = new String[list.size()];
list.toArray(giftarray);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gifts_selected);
getSupportActionBar().hide();
giftListView = (ListView) findViewById(R.id.gift_list1);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_gallery_item, giftarray);
giftListView.setAdapter(arrayAdapter);
giftListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = "Item added to your registry";
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}