当先锋百科网

首页 1 2 3 4 5 6 7

        TabHost的功能可以由Fragment来实现。

        FragmentTransactionfragment进行添加,移除,替换,以及执行其他动作。

从 FragmentManager 获得一个FragmentTransaction的实例 :
FragmentManager fragmentManager = getFragmentManager(); 
FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();

一个小实例:

MainFragment.java

public class MainFragment extends Activity implements OnClickListener{
    
	private Button first, second, third;
	private FrameLayout fl;
	
	private FirstFragment ff;
	private SecondFragment sf;
	private ThirdFragment tf;
    
     @Override
    protected void onCreate(Bundle savedInstanceState){
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        first = (Button)findViewById(R.id.first_btn);
        second = (Button)findViewById(R.id.second_btn);
        third = (Button)findViewById(R.id.third_btn);
        
        fl = (FrameLayout)findViewById(R.id.fl);
        
        first.setOnClickListener(this);
        second.setOnClickListener(this);
        third.setOnClickListener(this);
        
        ff = new FirstFragment();
        sf = new SecondFragment();
        tf = new ThirdFragment();
    }
        
    @Override
    public void onClick(View v){

    	switch (v.getId()){
            case R.id.first_btn:
                switchFragment(R.id.fl, ff);
                break;
            case R.id.second_btn:
                switchFragment(R.id.fl, sf);
                break;
            case R.id.third_btn:
                switchFragment(R.id.fl, tf);
                break;
            default:
                break;
        }
    }
    
    public void switchFragment(int id, Fragment fragment){
        try{
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.replace(id, fragment); 
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); 
            ft.commit();// 提交
        }
        catch (Exception e){
        	e.printStackTrace();
        }
    }
}

FirstFragment.java,SecondFragment、ThirdFragment代码相似
public class FirstFragment extends Fragment{
    @Override
    public View onCreateView(LayoutInflater inflater, 
    		ViewGroup container, Bundle savedInstanceState){
        // TODO Auto-generated method stub
        View fragmentView = inflater.inflate(R.layout.first, null);

        return fragmentView;
    }
}

运行结果截图:


jpg改rar解压可得代码