无论如何,在Java运行时是否可以更改字符串。 请检查我更新的问题 在mainActivity.java中,我想更改菜单项标题
我可以在MainActivity.java中设置菜单项标题吗,因为我想在某些情况下更改标题,如何在Java文件中设置标题...
strings.xml
<img th:src="@{/images/logo.jpg}" width="217" height="43" alt="" >
我在其中使用字符串的导航菜单
menu_nevigation.xml
secret_word = 'COMPUTER'
clue = str(len(secret_word) * '-') # this step gives the user the nos of characters in secret_word
user_guess = input("Type a single letter here, then press enter: ")
user_guess = user_guess.upper()
if user_guess in secret_word:
index = user_guess.find(user_guess) # this finds the index of the user guess in secret_word
clue = clue[:index] + user_guess + clue[index+1:]
print("The word now looks like this: " + clue)
MainActivity.java
<resources>
<string name="app_name">check</string>
<string name="title_home">Home</string>
<string name="title_dashboard">Dashboard</string>
<string name="title_notifications">Notifications</string>
</resources>
答案 0 :(得分:1)
根据您对注释的解释,我猜测您想在运行时更改R.string文件夹。这是不可能的。实际上,无法在运行时修改整个res文件夹。
如果要在运行时更改菜单标题
menu = mynavigationview.getMenu() //mynavigationview is the name of your navigationcomponent
MenuItem menuitem = menu.getItem(*insert item index here*); //menu is the menu here
menuitem.setTitle("Your title");
这应该有效。如果要保留标题,则应使用共享的首选项,并在每次启动应用程序时从首选项中进行设置。
答案 1 :(得分:0)
首先,您需要使用findViewById(R.id.nav_view_id)获取navigationView,然后:
Menu menu = navigationView.getMenu();
MenuItem item = menu.findItem(R.id.your_menuItem_id);
// or MenuItem item = menu.getItem(0) if you have one MenuItem
然后,您将创建一个方法,您可以在其中选择当前所需的标题。
//for example
protected String getMyTitle(){
if(/*something*/){
return getResources().getString(R.id.title_home);
}else if(/*something*/){
return getResources().getString(R.id.title_dashboard);
}else{
return getResources().getString(R.id.title_notifications);
}
}
结果,我们将文本放入了项目中。
item.setTitle(getMyTitle());
此链接也可以为您提供帮助:link