2014-12-06 125 views
0

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

这里是我的代码:

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); 

    } 



} 
+0

请阅读[开发文档(http://developer.android.com/guide/components/fragments.html) ,这不是我们如何使用片段。 – Shvet 2014-12-06 10:20:53

+2

使用FragmentActivity而不是Activity来显示片段 – 2014-12-06 10:21:01

+0

@ρяσѕρєяK立即尝试它。 – 2014-12-06 10:24:33

回答

0

没人能取代你放什么的setContentView(R。 layout.main);如果main.xml是hardCoded ...(xml文件)。与 transaction.replace ... 您可以使用fragmentActivity没有的setContentView(R.layout.main)

+0

他可以将具有特定ID的空FrameLayout作为容器,然后用片段事务替换该framelayout的内容:http://developer.android.com/training/basics/fragments/fragment-ui.html #更换 – EpicPandaForce 2014-12-06 11:11:15