调用我试图从我的主要活动开始片段,但不知何故片段没有显示出来。有人可以帮我弄这个吗?片段不会启动 - 从活动
这里是我的代码:
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);
}
}
请阅读[开发文档(http://developer.android.com/guide/components/fragments.html) ,这不是我们如何使用片段。 – Shvet 2014-12-06 10:20:53
使用FragmentActivity而不是Activity来显示片段 – 2014-12-06 10:21:01
@ρяσѕρєяK立即尝试它。 – 2014-12-06 10:24:33