我有一个导航抽屉,其中包含单击菜单时要打开的特定片段的n个菜单。首先,我尝试了一些活动和意图。在使用片段的情况下,它看起来不太好。我通过id选择它们,并从活动中调用该片段。在该片段中,我使用的饼图会引发空指针异常。我尝试从get视图进行更改,因为只有在Oncreate View之后才能实例化它。但没有结果。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pieChart1 = (PieChart) getView().findViewById(R.id.piechart1);
pieChart2 = (PieChart) getView().findViewById(R.id.piechart2);
这里是一个示例代码,将有助于您理解。首先用OnCreate()中的片段替换activity_main.xml内容:
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new HomeFragment()).commit();
然后在onNavigationItemSelected()中将此HomeFragment替换为其他的:
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
// Handle the camera action
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new HomeFragment()).commit();
} else if (id == R.id.nav_current_order) {
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new MyCurrentOrderFragment(),"Tag").commit();
} else if (id == R.id.nav_received_images) {
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new HistoryFragment()).commit();
} else if (id == R.id.nav_rate_app) {
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new RateOurAppFragment()).commit();
} else if (id == R.id.nav_help) {
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new HelpFragment()).commit();
} else if (id == R.id.nav_settings) {
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new SettingsFragment()).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
在您的content_main.xml中添加一个FrameLayout并将其ID设置为“ content_frame”
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="bd.com.chalo.dsstudio.MainActivity"
tools:showIn="@layout/app_bar_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:visibility="gone" />
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</RelativeLayout>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句