我会直接解决问题。在Android中替换片段时我做错了什么?点击赞助商时的预期结果:
现实(我实际得到的东西:基本上,它只是赞助商片段,它只是放在其他片段上):
我通过
调用片段fragment = new Other(this);
Sponsors.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Sponsors" />
</RelativeLayout>
Sponsors.java
...
public class Sponsors extends android.support.v4.app.Fragment {
private Context context;
public Sponsors(Context context) {
this.context = context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.sponsors, null);
return rootView;
}
}
other.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/other_frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="COMMON"
android:textStyle="bold"
android:textColor="@color/header_red"
android:layout_marginTop="15dp"
android:layout_marginLeft="10dp" />
<View
android:layout_width="fill_parent"
android:layout_height="2dp"
android:background="@color/header_red"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" />
<TextView
android:id="@+id/sponsors"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Sponsors"
android:textColor="@color/subtext"
android:textSize="16sp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:paddingLeft="15dp" />
</LinearLayout>
</FrameLayout>
Other.java
public class Other extends android.support.v4.app.Fragment {
public Other(Context context) {
this.context = context;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.other, container, false);
sponsors = (TextView) rootView.findViewById(R.id.sponsors);
sponsors.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (savedInstanceState == null) {
Sponsors duedateFrag = new Sponsors();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.other_frame_container, duedateFrag);
ft.addToBackStack(null);
ft.commit();
}
}
});
}
答案 0 :(得分:3)
在add
replace
更改为FragmentTransaction
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.other_frame_container, duedateFrag);