調用我試圖從我的主要活動開始片段,但不知何故片段沒有顯示出來。有人可以幫我弄這個嗎?片段不會啓動 - 從活動
這裏是我的代碼:
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