65.9K
CodeProject 正在变化。 阅读更多。
Home

MonoAndroid:调用次级活动

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.82/5 (15投票s)

2013年10月10日

CPOL

4分钟阅读

viewsIcon

25713

downloadIcon

637

让我们来理解如何调用辅助 Activity 以及如何从辅助 Activity 返回数据。

引言

在本文中,我将尝试解释如何从 MainActivity 激活/启动第二个 Activity,这将是我们的步骤 1,在第二步中,我们将讨论如何将数据从第二个 Activity 返回到主 Activity。我将使用 MonoAndroid 来构建此应用程序,有关系列中先前文章的链接,请参阅文章底部。

在本文中,我将创建一个印度电影明星传记应用程序,其中主 Activity 将包含一个 ListView,显示电影明星的小图片和姓名,点击某个项目将进入一个新的 Activity,该 Activity 将显示所选电影明星的年龄和简短传记等信息。

我们一步一步地前进

  1. 选择 New -> Solutions 创建 Android 应用程序,并将其命名为 “CallingSecondActivity
  2. 现在,在 Layout 下的 Main.axml 文件中进行以下更改,添加 UI 代码后,它看起来大致如下:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">  
        <ListView
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/lstFlimStars" />
    </LinearLayout>

    在此布局中,我添加了一个 ListView,我将用电影明星的姓名和图片填充它。

  3. 现在,添加一个名为 FlimStarInformationModal 的类,并继承自抽象泛型类 Java.Lang.Object,以下是 FlimStarInformationModal 类的代码。添加代码后,它看起来像这样:
    [Serializable]
    public class FlimStarInformationModal :Java.Lang.Object
    {
        public string FilmStarName {get;set;}
        public int FlimStarImageID {get;set;}
        public int FlimStarIconImageID {get;set;}
        public string FilmStarBio {get;set;}
        public string FilmStarAge { get; set;}
    }

    此模型类的每个对象都将由 listview 和辅助 Activity 用于显示数据。

  4. 由于我们没有数据库或 Web 服务来获取数据,因此我在 MainActivity 中创建了一个方法,其中我将硬编码数据以在不同的 UI 控件中显示。
    void CreateProjectDS ()
    {
        _lstFlimStarInfo = new List<flimstarinformationmodal> ();
        _lstFlimStarInfo.Add (new FlimStarInformationModal () {
            FilmStarName = "Amitabh Bachan",
            FilmStarAge = "71 Year Old",
            FlimStarImageID = Resource.Drawable.ABSR,
            FlimStarIconImageID = Resource.Drawable.ABSRIco,
            FilmStarBio = "Amitabh Harivansh Bachchan (born 11 October 1942) is an Indian film actor. 
              He first gained popularity in the early 1970s as the \"angry young man\" 
              of Hindi cinema, and has since appeared in over 180 Indian films in a career spanning 
              more than four decades. Bachchan is widely regarded as one of the greatest and most 
              influential actors in the history of Indian cinema.So total was his dominance of the 
              movie scene in the 1970s and 1980s that the French director Francois Truffaut called 
              him a \"one-man industry\"." +
             "shares with Kamal Hassan and Mammootty), a number of awards at international 
             film festivals and award ceremonies and fourteen Filmfare Awards. 
             He is the most-nominated performer in any major acting category at Filmfare, 
             with 39 nominations overall. In addition to acting, Bachchan has worked as a 
             playback singer, film producer and television presenter. He also had a stint 
             in politics in the 1980s. The Government of India honoured him with the Padma 
             Shri in 1984 and the Padma Bhushan in 2001 for his contributions towards the arts.",
        });
    
        _lstFlimStarInfo.Add (new FlimStarInformationModal () {
            FilmStarName = "Shahrukh Khan",
            FlimStarImageID = Resource.Drawable.SRK,
            FlimStarIconImageID = Resource.Drawable.SRKIco,
            FilmStarAge = "48 Year Old",
            FilmStarBio = "Shahrukh Khan (born 2 November 1965), often credited 
              as Shah Rukh Khan and informally referred as SRK, is an Indian film actor. 
              Referred to in the media as \"Badshah of Bollywood\", \"King Khan\" 
              and \"King of Romance\", Khan has acted in 75 Hindi films in genres ranging 
              from romantic dramas to action thrillers.[4][5][6][7] His contributions to the film 
              industry have garnered him numerous achievements, including fourteen Filmfare Awards 
              from thirty nominations. His eighth Filmfare Best Actor Award win made him the most 
              awarded Bollywood actor of all time in that category, tied only with actor Dilip Kumar. 
              In 2005, the Government of India honoured him with the Padma Shri for his contributions 
              towards Indian cinema." +
            "Khan is considered to be one of the biggest film stars in cinematic history, 
              with a fan following claimed to number in the billions; in 2011, the Los Angeles 
              Times called him \"the world's biggest movie star.\"[19] He has also 
              been regularly featured in the listing of the most powerful names in Indian Cinema 
              and in 2008, Newsweek named him one of the 50 most powerful people in the world.[5] 
              Khan has an estimated net worth of over US $600 million(INR25 billion).",
        });
    
        _lstFlimStarInfo.Add ( new FlimStarInformationModal () {
            FilmStarName = "Hrithik Roshan",
            FlimStarImageID = Resource.Drawable.HR,
            FlimStarIconImageID = Resource.Drawable.HRIco,
            FilmStarAge = "39 Year Old",
            FilmStarBio = "Hrithik Roshan (born on 10 January 1974) is an Indian film actor 
              and professional dancer.[1][2] Having appeared as a child actor in several 
              films throughout the 1980s, Roshan made his film debut in a leading role in 
              Kaho Naa... Pyaar Hai in 2000. His performance in the film earned him Filmfare 
              Awards for Best Actor and Best Male Debut. He followed it with leading roles in Fiza 
              and Mission Kashmir (both released in 2000) and a supporting part in the blockbuster 
              Kabhi Khushi Kabhie Gham (2001)" +
            "Following through with several unnoticed performances from 2002 to 2003, he starred 
              in the blockbusters Koi... Mil Gaya (2003) and its sequel Krrish (2006), 
              both of which won him numerous Best Actor awards.[3] Roshan received his 
              third Filmfare Award for Best Actor in 2006 for his performance in the action 
              film Dhoom 2, and his fourth for Jodhaa Akbar[4] for which he was also awarded 
              at the Golden Minbar International Film Festival. He later received further 
              acclaim for his work in Guzaarish (2010), Zindagi Na Milegi Dobara (2011) 
              and Agneepath (2012), his biggest commercial success so far. These accomplishments 
              have established him as a leading contemporary actor of Hindi cinema.",
        });
    }
  5. 现在,由于我们使用的是自定义模型类,因此我们必须为 ListView 编写自定义适配器来显示其中的数据。您可以在此处阅读更多有关创建自定义 BaseAdapter 的信息。

    现在,我们名为 FlimStarAdapater 的自定义 base adapter 的代码如下所示:

    internal class FlimStarAdapater:BaseAdapter<FlimStarInformationModal>
    {
        Activity _mainActivity;
        List<FlimStarInformationModal> _lstFlimStarInfo;
    
        public FlimStarAdapater (Activity mainActivity,
                  List<FlimStarInformationModal> lstFlimStarInfo)
        {
            _mainActivity = mainActivity;
            _lstFlimStarInfo = lstFlimStarInfo;            
        }
    
        #region implemented abstract members of BaseAdapter
        public override long GetItemId (int position)
        {
            return position;
        }
        public override View GetView (int position, View convertView, ViewGroup parent)
        {
            var currentObj = this [position];
            if (convertView == null)
                convertView =_mainActivity.LayoutInflater.Inflate (
                     Android.Resource.Layout.ActivityListItem,null);
    
            convertView.FindViewById<TextView> (Android.Resource.Id.Text1).Text = currentObj.FilmStarName;
            convertView.FindViewById<ImageView> 
              (Android.Resource.Id.Icon).SetImageResource(currentObj.FlimStarIconImageID);
    
            return convertView;
        }
        public override int Count {
            get {
                return _lstFlimStarInfo != null ? _lstFlimStarInfo.Count : -1;
            }
        }
        #endregion
        #region implemented abstract members of BaseAdapter
        public override FlimStarInformationModal this [int index] {
            get {
                return _lstFlimStarInfo != null ? _lstFlimStarInfo[index] : null;
    
            }
        }
        #endregion
    }

    现在我们的 baseadapter 已准备就绪,数据源也已准备就绪,我们可以使用以下代码将自定义适配器附加到 MainActivity.cs 文件中的 ListView。

    var lstvwObject = this.FindViewById<ListView> (Resource.Id.lstFlimStars);
    
    if (lstvwObject != null) {
        lstvwObject.Adapter = new FlimStarAdapater (this, _lstFlimStarInfo);
        lstvwObject.ItemClick += OnFilmStarListViewClickSA;
    }

    当我们单击 listview 中的项目时,将调用 OnFilmStarListViewClickSA 方法。在这里,我们为传递信息给第二个 Activity 并启动它编写了代码。 FullInformationActivity 是第二个 Activity 类的名称,它将处理主 Activity 发送的数据。

    void OnFilmStarListViewClickSA  (object sender, AdapterView.ItemClickEventArgs e)
    {
        Intent myIntent = new Intent (this, typeof(FullInformationActivity));
        var cItem = _lstFlimStarInfo[e.Position];
        myIntent.PutExtra ("FilmStarName", cItem.FilmStarName);
        myIntent.PutExtra("FlimStarImageID", cItem.FlimStarImageID);
        myIntent.PutExtra("FilmStarBio", cItem.FilmStarBio);
        myIntent.PutExtra("FilmStarAge", cItem.FilmStarAge);
        StartActivity(myIntent);
    }
  6. 现在,添加一个名为 FullInformationLayout.xaml 的布局,它将作为 FullInformationActivity.cs 的 UI 前端,并添加以下代码:
  7. <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:minWidth="25px"
        android:minHeight="25px">
        <RelativeLayout
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:id="@+id/relativeLayout1">
            <TextView
                android:text="Name"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_width="121.5dp"
                android:layout_height="wrap_content"
                android:id="@+id/lblName"
                android:layout_marginLeft="14.2dp"
                android:layout_marginTop="10.0dp"
                android:textColor="#FF00FF" />
            <TextView
                android:text="Age"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_width="121.5dp"
                android:layout_height="wrap_content"
                android:id="@+id/lblAge"
                android:layout_marginLeft="14.2dp"
                android:layout_marginTop="10.0dp"
                android:layout_below="@+id/lblName" />
            <ImageView
                android:src="@android:drawable/ic_menu_gallery"
                android:layout_width="96dp"
                android:layout_height="120dp"
                android:id="@+id/imageView1"
                android:layout_toRightOf="@+id/lblName"
                android:layout_marginLeft="35.0dp"
                android:layout_marginBottom="4.0dp" />
            <ScrollView
                android:minWidth="25px"
                android:minHeight="25px"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:id="@+id/scrollView1"
                android:layout_marginLeft="14.2dp"
                android:layout_below="@+id/imageView1"
                android:layout_above="@+id/btnGoBack">
                <TextView
                    android:text="Biography"
                    android:textAppearance="?android:attr/textAppearanceSmall"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:id="@+id/lblBiography"
                    android:layout_marginRight="4dp"
                    android:layout_weight="1"
                    android:textColor="#FF0000" />
            </ScrollView>
            <Button
                android:text="Go Back!"
                android:layout_width="fill_parent"
                android:layout_height="50dp"
                android:id="@+id/btnGoBack"
                android:layout_alignParentBottom="true"
                android:layout_marginTop="8.0dp" />
        </RelativeLayout>
    </LinearLayout>

    UI 创建步骤如下:

    • 添加 RelativeLayout
    • RelativeLayout 中添加一个 ID 为 "@+id/lblName"TextView
    • 添加另一个 ID 为 "@+id/lblAge" 的 TextView,并将 RelativeLayout 的依赖属性 android:layout_below 设置为 "@+id/lblName",将其放置在名称 TextView 的下方。
    • 添加一个 ID 为 "@+id/imageView1"ImageView,并将 RelativeLayout 的依赖属性 android:layout_toRightOf 设置为 "@+id/lblName",将其放置在名称 TextView 的右侧。
    • 放置一个 ID 为 "@+id/btnGoBack" 的按钮,并将其 android:layout_alignParentBottom 设置为 "true",使其位于布局的底部。
    • 添加 ScrollView,因为传记内容很可能超出屏幕。在此,我设置了两个 RelativeLayout 依赖属性 android:layout_below="@+id/imageView1"android:layout_above="@+id/btnGoBack",用于将 ScrollView 放置在 ImageViewButton 之间。
    • 最后,添加一个 ID 为 "@+id/lblBiography"TextView,它将显示电影明星的传记。
    • 我设置了 UI 控件的布局边距,以使 UI 看起来更好。

    创建后,UI 看起来是这样的:

    被调用的 Activity UI
  8. 现在,添加名为 FullInformationActivity 的 Activity 类,它将是 FullInformationLayout 的后端。在此,我添加了一个方法来更新从 MainActivity 发送的数据。
  9. void UpdateActivityWithInformation ()
    {
        var txtFilmStarInfo = FindViewById<TextView> (Resource.Id.lblName);
        var txtage = FindViewById<TextView> (Resource.Id.lblAge);
        var txtFilmStarBio = FindViewById<TextView> (Resource.Id.lblBiography);
        var ivFilmStar = FindViewById<ImageView> (Resource.Id.imageView1);
    
        txtFilmStarInfo.Text = this.Intent.GetStringExtra("FilmStarName");
        ivFilmStar.SetImageResource(this.Intent.GetIntExtra("FlimStarImageID",-1));
        txtFilmStarBio.Text = this.Intent.GetStringExtra("FilmStarBio");
        txtage.Text = this.Intent.GetStringExtra("FilmStarAge");
    }

    以下是 btnGoBack 的代码,我将调用 Finish() 来关闭 Activity。

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        SetContentView (Resource.Layout.FullInformationLayout);
        Button btnGoBack = FindViewById<Button> (Resource.Id.btnGoBack);
    
        if(btnGoBack!=null)
            btnGoBack.Click += (object sender, EventArgs e) => 
        {
            SetResult(Result.Ok);
            Finish();
        };
    }


  10. 现在构建并运行应用程序
    初始屏幕 点击 ListView 项目时 点击“返回”按钮时
     
  11. 这里有一个简单的流程图来解释我们上面所做的内容
  12. 流程图 I


  13. 现在,让我们开始处理步骤 2:从被调用的 Activity 返回数据。为此,我们需要使用 StartActivityForResult API 传递 Intent 数据,就像之前使用 StartActivity API 一样,并使用一个唯一的请求代码来标识返回的请求。
    ///--- In MainActivityClass
    const int MY_RESULT_CODE = 101;
    ///-- In OnFilmStarListViewClickSA Method
    StartActivityForResult(myIntent,MY_RESULT_CODE);

  14. 现在修改 btnGoBack 的点击代码,从被调用的 Activity 返回数据,您需要创建一个 Intent,将数据放入其中,并使用 SetResult 将数据推回主 Activity。
  15. Button btnGoBack = FindViewById<Button> (Resource.Id.btnGoBack);
    
    if(btnGoBack!=null)
        btnGoBack.Click += (object sender, EventArgs e) => 
    {
        Intent myIntent = new Intent();
        myIntent.PutExtra("returnData", this.Intent.GetStringExtra("FilmStarName"));
        SetResult(Result.Ok,myIntent);
        Finish();
    };
  16. 您已经使用了 StartActivityForResult 来启动 Activity,并且也从被调用的 Activity 返回了数据。为此,您必须重写 OnActivityResult 来处理返回的数据。它有三个参数:requestCoderesultCodeIntentDatarequestCode 包含启动 Activity 时发送的 requestCoderesultCodeintentData 包含在被调用 Activity 的 SetResult API 中设置的值。
  17. protected override void OnActivityResult(int requestCode, Result resultCode, Intent data){
        if (requestCode == MY_RESULT_CODE) {
            switch (resultCode) {
            case Result.Ok:
                Toast.MakeText (this, data.GetStringExtra ("returnData"), ToastLength.Long).Show ();
                break;
            default:
                break;
            }
    
        }
    }
  18. 再次构建并运行
  19. 初始屏幕 点击 ListView 项目时 点击“返回”按钮时

    您可以在第三张图片中看到显示的 Toast,显示了从被调用的 Activity 返回的数据。

  20. 这里有一个简单的流程图来解释我们上面所做的内容
  21. 流程图 II

关注点

我使用了MonoAndroid (C#)Xamarin Studio来构建本教程。请留意,如果我继续学习,您可能会期待更多文章即将发布。

尽管Xamarin Studio是专有软件,但他们提供了免费的入门版本来构建、测试和发布Android应用程序。我正在使用它来学习。

本系列文章!

本系列技巧/窍门

历史

  • 2013 年 10 月 10 日:第一个版本。
  • 2013 年 11 月 5 日:更新系列中的文章
  • 2013年11月22日:更新了其他文章部分
© . All rights reserved.