将数据从一个 activity 动态添加到另一个

Dynamically add data from one activity to another

我正在开发一个显示怪物列表的小应用程序。您可以点击每个怪物查看有关该怪物的更多信息。

列表在我的 xml 布局文件中的 TableLayout 中。

但是查看代码,很容易看出我添加的怪物越多,事情就越容易失控。

我在想,是否有更好的方法来确定单击了哪个怪物以及如何获取从怪物列表视图传递到怪物信息视图的所需信息。

到目前为止,这是我的代码。它工作正常,但我知道它不是很好,因为我必须为每个添加到列表中的新怪物添加一个新的 case 语句。

public void AddNewView(View view) {
        //get selected button view
        switch(view.getId())
        {
            //get textview & imageview monsters from xml 
            //get monster picture and monster info from xml
            case R.id.showMonsterButton1:
                iv  = (ImageView) findViewById(R.id.monster1_icon);
                tv = (TextView) findViewById(R.id.monster1_info);
                ShowMonsterInfoView(tv, iv);
                break;

            case R.id.showMonsterButton2:
                iv  = (ImageView) findViewById(R.id.monster2_icon);
                tv = (TextView) findViewById(R.id.monster2_info);
                ShowMonsterInfoView(tv, iv);
                break;

            case R.id.showMonsterButton3:
                iv  = (ImageView) findViewById(R.id.monster3_icon);
                tv = (TextView) findViewById(R.id.monster3_info);
                ShowMonsterInfoView(tv, iv);
                break;

            case R.id.showMonsterButton4:
                iv  = (ImageView) findViewById(R.id.monster4_icon);
                tv = (TextView) findViewById(R.id.monster4_info);
                ShowMonsterInfoView(tv, iv);
                break;
        }
    }

    public void ShowMonsterInfoView(TextView tv, ImageView iv) {
        Intent intent = new Intent(this, DisplayMonsterInfo.class);
        String text_tag = tv.getTag().toString();
        String image_tag = iv.getTag().toString();
        Bundle extras = new Bundle();
        extras.putString("name", text_tag);
        extras.putString("avatar", image_tag);
        intent.putExtras(extras);
        startActivity(intent);

    }

根据如何获取点击了哪个怪物。如果您使用 RecyclerView,如果 ListView 只是 setOnItemClickListener。通过单击项目的位置,您可以从包含怪物对象的列表中获取对象,然后从那里获取 id

将有关怪物的数据放入数据库中,并将怪物的 id 传递给另一个 activity,您将从数据库中获取数据。

您可以做的只是将数据保存到数据库并为每个 monster.On 的点击分配一个唯一的 ID,然后将 ID 传递给下一个 activity 并获取有关怪物的数据。

另一方面,如果您不想保存数据,请将带有点击意图的数据传递给其他 activity(即如果您在第一个 activity 中有数据) .

由于您必须添加视图,我建议您使用回收器视图,您可以在其中简单地在您提供的列表中添加项目并调用 notifyDataSetChanged()。为此使用 table 布局可能不是好主意。

将您的怪物列表保存在 List 对象中,并将其传递到 ArrayAdapter 对象中,该对象将用于填充 ListView。在 List 对象中,您可以使用 obj.add(monster_name) 动态添加更多怪物。在 setOnItemSelected 方法中,将选定的怪物保存在 static 字符串对象中,可以在任何 Activity 中使用 MonsterListActivity.monster_name 访问该对象。使用它从 file/database.

中提取数据