2012-12-10 35 views
1

dialogs上的android文档给出了一个很好的关于AlertDialogs的小教程。在使用代码时,立即在getActivity()的Eclipse中出现错误。为什么这不起作用?错误:The method getActivity() is undefined for the type MainActivity对于那些试图通读文档以成为更好的程序员的人来说,这尤其令人困惑,但似乎我并没有在某些事物上连接点。谢谢。Android AlertDialog教程给出了一个错误 - 空白应用程序

import android.os.Bundle; 
import android.app.Activity; 
import android.app.AlertDialog; 
import android.view.Menu; 
import android.view.View; 

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 

    } 
} 

回答

1

您不是针对正确的api构建的......方法getActivity()在以前的API中不可用。你可以随时去

AlertDialog.Builder builder = new AlertDialog.Builder(this); 

或从一个内部类调用时,使用

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
0

使用

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

代替

2

的医生说:

getActivity (Context con, int reqCode, Intent intent, int flags)

Retrieve a PendingIntent that will start a new activity, like calling Context.startActivity(Intent). Note that the activity will be started outside of the context of an existing activity, so you must use the Intent.FLAG_ACTIVITY_NEW_TASK launch flag in the Intent.

[public AlertDialog.Builder (Context context)][2] 

Constructor using a context for this builder and the AlertDialog it creates. 

意味着AlertDialog.Builder构造函数需要一个Context实例来代替的PendingIntent

改变你的代码为:

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 

编辑:

为纽带的你

http://developer.android.com/guide/topics/ui/dialogs.html

在这个例子作家提供谈到如何表现AlertDialogDialogFragment。我们在使用时getActivity()DialogFragment其返回的活动这个片段目前与相关。意味着间接地getActivity()返回上下文实例

相关问题