[英]Click on item in listview opens activity with a list based on the item that was clicked in android studio
I'm learning android with a simple app. 我正在用一个简单的应用程序学习android。 Is there a way so that when I click on an item in a listview that it goes to a new activity but it contains a certain list specific to the item that was clicked. 有没有一种方法,当我在列表视图中单击某个项目时,它会转到一个新活动,但是它包含特定于所单击项目的某个列表。
For Example: 例如:
List 1 ->(ActivityName) Cheese, apples, water 清单1->(活动名称)奶酪,苹果,水
List 2 ->(ActivityName) bread, grapes, soda 清单2->(ActivityName)面包,葡萄,汽水
List 3 ->(ActivityName) cake, oranges, milk 清单3->(ActivityName)蛋糕,橘子,牛奶
I know how to open a new activity and pass data with intents but I don't know how to contain a list as 1 item in a listview. 我知道如何打开一个新活动并通过意图传递数据,但是我不知道如何在列表视图中将列表作为一项包含在内。
All you do need is to pass a string list to your new activity. 您需要做的就是将字符串列表传递给新活动。
Here is a sample code: 这是一个示例代码:
ListView lstView;
ArrayAdapter<String> adapter;
ArrayList<String> list = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstView = (ListView) findViewById(R.id.main_activity_layout);
// Set the ArrayAdapter as the ListView's adapter.
adapter= new ArrayAdapter<String>(this, R.layout.simplerow, lstView);
list.add("Cheese, apples, water");
list.add("bread, grapes, soda");
list.add("cake, oranges, milk");
lstView.setAdapter(adapter);
adapter.notifyDataSetChanged();
lstView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
for (int j = 0; j < adapterView.getChildCount(); j++)
adapterView.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);
// change the background color of the selected element
view.setBackgroundColor(Color.LTGRAY);
selectedItemIndex = i;
Intent intent = new Intent(getApplicationContext(), AnotherActivity.class);
intent.putExtra("info", list.get(i));
intent.putExtra("selectedTemplateIndex", selectedItemIndex);
startActivityForResult(intent, 100);
}
});
}
So when the other activity loads you have to fetch the info that you have sent. 因此,当其他活动加载时,您必须获取已发送的信息。
String contactInfo;
int selectedTemplateIndex;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_contact);
// get the contact info from the contact activity so the user can see the selected contact info
Bundle extras = getIntent().getExtras();
if (extras != null) {
contactInfo = extras.getString("info");
selectedTemplateIndex = extras.getInt("selectedTemplateIndex");
}
.
.
.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.