close
2018更新
因為我本身開發的App跟生命週期是息息相關的
所以如果你也是那還是少用Fragment!!
我曾經有用Fragment開發過
但是那個問題真的多到一個不行
但如果你的App只是單純地要呈現畫面
那你就很適合用Frgment下去做開發!
想要利用Fragment來跳轉頁面,頁面的上方標題不換,只轉換下面的頁面
畫面配置如下
下面的白色頁面 fragment_container 是用來切換頁面的部份
因為我想要在畫面的一開始下面的畫面就有東西,所以在onCreate的時候我就需要將 fragment_container放入東西
我想要切換的畫面為fragment_login
利用這個changeFragment function來將fragment_container取代成想要的畫面
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
changefragmet(fragment_1.newInstance());
}
private void changefragmet(android.support.v4.app.Fragment f){
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container,f);
transaction.commitNowAllowingStateLoss();
}
Fragment1
畫面配置如下,讓你想要呈現在fragment_container的畫面直接拉一個layout
按下Button後會切換到fragment2
public class fragment_1 extends Fragment{ private View v; private Button next; public static fragment_1 newInstance(){ fragment_1 f = new fragment_1(); Bundle arg = new Bundle(); f.setArguments(arg); return f; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { v = inflater.inflate(R.layout.fragment_one,container,false); next = (Button)v.findViewById(R.id.next); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { changefragmet(fragment_2.newInstance()); } }); return v; } private void changefragmet(android.support.v4.app.Fragment f){ android.support.v4.app.FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.fragment_container,f); transaction.commitNowAllowingStateLoss(); } }
public class fragment_2 extends android.support.v4.app.Fragment{ private View v; private Button back; public static fragment_2 newInstance(){ fragment_2 f = new fragment_2(); Bundle arg = new Bundle(); f.setArguments(arg); return f; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { v = inflater.inflate(R.layout.fragment_two,container,false); back = (Button)v.findViewById(R.id.back); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { changefragmet(fragment_1.newInstance()); } }); return v; } private void changefragmet(android.support.v4.app.Fragment f){ android.support.v4.app.FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.fragment_container,f); transaction.commitNowAllowingStateLoss(); } }
實際操作畫面會變成下面這樣
下面都是利用Fragment做跳轉
文章標籤
全站熱搜
留言列表