Angkor Empire
Angkor Empire

Reputation: 221

How to I get value text inside of button by using one function

I have many button look like keyboard. that contain with diference text inside example: 0123456789abcdefghijkl... what I want is how to implement click one of them I get value text inside of button by using one function FilterBusinessKeyboard

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >
        <Button
              android:layout_width="match_parent"
              android:layout_height="@dimen/button_height"
              android:layout_margin="1dp"
              android:layout_weight="1"
              android:text="0"
              android:background="@drawable/btn_key"
              android:onClick="FilterBusinessKeyboard"
              />
       <Button
              android:layout_width="match_parent"
              android:layout_height="@dimen/button_height"
              android:layout_margin="1dp"
              android:layout_weight="1"
              android:text="1"
              android:background="@drawable/btn_key"
              android:onClick="FilterBusinessKeyboard"
              />
.......
</LinearLayout>

Upvotes: 0

Views: 457

Answers (3)

Athul
Athul

Reputation: 821

You can define a function and with view called in it . Initialise the function and fetch the button you defined before globally and initialised in onCreate method.

    public class ButtonActivity extends AppCompatActivity {
    Button button;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_button_activity);

    }
    public void FilterBusinessKeyboard(View view){


        Toast.makeText(this, ((Button) view).getText().toString(), Toast.LENGTH_SHORT).show();
    }
}

Upvotes: 0

Amir Panahandeh
Amir Panahandeh

Reputation: 9059

use this:

public void FilterBusinessKeyboard(View view){
    ((Button) view).getText();
}

Edit

If you extend Fragment instead of Activity then you have to choose one of this ways:

1-Declare another click function in your activity then send calls to your fragment

public void FilterBusinessKeyboard(View view){
    fragment.FilterBusinessKeyboard(view);
}

2-Use setOnClickListener for buttons inside Fragment

Upvotes: 4

Vinodh
Vinodh

Reputation: 1129

set ID for each button in xml and get the text of the Button using getText().toString() API on button view using switch :

public void getTextFromButton(View view){
    switch(view.getId())
    {
        case R.id.button1:
            //get text

            break;
        case R.id.button2:
            //get text

            break;
        case R.id.button3:
            //get text
            break;
            .
            .
            .
        case R.id.buttonN:
            //get text
            break;
    }
}

Upvotes: 0

Related Questions