从首选项更改布局背景
我想通过用户从首选项中的 ListPreference 中选择的内容来更改布局的背景。我在做这件事时遇到了一点麻烦。我已经在 Java 中设置了首选项:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
并为 ListPreference 设置了一个数组。
这是我从首选项中获取字符串以根据所选内容更改背景的位置:
SharedPreferences SP = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String strFavTeam = SP.getString("keyFavTeam", "0");
LinearLayout linearLayout = (LinearLayout) this.findViewById(R.layout.main);
if(strFavTeam.equals("0")){
linearLayout.setBackgroundResource(R.drawable.first_screen);
}
if(strFavTeam.equals("73")){
linearLayout.setBackgroundResource(R.drawable.tennessee_screen);
}
if(strFavTeam.equals("67")){
linearLayout.setBackgroundResource(R.drawable.georgia_screen);
}
每次从 ListPreference 中选择田纳西州(其值为 73)时,我都会强制关闭。
请帮忙! 谢谢!!
I want to change the background of a layout through what the user selects from a ListPreference in the preferences. I am having a little bit of trouble doing this. I have set up the preferences in my Java:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
and have an array set up for the ListPreference.
This is where I get the string from the preferences to change the background based on what is selected:
SharedPreferences SP = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String strFavTeam = SP.getString("keyFavTeam", "0");
LinearLayout linearLayout = (LinearLayout) this.findViewById(R.layout.main);
if(strFavTeam.equals("0")){
linearLayout.setBackgroundResource(R.drawable.first_screen);
}
if(strFavTeam.equals("73")){
linearLayout.setBackgroundResource(R.drawable.tennessee_screen);
}
if(strFavTeam.equals("67")){
linearLayout.setBackgroundResource(R.drawable.georgia_screen);
}
I get a force close every time I choose Tennessee (which has a value of 73) from the ListPreference.
Please help!
Thanks!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在使用布局 ID 搜索视图。除了
null
之外,它永远不会返回任何内容。您需要搜索要更改的 LinearLayout 视图的 id。它类似于R.id.?
,其中?
是您在 main.xml 中分配给视图的任何 id。You're searching for a view using a layout id. That's never going to return anything except
null
. You need to search for the id of the LinearLayout view you want to change. It will be something likeR.id.?
where?
is whatever id you assigned to the view in main.xml.