以编程方式更改工具栏时出现奇怪问题

时间:2016-02-12 12:58:09

标签: android android-fragments android-actionbar android-toolbar

当我尝试以编程方式更改 ToolBar 时,我遇到了一些麻烦。

当我从代码中更改 ToolBar 标题时,当我在真实设备上运行程序时,我的工具栏标题是“MyAppName @ 2131558664”,但我只设置了“MyAppName”

我还有 ViewPager 带片段,在其中一个片段中我得到工具栏并更改工具栏菜单(添加 SearchView ),当我也启动程序并打开 SearchView 我的查询也包含此“@ 2131558664”。为什么会这样?我该如何解决? 感谢回复

Toolbar.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="?android:actionBarSize"
    app:theme="@style/MyToolBar"
    android:layout_centerHorizontal="true"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Dark">
    </android.support.v7.widget.Toolbar>

MyToolBar主题:

<style name="MyToolBar" parent="Theme.AppCompat.Light">
        <item name="android:text">@style/TextAppearance.Widget.Event.Toolbar.Title</item>
        <item name="android:windowActionBarOverlay">true</item>
        <!-- Support library compatibility -->
        <item name="windowActionBarOverlay">true</item>
        <item name="android:textColorPrimary">@color/colorAccent</item>
        <item name="android:textColorSecondary">@color/colorAccent</item>

    </style>

我更改工具栏:

的代码段
        Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle("MyAppName");

3 个答案:

答案 0 :(得分:0)

之所以发生这种情况,是因为你写了“android:text”而不是文本,你传递了一个主题,而不是文本,因为你引用了一个对象而不是一个字符串,你得到了 - @ 2131558664。 由于您添加了一段代码来设置标题,因此您实际连接了两个字符串。 它有点像写作:

setTitle("my app" + "@2131558664");

作为参考,如果您将查找您的R文件(如在R.id.my_textView中),例如,您将看到一个填充了这些文件的大文件:

int attr actionBarTheme 0x7f010060
int attr actionBarWidgetTheme 0x7f010061

所以我猜测文本“@ 2131558664”指的是该主题的id。

您还需要了解的一些事情:

1.R文件中的每个id实际上都是一个int,即使它中有一个字母。

2.如果您在TextView或任何类似的任何小部件上使用“toString()”方法,您将获得类似的结果,除非它是一个字符串然后您将获得字符串本身。

3.用户无法编辑R文件,以及为什么必须使用id方法查找视图,该方法实际上通过id将对象连接到您正在创建的对象。

一个很好的例子是从文本中获取文本和编辑文本

EditText et = (EditText) findViewById(R.id.editText);
//EditText - this is the object you create
//R.id.editText - thats the int in the memory


et.getText();
//XXXXX this is thee wrong way to get a string from edit text since
//its return and editable and if you will pass it to a text view you
//will get the int with represent the id in the memory. 



et.getText().toString();
//this is the right way to get a string from an edit text since it
//return a string

你应该尝试一下,只是为了娱乐和知识= D

答案 1 :(得分:0)

尝试将字符串移动到string.xml文件并使用getResources().getString(R.string.appTitle); 从string.xml读取字符串。

还尝试清理项目并检查xml上是否有任何遗漏或错误 资源文件

答案 2 :(得分:0)

好的,我已经解决了我的问题。 当我删除

时,这个奇怪的文字消失了

<item name="android:text">@style/TextAppearance.Widget.Event.Toolbar.Title</item>

我不知道为什么会发生这种情况,如果有人知道请解释我。

相关问题