PDA

View Full Version : Newbie Question



moses2011
12-05-2011, 02:09 AM
Hello Guys, i am trying to learn to develope application on android using Eclipse and Java.
So here is the code, and my aim is to make when i click button 1 the content of edittext 1 be copied to edittext 2 but seems to no avail.

public
class HelloActivity extends Activity implements OnClickListener {


/** Called when the activity is first created. */




private Button button1;


private Button button2;


private Button button3;


@Override


public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

setContentView(R.layout.
main);




button1 = (Button)findViewById(R.id.button1);


button1.setOnClickListener(this);




button2 = (Button)findViewById(R.id.button2);


button2.setOnClickListener(this);




button3 = (Button)findViewById(R.id.button3);


button3.setOnClickListener(this);

}




public void onClick(View arg0) {


// TODO Auto-generated method stub

EditText nameField = (EditText) findViewById(R.id.edittext1);

String name = nameField.getText().toString();


if (name.length() == 0) {


new AlertDialog.Builder(this)

.setMessage(R.string.error_text1_missing)

.setNeutralButton(R.string.error_ok,
null)

.show();


return;

}




if (arg0 == button1)

{




int resourceId = arg0 == button1 ? R.string.edittext1; <=== the error



String greeting = getResources().getString(resourceId, name);

Toast.makeText(
this, greeting, Toast.LENGTH_LONG).show();



EditText greetingField = (EditText) findViewById(R.id.edittext2);

greetingField.setText(greeting);

}

alostpacket
12-10-2011, 03:24 PM
R.string.yourresourceID is an int

The parameter that is passed to onClick is the View object that was clicked. It looks like you are trying to compare the View with the int in your short-hard if statement ( the one with like a=b? x:y; )

See if this makes sense:


public void onClick( View arg0 )
{

//first lest get the ID of the view that was actually clicked
//to do this we'll use view.getId(); this will return the int resource identifier

int resourceId = arg0.getId();



//now we can compare the resource ID of what was clicked with the resource ID of button1

if ( resourceId == R.string.edittext1 )
{
//do something cool here
}


}
//end onClick();