Android——Fragment的入门使用

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

1.静态的使用

 1.1 在layout中添加frament1.xml和frament2.xml文件,之后在main.xml中添加frament标签
name中指定相对应的java文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"    
    android:orientation="horizontal" >


    <fragment
        android:id="@+id/fragment1"
        android:name="com.shenjian.sensor.Flagment1"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="1" 
        />
     <fragment
        android:id="@+id/fragment2"
        android:name="com.shenjian.sensor.Flagment2"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        />


</LinearLayout>


 1.2 新建Fragment1,Fragment1类 继承Fragment(import android.app.Fragment;最低版本3.0 要想在2.2以上使用要用import android.support.v4.app.FragmentTransaction;) ,实现onCreateView 方法
package com.shenjian.sensor;


import com.shenjian.paizhao.R;


import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class Flagment1 extends Fragment {


/*
*当Fragement被创建的时候调用的方法,返回当前fragment显示的内容
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment1, null);
}

}




2.动态的添加fragment(横屏显示蓝色 竖屏显示红色)


public class Main_activity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//1.判断当前手机的朝向
int width = getWindowManager().getDefaultDisplay().getWidth();
int height = getWindowManager().getDefaultDisplay().getHeight();

Left_fragment left_fm= new Left_fragment();
right_fragment right_fm =new right_fragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
if (width>height) {
//先remove掉 在替换掉 参数:要替换的窗体 (android.R.id.content 当前窗体的id),fragment类
transaction.replace(android.R.id.content, left_fm);
} else {
transaction.replace(android.R.id.content, right_fm);
}
//关闭事务
transaction.commit();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值