创建对 Activity 的事件回调
MainActivity.java
public class MainActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Fraga fraga = new Fraga();
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment, fraga, "fragment1");
fragmentTransaction.commit();
Button bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fraga.setcall(new Fraga.CallBack() {
@Override
public void getText(String xx) {
Toast.makeText(MainActivity.this, xx, Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
Fraga.java
public class Fraga extends Fragment {
EditText editText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fraga, null);
editText = (EditText) v.findViewById(R.id.editText2);
return v;
}
public void setcall(CallBack callBack){
callBack.getText(editText.getText().toString());
}
public interface CallBack{
public void getText(String xx);
}
}