【问题标题】:How to dynamically set title on a Xamarin Android dialog activity?如何在 Xamarin Android 对话框活动上动态设置标题?
【发布时间】:2017-02-23 07:19:44
【问题描述】:

我在 Xamarin Android 上有 2 个活动。请注意,第二个设置为以对话框形式打开。

[Activity(Label = nameof(ActivityOne), HardwareAccelerated = true, ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)]
public class ActivityOne : Activity { ... }

[Activity(Label = nameof(ActivityTwo), HardwareAccelerated = true, ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait, Theme = "@android:style/Theme.Holo.Dialog")]
public class ActivityTwo : Activity { ... }

第一个这样调用第二个:

var activity = new Intent(this, typeof(ActivityTwo));
StartActivity(activity);

当第二个活动打开时,我希望能够在对话框上动态设置标题。

我尝试在创建第二个活动时这样做:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.ActivityTwo);
    SetTitle(Resource.Id.title);

    ...
}

其中 title 被定义为 ActivityTwo.axml 中的“隐藏”文本视图:

<TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/title"
  android:text="Example Title"
  android:visibility="gone" />

但这就是我在运行应用程序时得到的对话框标题:

同样没有 SetTitle 行,标题只是“ActivityTwo”。谁能帮我解决这个问题?

【问题讨论】:

    标签: xamarin.android


    【解决方案1】:

    解决方案就是在 OnCreate() 中使用以下内容

    this.Title = "ExampleTitle";
    

    【讨论】:

    • 绝对!我错过了那个。不错
    【解决方案2】:

    如果你只想设置标题,Activity顶部的Label属性就是标题。这就是为什么如果你不 SetTitle 它会显示 ActivityTwo 因为你是通过使用 nameof(ActivityTwo) 告诉它这样做的。

    [Activity(Label = "Here the title you want to show", HardwareAccelerated = true, ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait, Theme = "@android:style/Theme.Holo.Dialog")]
    public class ActivityTwo : Activity { ... }
    

    关于您尝试的内容,您应该将 Resource.String 传递给该方法。假设您在 string.xml 文件 HelloActivityTitle

    中有一个条目
    SetTitle(Resource.String.HelloActivityTitle);
    

    这也将设置标题。

    第三个选项是Window.SetTitle,它接收string 或Java CharSequence”。

     Window.SetTitle("Here the title you want to show");
    

    更新

    Window.SetTitle("Here the title you want to show");
    

    应该从OnResume 方法调用。

    但是使用下面的方法可以从OnCreate调用它

    SetTitle(Resource.String.HelloActivityTitle);
    

    清理并重建您的解决方案,以防万一。

    希望对你有帮助。-

    【讨论】:

    • 谢谢!我忘记写的一件事是我想动态设置标题,而上述解决方案目前都不适合我。您能否更新您的答案来解决这个问题?我也在更新问题。
    猜你喜欢
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多