如何从ListView中获取文本单击并通过intent将其放入另一个活动中

时间:2017-08-07 06:50:34

标签: android listview

此时app工作不正常。我想点击Listview中的项目,然后app必须进入mainactivity并在TextView中设置文本并从资源中将图片设置为ImageView。

第二项活动

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

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

    lvMain.setAdapter(adapter);

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

            String name = ((TextView) view).getText().toString();

            Intent intent = new Intent(ListHeroes.this, MainActivity.class);

            intent.putExtra("name", name);
            startActivity(intent);
        }
    });

主要活动

    protected void onActivityResult(int requestCode, int resultCode, Intent 
   data) {
    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case REQUEST_CODE_PLAYER1:
                String name1 = data.getStringExtra("name");
                playerName1.setText(name1);
                break;

1 个答案:

答案 0 :(得分:0)

在列表视图上,单击以下命令:

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

        String name = names.get(position);

        Intent intent = new Intent(ListHeroes.this, MainActivity.class);
        intent.putExtra("name", name);
        startActivity(intent);
    }
});

然后在MainActivity中获取MainActivity的onCreate中的名称:

String name = String name = getIntent().getStringExtra("name");