Activity和Fragment交互
2015-05-31 12:42
323 查看
Activity和Fragment的交互有三种: 1.Activity访问Fragment中的控件、成员变量 2.Fragment访问Activity中的控件、成员变量 3.多个Fragment之间通讯
1.Activity访问Fragment中的控件、成员变量
如图: Activity中有一个CheckBox,底部是一个Fragment包含一个TextView和一个Button,点击CheckBox的时候得到Activity中成员变量的名字改变Fragment中TextView的值,点击Fragment中Button的时候得到CheckBox的状态显示Toast。 Fragment的xml布局:
<?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" > <TextView android:id="@+id/tv_status" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" /> <Button android:id="@+id/bt_status" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:text="@string/get_status" android:textSize="13sp" /> </LinearLayout>
Fragment中onCreateView()方法中返回一个View:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_bottom,container,false); bt_getStatus = (Button) view.findViewById(R.id.bt_status); return view; }
Activity的xml布局
<RelativeLayout 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" > <CheckBox android:id="@+id/cb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="20dp" android:text="@string/isMarry" /> <fragment android:id="@+id/bottomFragment" android:name="com.example.fragment_less03.fragment.BottomFragment" android:layout_width="match_parent" android:layout_height="50dp" android:layout_alignParentBottom="true" android:layout_marginBottom="40dp" />
Activity中,CheckBox设置状态改变监听方法中实现访问Fragment的代码:
cb_isMarry.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { //通过id或者tag获取Fragment BottomFragment fragment = (BottomFragment)getFragmentManager().findFragmentById(R.id.bottomFragment); if (fragment != null) { //访问Fragment的成员变量 fragment.setPersonName("LingDang"); //getView()获取View TextView tv_status = (TextView) fragment.getView() .findViewById(R.id.tv_status); if (isChecked) { 、 tv_status.setText(fragment.getPersonName()+"已婚"); } else { tv_status.setText(fragment.getPersonName()+"未婚"); } } } });
通过getFragmentManager().findFragmentById(R.id.bottomFragment);或者getFragmentManager().findFragmentByTag(String str);可以得到Fragment,Fragment对象再根据getView()返回一个View。根据返回的Fragment对象和View对象,即可访问Fragment的成员变量和控件
2. Fragment访问Activity:
代码还是的,在Fragment中添加代码:
// @Override public void onActivityCreated(Bundle savedInstanceState) { bt_getStatus.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CheckBox cb_isMarry = (CheckBox) getActivity().findViewById(R.id.cb); boolean isCheck = cb_isMarry.isChecked(); if (isCheck) { Toast.makeText(getActivity(), "已选中", 1000).show(); }else{ Toast.makeText(getActivity(), "未选中", 1000).show(); } } }); super.onActivityCreated(savedInstanceState); }
在onActivityCreated()方法中保证Activity的onCreate()方法调用完成。必须有super.onActivityCreated(savedInstanceState)才正确。 通过getActivity()可以得到Fragment对应的Activity,即可访问Activity中的内容。但是这样Fragment就和特定的Activity关联起来了,不利于Fragment的复用。我们可以这么做: 1.在Fragment中创建一个接口,并创建一个接口实例 2.在Fragment的onAttach中要求Activity实现该接口,点击的时候接口实例调用相应的方法 3.Activity实现Fragment对应的接口,实现方法 具体的请看多个Fragment通信
3.多个Fragment通信
效果图:
上边是InputFragment,只有一个EditText,下边是继承自ListFragment的ShowFragment。InputFragment输入一个字符串后点击回车在ShowFragment新增InputFragment输入的字符串,InputFragment的EditText的text设置为空。 多个Fragment通信的具体步骤: 1.在Fragment中创建一个接口,并创建一个接口实例 2.在Fragment的onAttach中要求Activity实现该接口,点击的时候接口实例调用相应的方法 3.Activity实现Fragment对应的接口,实现方法 代码: InputFragment的xml
<?xml version="1.0" encoding="utf-8"?> <EditText xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/edit" android:layout_width="match_parent" android:layout_height="match_parent" android:hint="input something" android:singleLine="true" > </EditText>
InputFragment代码:
public class InputFragment extends Fragment { private View view; EditText edit; public interface OnNewItemAddListener{ public void newItemAdd(String str); } private OnNewItemAddListener listener; @Override public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); //要求Fragment所附着的Activity必须实现这个方法 try{ listener = (OnNewItemAddListener)activity; }catch(Exception e){ throw new ClassCastException(activity.toString()+"must implement OnNewItemAddListener"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub view = inflater.inflate(R.layout.fragment_input, null); edit = (EditText) view.findViewById(R.id.edit); edit.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { if (keyCode == KeyEvent.KEYCODE_ENTER) { listener.newItemAdd(edit.getText().toString()); edit.setText(""); return true; } } return false; } }); return view; } } edit.setText("");前面还有一句listener.newItemAdd(edit.getText().toString());
ShowFragment代码: public class ShowFragment extends ListFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // TODO Auto-generated method stub return super.onCreateView(inflater, container, savedInstanceState); }
}
Activity的xml布局
<LinearLayout 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" android:orientation="vertical" > <fragment android:id="@+id/input" android:name="com.example.twofragment.fragment.InputFragment" android:layout_width="match_parent" android:layout_height="60dp" /> <fragment android:id="@+id/show" android:name="com.example.twofragment.fragment.ShowFragment" android:layout_width="match_parent" android:layout_height="wrap_content" />
Activity代码: public class MainActivity extends Activity implements OnNewItemAddListener{ private ArrayList<String> datas = new ArrayList<String>(); private ArrayAdapter adapter; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, datas); ShowFragment fragment = (ShowFragment) getFragmentManager().findFragmentById(R.id.show); fragment.setListAdapter(adapter); } @Override public void newItemAdd(String str) { datas.add(str); adapter.notifyDataSetChanged(); } }
按照上面的步骤编写即可,代码挺简单的。
相关文章推荐
- 人们抗拒组织变革的十大原因
- 《Cortex-CM3权威指南》——异常
- 李彦宏:PC时代结束
- 目标板通过nfs挂载根文件系统
- MySQL 查询数据
- 替代文本中的字符-python
- java享元模式
- Searching: Chained Hash Table Search And Insertion-2
- R语言入门学习
- Android 全局变量
- Linux下C的编写和执行
- html 标签记录
- 海洋模拟
- HDU 4009 Transfer water
- 第七章 实现炫酷效果—图像和动画(4)
- Win10 10074 版本无法连接 BT 鼠标
- UITableView中的(NSIndexPath *)indexPath
- [Objective-C]__bridge,__bridge_retained和__bridge_transfer的意思,区别与使用
- POJ-1088 滑雪 (动态规划)
- 用两个栈实现队列的功能