关于Fragment的新认识—动态添加布局

    xiaoxiao2021-03-25  88

    碎片(Fragment)

    用于调试的android项目的东西有很多,有平板,手机,模拟器等等,并且每个东西的尺寸都不一定是一样的,这时候我们会遇到一个问题就是我们原来在手机上调试的项目放在平板上,布局就会显得不那么美观,很多控件的位置相对来说都已经改变。这时候就出现了碎片的概念,我们可以通过碎片来动态加载布局,根据判断模拟器或者手机还是平板来进行动态添加布局。

    上代码:

    首先先创建两个布局,一个是横屏(手机),一个是竖屏的(模拟器),这两个布局分别是各自Fragment的布局。

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:text="这是平板的布局" android:textSize="20sp" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:background="#54d44b" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:text="这是一个模拟器或者是手机的布局" android:textSize="20sp" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>

    分别创建两个Fragment来绑定布局,创建并绑定的代码是一样的

    public class LeftFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.left,container,false); return view; } } 根据在MainActivity中判断是否是平板还是模拟器,来进行布局的动态添加。

    public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (ispad(this)) { LeftFragment fragment1 = new LeftFragment(); getSupportFragmentManager().beginTransaction().replace(R.id.main_layout,fragment1).commit(); } else { RightFragment fragment2 = new RightFragment(); getSupportFragmentManager().beginTransaction().replace(R.id.main_layout,fragment2).commit(); } } //返回true就是平板,返回false就是模拟器或者是手机 public static boolean ispad(Context context){ return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK)>=Configuration.SCREENLAYOUT_SIZE_LARGE; } }

    转载请注明原文地址: https://ju.6miu.com/read-19871.html

    最新回复(0)