I'm working through Google's tutorial on how to create custom dialogs Located here: http://developer.android.com/guide/topics/ui/dialogs.html#ShowingADialog
I entered everything in word or word and triple checked to make sure it is all correct but no matter how many times I check the code my program crashes. I have managed to fix it by changing a single line of code.
I changed the code from this
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);
To this
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(MainActivity.this);
My question is, why doesn't the getApplicationContext()
function return the right value. Since the code is from the official Google website, I'm assuming that I am doing something wrong.
I have included all my source code. I apologize if this is to spammy.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:text="Launch Custom Dialog"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>
custom_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
>
<ImageView android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFF"
/>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity
{
Button btn1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.icon);
dialog.show();
}
});
}
}