Android - MyFragment.java
java代码: MyFragment.java
1 package com.example.droid.util; 2 3 import com.example.droid.R; 4 import android.app.Activity; 5 import android.support.v4.app.Fragment; 6 import android.os.Bundle; 7 import android.view.LayoutInflater; 8 import android.view.View; 9 import android.view.View.OnClickListener; 10 import android.view.ViewGroup; 11 import android.widget.Button; 12 import android.widget.EditText; 13 14 public class MyFragment extends Fragment { 15 private View view; 16 private EditText editText; 17 private Button btn_one; 18 private Button btn_two; 19 private MyFragmentInterface activity; 20 private int id; 21 private OnClickListener clickListener = new OnClickListener() { 22 @Override 23 public void onClick(View view) { 24 String text = editText.getText().toString(); 25 switch (view.getId()) { 26 case R.id.btn_one: 27 if (activity != null) { 28 activity.setText(text); 29 } 30 break; 31 case R.id.btn_two: 32 if (activity != null) { 33 activity.sendMessage(id, text); 34 } 35 break; 36 default: 37 break; 38 } 39 } 40 }; 41 42 public void setCallback (MyFragmentInterface activity) { 43 this.activity = activity; 44 } 45 public void setId (int id) { 46 this.id = id; 47 } 48 public void setText (String text) { 49 if (editText != null) { 50 editText.setText(text); 51 } 52 } 53 54 @Override 55 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 56 super.onCreateView(inflater, container, savedInstanceState); 57 // 通过inflater来创建视图, 并返回该视图(View) 58 view = inflater.inflate(R.layout.fragment_one, null); 59 60 editText = (EditText) view.findViewById(R.id.editText); 61 btn_one = (Button) view.findViewById(R.id.btn_one); 62 btn_two = (Button) view.findViewById(R.id.btn_two); 63 64 btn_one.setOnClickListener(clickListener); 65 btn_two.setOnClickListener(clickListener); 66 return view; 67 } 68 69 // Interface 70 public static interface MyFragmentInterface { 71 void setText (String text); 72 void sendMessage (int id, String text); 73 } 74 }
XML代码: fragment_one.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" > 5 <EditText android:id="@+id/editText" 6 android:layout_width="match_parent" 7 android:layout_height="wrap_content"/> 8 <Button android:id="@+id/btn_one" 9 android:layout_width="wrap_content" 10 android:layout_height="wrap_content" 11 android:layout_below="@id/editText" 12 android:text="ButtonOne"/> 13 <Button android:id="@+id/btn_two" 14 android:layout_width="wrap_content" 15 android:layout_height="wrap_content" 16 android:layout_below="@id/editText" 17 android:layout_toRightOf="@id/btn_one" 18 android:text="ButtonTwo"/> 19 </RelativeLayout>