1

我编写了以下代码来使用 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 并挂起。如何使其始终如一地工作?

4

1 回答 1

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");

当然,您可以使用此方法创建更复杂的对话框 - 我们只使用了两种方法 from AlertDialog.Builder,但它提供了更多功能

于 2013-07-17T10:26:04.410 回答