Day4:一丶Fragment的基本使用:
1.创建Fragment:
public class MyFragment extends Fragment {
public MyFragment() {
// Required empty public constructor
}
/** * 参数详解
* fragment第一次创建用户界面时回调的方法
* @param inflater 实体加载器,用于加载一个fragment的视图
* @param container 表示当前fragment插入到activity中的对象
* @param savedInstanceState 表示储存一个fragment的信息
* @return */
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_my, container, false);
}
}
2.创建Fragment布局:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragment.MyFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
3.Activity布局添加fragment标签:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--一定要注意的是:name属性是fragment的全限定名-->
<fragment
android:id="@+id/my_fragment_id"
android:name="com.example.day004.fragment.MyFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</fragment>
</LinearLayout>
Day4:二丶Fragment进阶:
1.Fragment回退栈:
添加回退栈:
ContentFragment fragment = new ContentFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fl_content,fragment);
ft.addToBackStack();
ft.commit();
清空回退栈:
FragmentManager fm= getFragmentManager();
int count = fm.getBackStackEntryCount();
for (int i = 0; i < count; ++i) {
fm.popBackStack();
}
2.Fragment接口回调:
两个Fragment之间无法直接传递数据,需要一个中间桥梁可以是Handler或接口回调。
在一个 Fragment里发送消息:
Message message = new Message();
message.arg1 = 1;
message.obj = "datas";
Fragment2.handler.sendMessage(message);
在另外一个 Fragment里接收消息:
public static Handler handler=new Handler(){
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.arg1==1){
String data= msg.obj.toString();
}
fragment 给 activity传值:
public class F2AActivity extends AppCompatActivity
implements ShowTitleFragment.MyListener {
private TextView textView;
@Override
public void sendMessage(String string) {
textView.setText(string);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_f_2_a);
textView = findViewById(R.id.f2a_tv_id);
}
}