我在活動中使用片段存在問題。我想從活動中進入片段,我非常接近這樣做。這裏是我的活動:從活動切換到片段
Utils u;
Fragment fragment;
FrameLayout frameLayout;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.galleryID);
frameLayout = (FrameLayout)findViewById(R.id.fragmentContainer);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
fragment = new GalleryFragment();
Utils.fragmentManager(frameLayout.getId(), fragment, MainActivity.this);
} catch (Exception e) {
e.getStackTrace();
}
}
});
utils的:
public class Utils {
public static void fragmentManager(Integer contentId, Fragment fragment, Activity activity) {
try {
FragmentManager fm = activity.getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(contentId, fragment);
fragmentTransaction.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
}
GalleryFragment:
public class GalleryFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
// Defines the xml file for the fragment
return inflater.inflate(R.layout.fragment_galleryfragment, parent, false);
}
// This event is triggered soon after onCreateView().
// Any view setup should occur here. E.g., view lookups and attaching view listeners.
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Setup any handles to view objects here
// EditText etFoo = (EditText) view.findViewById(R.id.etFoo);
}
}
而且我個XML activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res /android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:orientation="horizontal" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:id="@+id/fragmentContainer"
android:layout_centerHorizontal="true">
</FrameLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/galleryID"
android:text="gallery"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
而且fragment_galleryfragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<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="@drawable/ok">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
當我點擊庫按鈕畫廊的佈局出現在屏幕上。但是activity_main佈局保留它的位置。我想切換佈局,如從活動A切換到活動B.任何人都可以幫忙嗎?
你能否解釋一下你想做些什麼?是否想從片段中開始另一個片段?或從你的活動一旦顯示片段,你想顯示另一個片段? –
在更換片段時,您正在更改framelayout的內容,因此活動中的其餘元素將保留。您必須以編程方式隱藏它們,或者讓您的活動僅包含您的framelayout並使用兩個片段(最初包含gallery按鈕和gallery片段) –
或者您可以使用buttonsetVisibility(false)隱藏按鈕一旦按鈕按下。 –