片段不会开始 - 从Activity调用

时间:2014-12-06 10:07:46

标签: android android-activity android-fragments

我试图从我的主要活动开始一个片段,但不知何故片段没有显示出来。有人可以帮我这个吗?

这是我的代码:

public class Main extends Activity implements OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b = (Button) findViewById(R.id.action_menu);
        b.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.action_menu){
            Log.d("--", "menu clicked");
            MenuFragment newFragment = new MenuFragment();
            FragmentTransaction transaction = getFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack
            transaction.replace(android.R.id.content, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }
    }


}

主要活动布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/main_rl" >

    <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/action_menu" android:text="Menu"/>
    </RelativeLayout>

和我的片段类:

public class MenuFragment extends Fragment{
    final String TAG=this.getClass().getSimpleName();
    private GridView grid;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View mView;
        Log.d(TAG, "Hello from Fragment");
        mView=inflater.inflate(R.layout.menu_fullscreen, null);
        initWidgets(mView);

        return mView;
    }

    private void initWidgets(View mView) {
        grid=(GridView) mView.findViewById(R.id.menu_fullscreen_grid);

    }



}

1 个答案:

答案 0 :(得分:0)

你不能替换你在setContentView(R.layout.main)中放置的内容;如果main.xml是hardCoded ...(xml文件)。同 transaction.replace ... 您可以在没有setContentView(R.layout.main)

的情况下使用fragmentActivity