Fragment is not shown on Activity

时间:2015-06-26 10:20:56

标签: android android-fragments android-activity fragment android-linearlayout

In my App,One Activity has to include three fragments, one of them always remains on Activity but the other two have to change places. But fragments are not shown on an activity.

I have read somewhere here that I should change LinearLayout to FragmentLayout but it did not work.

public class MainActivity extends ActionBarActivity {

private final Fragment_1to6 f1to6 = new Fragment_1to6();
private final Fragment_7to12 f7to12 = new Fragment_7to12();

private FragmentManager mFragmentManager;
private FrameLayout mButtonsLayout, mLayout1to6;
private FrameLayout mLayout7to12;

private static final int MATCH_PARENT = LinearLayout.LayoutParams.MATCH_PARENT;
private static final int WRAP_CONTENT = LinearLayout.LayoutParams.WRAP_CONTENT;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    mButtonsLayout = (FrameLayout) findViewById(R.id.fragment_buttons);
    mLayout1to6 = (FrameLayout) findViewById(R.id.fragment_1to6);
    mLayout7to12 = (FrameLayout) findViewById(R.id.fragment_7to12);

    mFragmentManager = getFragmentManager();
    final FragmentTransaction ft = mFragmentManager.beginTransaction();

    ft.add(R.id.fragment_buttons, new buttonsFragment());
    ft.add(R.id.fragment_1to6, f1to6);

    ft.addToBackStack("fragment_buttons");
    ft.addToBackStack("fragment_1to6");

    ft.commit();

    mFragmentManager
            .addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
                public void onBackStackChanged() {
                    setLayout();
                }
            });


    mFragmentManager.executePendingTransactions();


}

private void setLayout() {

    // Determine whether the Fragment has been added
    if (!f7to12.isAdded()) {

        mButtonsLayout.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT,
                MATCH_PARENT, 1f));
        mLayout1to6.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT,
                MATCH_PARENT, 6f));
    } else {

        mButtonsLayout.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT,
                MATCH_PARENT, 1f));
        // Make the TitleLayout take 6/13 of the layout's width
        mLayout1to6.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT,
                MATCH_PARENT, 6f));

        // Make the QuoteLayout take 6/13's of the layout's width
        mLayout7to12.setLayoutParams(new LinearLayout.LayoutParams(WRAP_CONTENT,
                MATCH_PARENT, 6f));
    }


}

how can i solve that ?

1 个答案:

答案 0 :(得分:0)

我有TableRows,这就是原因,现在我删除了它们并制作了LinearLayout,它显示在片段的预览中但不在activity_main中。这是主要活动的xml代码。以下是片段活动的xlm代码。我通过调用<%= show_vote_buttons(@post) %>

将片段添加到活动中
mButtonsFragment = (buttonsFragment) mFragmentManager.findFragmentById(R.id.fragment_buttons);