想在Android中使用程序方法

时间:2012-04-20 18:18:42

标签: java android multithreading

我希望主要活动在对话框被执行时等待。我在主要活动中尝试了this.wait();,但它给出了异常。这一切都在我脑海中浮现,所以我来这里寻求帮助:)。先感谢您 任何帮助都会得到赞赏

public class MyDailogTestActivity extends Activity {
    /** Called when the activity is first created. */
    String Xvalue,Yvalue;
    TextView TextViewString;    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button ShowDialog = (Button) findViewById(R.id.ShowDialog);
        TextViewString = (TextView) findViewById(R.id.ShowDialogText);      
        ShowDialog.setOnClickListener(new OnClickListener(){
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Dialog MyDialog = MyDailog();
                MyDialog.show();
                // I WANT THIS TO EXECUTE AFTER BELOW MENTIONED CODE
                TextViewString.setText(Xvalue + Yvalue);
            }

        });
    }

    private Dialog MyDailog(){
        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.my_dialog, null);
        return new AlertDialog.Builder(MyDailogTestActivity.this)
        .setTitle("Enter Value")
        .setView(textEntryView)
        .setPositiveButton("Oky", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                // THIS TO BE EXECUTE FIRST       
                Xvalue = "This ";
                Yvalue = "and That";                
                /* User clicked OK so do some stuff */
            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                /* User clicked cancel so do some stuff */
            }
        })
        .create();        
    }

}

这是执行

时此项目的图像

http://imageshack.us/photo/my-images/220/11696639.jpg/ 在此图像中,您可以看到Hello World不变。我试图反映你好世界TextView的变化。

http://imageshack.us/photo/my-images/338/27833231.jpg/ 现在在这张图片中。当我点击show对话框时,它继续执行下一个代码TextViewString.setText(Xvalue + Yvalue); 其中它显示值null 现在我希望它等待对话框完成代码,其中Xvalue和Yvalue将通过此代码获得值“This n That”

Xvalue = "This ";
Yvalue = "and That";  

2 个答案:

答案 0 :(得分:2)

移动此行:

TextViewString.setText(Xvalue + Yvalue);

点击你的正面按钮点击监听器:

public void onClick(DialogInterface dialog, int whichButton) {
    // THIS TO BE EXECUTE FIRST    
    Xvalue = "This ";
    Yvalue = "and That";                
    /* User clicked OK so do some stuff */
    TextViewString.setText(Xvalue + Yvalue);
}

答案 1 :(得分:0)

我不确定你是否可以做你想做的事情,但我可以提出一个认为是标准的替代方案。创建DialogInterface.OnDismissListener类型的侦听器,然后使用setOnDismissListener()将其设置为对话框。当您关闭对话框时,将调用此侦听器。

或者如果你没有任何沉重的逻辑,你可以像Tim建议的那样直接把它放在对话框里。