我试图在我自己创建的工具栏中放置一个居中的标题。它与基本工具栏完全按照预期工作,但出于不同的目的,我不得不切换到 Android.Support.V7,现在它不再工作,因为 FindViewById
返回 null
现在
这是我的代码:(在 Xamarin.Android 上工作)
MainPage.axml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbarMain"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorAccent"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imageView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:adjustViewBounds="true"
android:src="@drawable/bitmap_homepage" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="@+id/ListSpaces"
android:focusable="false" />
</LinearLayout>
</LinearLayout>
toolbarMain.xml
<?xml version="1.0" encoding="utf-8" ?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbarMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<TextView
android:id="@+id/toolbarMain_Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</android.support.v7.widget.Toolbar>
MainPageActivity.cs
public static string TitleFolder = "Welcome";
protected override void OnCreate(Bundle savedInstanceState) {
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.MainPage);
//Put toolbar
var toolbar = FindViewById<Toolbar>(Resource.Id.toolbarMain);
var ToolTitle = FindViewById<TextView>(Resource.Id.toolbarMain_Name);
SetSupportActionBar(toolbar);
SupportActionBar.SetDisplayShowTitleEnabled(false);
ToolTitle.Text = TitleFolder;
}
Visual Studio 给我的错误是
System.NullReferenceException: Object reference not set to an instance of an object.
当查看变量时,程序正在 Ressource.Designer 中查找所有 id,但返回 null 到 Tooltitle
但 toolbar
绝对没问题。
有什么想法吗?它慢慢地让我发疯,因为它在标准工具栏上运行得非常好...... 非常感谢
最佳答案
V7 支持工具栏有不同的设置,调用:
setSupportActionBar(findViewById(R.id.toolbarMain))
通过https://developer.android.com/training/appbar/setting-up了解详情。
关于c# - FindViewById 返回 null(只有一个,在 OnCreate 内部和 SetContentView 之后),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50393063/