我试图根据是否启用 GPS 来显示不同的 fragment 。但是我收到了这个错误:-
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0e00a1
请告诉我如何做到这一点:
这是我的 MainActivity 类:
public class MainActivity extends Activity {
Fragment fr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
fr = new FragmentTwo();
getFragment();
} else {
fr = new FragmentOne();
getFragment();
}
}
public void getFragment() {
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
}
}
fragment 一:-
public class FragmentOne extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
fragment 二:-
public class FragmentTwo extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_two, container, false);
}
}
我的 activity_main:-
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:id="@+id/fragment_place"
android:name="com.test.FragmentTwo"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
fragment_one.xml 和 fragment_two.xml 是相同的,只是文本不同:-
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="GPS IS ENABLE"/>
</RelativeLayout>
提前致谢。
最佳答案
替换
<fragment
android:id="@+id/fragment_place"
android:name="com.test.FragmentTwo"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
与
<FrameLayout
android:id="@+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="match_parent" />
作为静态Fragment
无法在运行时替换。但您可以在 FrameLayout
中添加或替换 fragment 。
关于android - 改变 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36792321/