I've read hundreds of explanations on "this" in java and I'm really having trouble grasping it. I'm learning android and java side-by-side, I know it's harder that way but I'm enjoying it. The one thing I'm getting killed on is "this"... I'm pasting code from a tutorial below that utilizes "this" one time. I was going to just put a piece of the code but want to be as helpful as possible.
I'm looking for a good explanation of "this" that I can add to my notes. Any and all help is appreciated. Thanks in advance.
example code starts below:
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import android.view.View;
import android.content.DialogInterface;
import android.app.Dialog;
import android.app.AlertDialog;
public class DialogActivity extends Activity {
CharSequence[] items = { "Google", "Apple", "Microsoft" };
boolean[] itemsChecked = new boolean [items.length];
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View v) {
showDialog(0);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("This is a dialog with some simple text...")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),
"OK Clicked!", Toast.LENGTH_SHORT).show();
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),
"Cancel clicked!", Toast.LENGTH_SHORT).show();
}
}
)
.setMultiChoiceItems(items, itemsChecked,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
int which, boolean isChecked) {
Toast.makeText(getBaseContext(),
items[which] + (isChecked ? " checked!":" unchecked!"),
Toast.LENGTH_SHORT).show();
}
}
).create();
}
return null;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…