如何通过activity来访问fragment的信息呢,我们可以通过一个实例来了解。
使用两个Fragment和一个activity管理
效果图:
第一个fragment来表示输入框
第二个fragment表示listview内容
最终由activity来控制两个fragment。
实现方法:
fragment与其附着的activity之间的通讯最佳方式:
1, 在发起事件的fragment中定义一个接口,借口中声明你的方法 2,在onattach中要求activity实现该接口 3,在activity实现方法具体代码:
step 1:创建Framlayou并与相应的Fragment创建联系
step 2 :监听封装了EditText的Fragment的回车事件,并使用最佳通讯方式将信息传给Activity
public class FragmentEditText extends Fragment { private View view; private OnEnterClickedListener mListener; private String message; private EditText editText; public interface OnEnterClickedListener { public void onEnterClicked(String message); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnEnterClickedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_edit_text, container,false); editText = (EditText) view.findViewById(R.id.fragment_et); editText.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { System.out.println("Action_down"); if (keyCode == KeyEvent.KEYCODE_ENTER) { message = editText.getText().toString(); mListener.onEnterClicked(message); System.out.println(message + "messagesdfsd"); editText.setText(""); return true; } } return false; } }); return view; }
step 3 :在activity中实现方法,其中内容的Fragment继承ListFragment可以不覆写任何方法,直接使用,具体参见AndroidDoc
public class MainActivity extends Activity implements OnEnterClickedListener { private Listdata; private ArrayAdapter adapter; private FragmentContainer fragmentContainer; private FragmentManager fragmentManager; private FragmentTransaction beginTransaction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); data = new ArrayList (); adapter = new ArrayAdapter (this, android.R.layout.simple_list_item_1, data); fragmentManager = getFragmentManager(); beginTransaction = fragmentManager.beginTransaction(); fragmentContainer = new FragmentContainer(); fragmentContainer.setListAdapter(adapter); beginTransaction.add(R.id.fragment_container, fragmentContainer); beginTransaction.add(R.id.fragment_edit_text, new FragmentEditText()); beginTransaction.commit(); } public void onEnterClicked(String message) { data.add(message); adapter.notifyDataSetChanged(); }}
主要知识点就是利用接口的方式让activity操作Fragment的数据。