我正在使用SlidingMenu for Android,我有一个"菜单片段"像这样:
public class MenuListFragment extends ListFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list, null);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] items = getResources().getStringArray(R.array.menu);
ArrayAdapter<String> colorAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, items);
setListAdapter(colorAdapter);
getListView().setSelector(R.drawable.menu_selector);
}
@Override
public void onListItemClick(ListView lv, View v, int position, long id) {
Fragment newContent = null;
switch (position) {
case 0:
etc...
}
if (newContent != null)
switchFragment(newContent);
v.setSelected(true);
lv.setSelected(true);
}
private void switchFragment(Fragment fragment) {
if (getActivity() == null)
return;
MainActivity activity = (MainActivity) getActivity();
activity.switchContent(fragment);
}
}
选择器:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:exitFadeDuration="@android:integer/config_mediumAnimTime">
<!--<item android:drawable="@android:color/transparent" android:state_pressed="true"/>-->
<item android:drawable="@color/white" android:state_selected="true"/>
<!--<item android:drawable="@color/red" android:state_activated="true"/>-->
<item android:drawable="@color/black" />
</selector>
和列表布局:
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/list_padding"
android:paddingRight="@dimen/list_padding"
android:choiceMode="singleChoice"/>
单击菜单中的一个项目后,菜单将被隐藏(如假设)。但是当再次显示菜单时,没有更多选定的项目。
有没有办法保持项目的选择?
更新
根据Shereef Marzouk的建议,我改变了:
public class MenuListFragment extends ListFragment {
private View selectedView;
...
@Override
public void onListItemClick(ListView lv, View v, int position, long id) {
Fragment newContent = null;
switch (position) {
// stuff
}
if (selectedView != null) selectedView.setBackgroundColor(getResources().getColor(R.color.aqincolor));
v.setBackgroundColor(getResources().getColor(R.color.espresso));
selectedView = v;
if (newContent != null)
switchFragment(newContent);
}
...
}
在这种情况下,它有效,但我不会感觉到menu_selector.xml
甚至无法切换super.onActivityCreated(savedInstanceState);
答案 0 :(得分:1)
这就是我在申请中所做的:
final Class<?> currentClass = getActivity.getClass();
switch (position) {
case 0: //Menu
cls = MainNavigationActivity.class;
if (currentClass.equals(cls)) {
view.setBackgroundColor(parent.getContext().getResources().getColor(R.color.selectedMenuBackground));
}
break;
}
初始化菜单时,检查您已初始化的类,并根据该类更改BG颜色