我正在使用带有 ListView 作为菜单的 SlidingMenu,并且我想根据 ListView 元素的单击动态更改 MainActivity 的内容。我知道我必须使用 Fragments 来实现这一点。
我有一个 PlayerFragment 里面什么都没有:
public class PlayerFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.activity_player_fragment, container, false);
}
}
我的标准 MainActivity 里面有一个 SlidingMenu:
public class MainActivity extends SlidingFragmentActivity {
private ListView mainListView;
private ArrayAdapter<String> listAdapter;
private SlidingMenu menu;
protected ListFragment mFrag;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu = new SlidingMenu(this);
menu.setMode(SlidingMenu.LEFT);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setShadowWidth(8);
menu.setFadeDegree(0.8f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
menu.setBehindWidth(600);
menu.setMenu(R.layout.menu_frame);
mainListView = (ListView) findViewById(R.id.listView1);
String[] planets = new String[] { "News", "Android", "Control",
"About" };
ArrayList<String> planetList = new ArrayList<String>();
planetList.addAll(Arrays.asList(planets));
listAdapter = new ArrayAdapter<String>(this,
R.layout.custom_list_element, R.id.title, planetList);
mainListView.setAdapter(listAdapter);
mainListView.setSelector(R.layout.listselector);
mainListView
.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = String.valueOf(mainListView
.getItemAtPosition(position));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onBackPressed() {
if (menu.isMenuShowing()) {
menu.toggle();
} else {
super.onBackPressed();
}
}
}
应用启动时如何调用标准片段?以及如何根据 ListView 的点击更改片段?
我想到了这样的事情:
if (fragment == null) {
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.RELATIVEVIEW_ID_HERE, new BasicFragment());
ft.commit();
}
并更改片段:
Fragment fg = NewsFragment.newInstance();
getFragmentManager().beginTransaction().add(R.id.RELATIVEVIEW_ID_HERE, fg).commit();
它是否正确?
提前致谢!