您的位置:首页 > 其它

Fragment知识总结

2016-04-27 21:43 357 查看
1.静态加载fragment

创建2个类,都继承fragment。

public class Fragment1 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
}

}

public class Fragment2 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
}

}


创建一个activity,

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false" >

<fragment
android:id="@+id/fragment1"
android:name="com.example.fragment.Fragment1"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1" />

<fragment
android:id="@+id/fragment2"
android:name="com.example.fragment.Fragment2"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1" />

</LinearLayout>


2.动态加载fragment

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
<p>//1.获取到FragmentManager,在Activity中可以直接通过getFragmentManager得到。</p><p>//2.开启一个事务,通过调用beginTransaction方法开启。</p><p>//3.向容器内加入Fragment,一般使用replace方法实现,需要传入容器的id和Fragment的实例。</p><p>//4.提交事务,调用commit方法提交。
</p>            Fragment1 fragment1 = new Fragment1();
getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();

}

}

3.fraagment之间的通信

多个fragment在一个activity里,主要都是通过getActivity这个方法实现的。getActivity()方法可以让Fragment获取到关联的Activity,然后再调用Activity的findViewById方法,就可以获取到和这个Activity关联的其它Fragment的控件了。

例如:

public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final TextView textView= (TextView) getActivity().findViewById(R.id.text);
Button button= (Button) getActivity().findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(),textView.getText().toString(),Toast.LENGTH_LONG).show();
}
});
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: