«

Fragment的简单使用

时间:2024-3-2 20:02     作者:韩俊     分类: Android


做页面跳转,以前我们使用的是Activity,现在有一个更轻量级的组件-fragment可供我们选择。


Activity 代码:

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;


public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE)
.add(R.id.container, new MyFragment1()).commit();
}


}


Fragment1代码:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


import com.example.testfragment.R;


public class MyFragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.myfragment1, container, false);
root.findViewById(R.id.button1).setOnClickListener(
new Button.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().beginTransaction()
.addToBackStack("fragment2")
.replace(R.id.container, new MyFragment2())
.commit();
}
});
return root;
}
}


Fragment2代码:
package com.example.testfragment;

import android.os.Bundle;

import android.support.v4.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.Button;





import com.example.testfragment.R;





public class MyFragment2 extends Fragment {

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {

View root = inflater.inflate(R.layout.myfragment2, container, false);

root.findViewById(R.id.button2).setOnClickListener(new Button.OnClickListener() {



@Override

public void onClick(View v) {

getFragmentManager().popBackStack();

}

});

return root;

}

}

        <p>版权声明:本文为博主原创文章,未经博主允许不得转载。</p>

标签: android

热门推荐