我已经阅读了很多关于如何将FragmentDialog与活动进行通信的教程,但我似乎无法使它们适应我的项目。
我想要做的很简单,当用户点击我的FragmentDialog上的正按钮时,我想在主要活动中调用一个方法。一个简单的想法,但执行正在扼杀我。
我的主要活动使用选项卡式浏览,我的事情就是弄乱了这个洞。
这是我主要活动的简短版本。
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
//.....
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if(id == R.id.menu_change_date){
DialogFragment dialog = new Dialog_Elegir_Mes();
dialog.show(getSupportFragmentManager(),"Elegir Mes");
}
//....
public void dosomething() {
}
}
对话框
public class Dialog_Elegir_Mes extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Build the dialog and set up the button click handlers
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View v = inflater.inflate(R.layout.diag_select_month,null);
adb.setTitle("Elegir Mes");
adb.setView(v)
.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Here call dosomething();
}
})
.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Dialog_Elegir_Mes.this.getDialog().cancel();
}
});
return adb.create();
}
}
答案 0 :(得分:1)
创建一个接口并在Activity类中实现它,并将其引用传递给Dialog类。当用户单击对话框按钮时,使用界面调用该方法。
做这样的事情
public interface OnMyDialogClick
{
public abstract void onPositiveButtonClick();
}
您的活动
if(id == R.id.menu_change_date){
DialogFragment dialog = new Dialog_Elegir_Mes(new OnMyDialogClick()
{
@Override
public void onPositiveButtonClick()
{
//Call your activity method here
}
});
dialog.show(getSupportFragmentManager(),"Elegir Mes");
}
您的对话类
public class Dialog_Elegir_Mes extends DialogFragment {
private OnMyDialogClick _onMyDialogClick = null;
public Dialog_Elegir_Mes(OnMyDialogClick ref)
{
_onMyDialogClick = ref;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Build the dialog and set up the button click handlers
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View v = inflater.inflate(R.layout.diag_select_month,null);
adb.setTitle("Elegir Mes");
adb.setView(v)
.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
_onMyDialogClick.onPositiveButtonClick();
}
})
.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Dialog_Elegir_Mes.this.getDialog().cancel();
}
});
return adb.create();
}
}