Fragment,androidfragment

來源:互聯網
上載者:User

Fragment,androidfragment

Fragment 是輕量級的,比Activity 快,適合約一個APP 內頁面的跳轉。

1: 在MainActivity 中啟動一個fragment  BlankFragment:

public class MainActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener{    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        if(savedInstanceState == null){            getSupportFragmentManager().beginTransaction()                    .add(R.id.container,new BlankFragment())                    .commit();        }    }    @Override    public void onFragmentInteraction(Uri uri) {    }}

  2、 在 BlankFragment 呈現一個按鈕,點擊按鈕,轉到另一個fragment:

      

    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        View rootView = inflater.inflate(R.layout.fragment_main,container,false);        rootView.findViewById(R.id.btnShowAnotherFragment).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                getFragmentManager().beginTransaction()                        .addToBackStack(null)                        .replace(R.id.container, new AnotherFragment()).commit();            }        });        return  rootView;    }

  3、 在另一個fragment 增加一個返回按鈕,返回到上一個fragment:

     

public class AnotherFragment extends Fragment {    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        View root = inflater.inflate(R.layout.fragment_another,container,false);        root.findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener(){            @Override            public void onClick(View view) {                getFragmentManager().popBackStack();            }        });        return root;    }}

 

 

在第一個fragment A 跳轉 到 第二個fragment B時:

執行 B.onCreate -- A.onPause -- A.onDestoryView --b.onCreateView   , 在B頁面點後退,執行 B.onPause -- B.onDestory

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.