繁体   English   中英

单击列表视图中的项目可打开活动,其中包含基于android studio中单击的项目的列表

[英]Click on item in listview opens activity with a list based on the item that was clicked in android studio

我正在用一个简单的应用程序学习android。 有没有一种方法,当我在列表视图中单击某个项目时,它会转到一个新活动,但是它包含特定于所单击项目的某个列表。

例如:

清单1->(活动名称)奶酪,苹果,水

清单2->(ActivityName)面包,葡萄,汽水

清单3->(ActivityName)蛋糕,橘子,牛奶

我知道如何打开一个新活动并通过意图传递数据,但是我不知道如何在列表视图中将列表作为一项包含在内。

您需要做的就是将字符串列表传递给新活动。

这是一个示例代码:

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);
        }
    });
}

因此,当其他活动加载时,您必须获取已发送的信息。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM