gpt4 book ai didi

android - finish() 有时无法正常工作

转载 作者:行者123 更新时间:2023-11-30 03:29:31 29 4
gpt4 key购买 nike

我编写了以下代码来使用 TextView 和按钮显示消息框。单击按钮时, Activity 应该完成。但这有时会起作用,但并不一致。有时它会挂起。如何让它始终如一地工作?请帮忙

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 并挂起。如何让它始终如一地工作?

最佳答案

您可以尝试使用 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 .

关于android - finish() 有时无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17695037/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com