Android布局之FrameLayout
FrameLayout 的作用可以笼统的看做一个占位符,占用布局的一个位置,在需要的时候做相应的替换,它的出现是为了解决宽屏上的展示问题。
话不多说上代码
activity _main.xml:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.zhangqiongwen.demo.MainActivity"> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/activity_main_framelayoutTest" > </FrameLayout> </android.support.constraint.ConstraintLayout>
fragment1.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintBottom_toBottomOf="parent" android:id="@+id/fragment1_textview1" android:text="这是第一个fragment页面" /> </android.support.constraint.ConstraintLayout>
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment1 mFragment = new Fragment1();
getFragmentManager().beginTransaction().replace(R.id.activity_main_framelayoutTest, mFragment).commit();
}
}
Fragment1.java
public class Fragment1 extends Fragment {
View mView;
TextView mTextViewTest;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment1, null, false);
//对替换的fragment页面中控件的绑定、设置监听等操作应当在fragment中完成
mTextViewTest = mView.findViewById(R.id.fragment1_textview1);
mTextViewTest.setText("this is the first fragment");
return mView;
}
}
Fragment也像activity一样,拥有自己的生命周期,可以像activity一样将不同的操作放在不同的on方法中。
如果两个Fragment之间需要进行通信,可以通过Activity或者设置回调接口来进行通信,谷歌官网上推荐是使用接口方式进行通信。