如何用不同的数据调用相同的活动(相同的布局)? [英] How to call same activity (same layout) with different data?

查看:57
本文介绍了如何用不同的数据调用相同的活动(相同的布局)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是android领域的新手.我正在开发餐厅菜单应用程序,我已经创建了显示餐厅名称的列表视图.当我在列表视图中选择任何一项时,它将启动另一项活动,它包含显示所选项目详细说明的文本视图字段.类似地,当我选择其他项目时,它应该启动相同的活动,但是数据应该属于该选定项目,如何实现这一目标?如果我使用sqlite数据库作为数据源.

I am new to android field. i am developing restaurant menu application, i have created list view which shows names of items in restaurant. when i select any one item in list view it will launch another activity, it contains text view field showing detail description of selected item. similarly when i select other items, it should launch same activity but data should be of that selected item, how to achieve this ? if i use sqlite database for data source.

推荐答案

您需要传递值onItemClick:

You need to pass the values onItemClick:

Intent intent = new Intent(context, CalledActivity.class);
        intent.putExtra(key, value);
        startActivity(intent);

如果您想从被调用的Activity中返回一些数据,则可以使用startActivityForResult()如下:

If you want some data back from called Activity then you can use startActivityForResult() as:

Intent intent = new Intent(context, CalledActivity.class);
        intent.putExtra(key, value);
        startActivityForResult(intent, requestCode);

在被叫活动中,您可以将数据设置为:

In called activity you can set data as:

setResult(RESULT_OK, intent);

注意:在这里,您可以按意图设置值,并将其传递给setResult().

Note: Here you set the value in intent and pass it to setResult().

返回调用活动后,您可以通过覆盖获取数据:

On returning back to calling Activity you can get data by overriding:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            //Get data from Intent "data" and do your task here....
        }
    }

注意:您可以通过Intent传递原始数据类型值,如果要传递其他类型,则必须使用Bundle这样.

Note: You can pass primitive data type values thru Intent and if you want to pass other types then you have to use Bundle like this.

Bundle data = new Bundle();
        data.putIntArray(key, value);

//same way you can set other values.......
//Now set this Bundle value to Intent as you do for primitive type....

Intent intent = new Intent(context, CalledActivity.class);
        intent.putExtra(data);
        startActivity(intent);

在活动中接收数据:

//For primitive values:
DataType var_name = getIntent().getExtras().get(key);

//For Bundle values:
Bundle var_name = getIntent().getExtras().getBundle(key);

这篇关于如何用不同的数据调用相同的活动(相同的布局)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆