Juan BG
Juan BG

Reputation: 97

How to manipulate the contents of a button without using id; Android?

I'm new in android world and I have a problem, well, I'm making a project very simple it is about an activity where i have a button and an EditText. The button has an event onClick in XML. My problem is it: I need the button value and send this value to EditText but my button don't have a id. Help me I don't know how manipulate a element if it dont have a id.

XML Code:

 <View 
             android:layout_height="@dimen/cell_height"
             android:background="@color/red"/>
         <Button 
             android:layout_marginLeft="@dimen/button_margin"
             android:layout_gravity="center_vertical"
             android:text="@string/hex_red"
             android:textColor="@color/red"
             android:onClick="copy"/>`

Java code:

public void copy(View boton){

    EditText txtSelected = (EditText)this.findViewById(R.id.txtColor)

    String color =  boton; <-- here need the button value

    txtSelected.setText(color);
}

I need your help, Thanks

Upvotes: 1

Views: 299

Answers (3)

Salman500
Salman500

Reputation: 1211

public void onClickBtn(View view) {

EditText txtSelected = (EditText)this.findViewById(R.id.txtColor)


Button btn = (Button)(view);
String value = (String) btn.getText();
txtSelected.setText(value);
txtSelected.setSelection(value.length()); // cursor will be at the end of the text

}

Upvotes: 0

chartsai
chartsai

Reputation: 368

Modify your copy() function like this:

public void copy(View boton) {
  EditText txtSelected = (EditText)this.findViewById(R.id.txtColor)

  Button btn = (Button) boton;  // << key point.
  String color = btn.getText().toString();

  txtSelected.setText(color);
}`

Upvotes: 1

krishna
krishna

Reputation: 609

you can say boton.getText().toString()

Upvotes: 1

Related Questions