finish()有时不能正常工作

时间:2013-07-17 08:39:52

标签: android android-layout android-intent

我编写了以下代码,以显示使用textview和按钮的消息框。当按钮单击时,应该完成活动。但这有时是有效的,不一致。有时会挂起来。如何让它始终如一?请帮忙

public class MyClass extends Activity {
private TextView mText;
private Button mOk;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.msgbox);

    mText = (TextView) findViewById(R.id.txt);
    mText.setText(“Click ok to exit”);

    mOk = (Button) findViewById(R.id.ok);
    mOk.setOnClickListener(mOnOkClickListener);
}

private final OnClickListener mOnOkClickListener = new OnClickListener() {
    public void onClick(View v) {
        finish();
    }
};

}

在工作条件下,单击“确定”按钮时会调用onPause,onStop和onDestroy。挂起时,它只调用onPause并挂起。如何让它始终如一地运作?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用DialogFragment制作邮件 设置:

//imports you'll need to add:
import android.app.Dialog;
import android.app.AlertDialog;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;

//Activity that fires up your Dialog needs to be a FragmentActivity:        
public class MyActivity extends FragmentActivity {

// ...

//class representing Dialog you want to show
public static class Dialog1 extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("Click ok to close");
        builder.setPositiveButton("Button text", null);
        return builder.create();
    }
}

执行对话框:

    DialogFragment df = new Dialog1();
    df.show(getSupportFragmentManager(), "tag");

当然,您可以使用此方法创建更复杂的对话框 - 我们只使用AlertDialog.Builder中的两种方法,但it has much more to offer