Saturday, April 12, 2014

Novice under eclipse ADT advice on how to add visual environment in response to a button event


I wrote Mainactivity.java in a openDialog () used to do incident response, but added openDialog in button OnClick property () no effect, suggesting openDialog () can not find
 
public class MainActivity extends Activity {
private TextView txtView;
@ Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
this.txtView = (TextView) findViewById (R.id.textView1);

if (this.txtView! = null) {

this.txtView.setText ("Hello World");
}
}
public void openDialog () {
AlertDialog.Builder builder = new AlertDialog.Builder (this);
builder.setTitle ("Hello");
builder.setMessage ("Hello World \ n");
builder.setNegativeButton ("OK", null);
builder.show ();
}

@ Override
public boolean onCreateOptionsMenu (Menu menu) {
/ / Inflate the menu; this adds items to the action bar if it is present
.getMenuInflater () inflate (R.menu.main, menu);.
return true;
}

}


Add Button's On Click property

<-! Main posts under Banner (D4) -><-! Posts under the main text (D5) ->
Reply:
Visual design interface only provides property settings, trigger events with a code on it:
 public class MainActivity extends Activity {
private TextView txtView;
@ Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
this.txtView = (TextView) findViewById (R.id.textView1);

if (this.txtView! = null) {

this.txtView.setText ("Hello World");
}

Button button = (Button) findViewById (R.id.button_id);
button.setOnClickListener (new View.OnClickListener () {
public void onClick (View v) {
openDialog ();
}
});
}
public void openDialog () {
AlertDialog.Builder builder = new AlertDialog.Builder (this);
builder.setTitle ("Hello");
builder.setMessage ("Hello World \ n");
builder.setNegativeButton ("OK", null);
builder.show ();
}

@ Override
public boolean onCreateOptionsMenu (Menu menu) {
/ / Inflate the menu; this adds items to the action bar if it is present
.getMenuInflater () inflate (R.menu.main, menu);.
return true;
}

}

Reply:
Think of ways to define onClick in xml in the case, be sure to use this format:
 public void openDialog (View view) {
/ / ...
}

To be defined as public, and to accept a View as parameters, this parameter is less here, you is not enough.
Or use the second floor of the method, using code.

No comments:

Post a Comment