Android: Return a string from a view?

2019-07-24 15:29发布

问题:

How do I get a string from a view? To be more specific I have 36 buttons in a tabview. When I click the button it calls an

android:onClick="onClick"

from my XML to call the method onClick(View v). I then want to pass variables via an intent to another activity based on the button clicked. Now I know my View of the button pressed is 'v', what I want to know is how to take that view and make it a string that I can manipulate.

回答1:

In your xml define of Button, set tag for it:

<Button
    android:layout_width="wrap_content"
    android:layout_height="40dip"
    android:text="Btn 1"
    android:tag="1"android:onClick="onClick"/>

And in onClick function: public void onClick(View v)

{
    Button button = (Button) v;
    String tag = button.getTag.toString();
    //now open new Activity with this tag
    Intent intent = new Itent();
    Bundle b = new Bundle();
    b.putString("tag", tag);
    intent.putExtras(b);
    startActivity(intent);
}


回答2:

Do you mean this? It's explicit class casting, a Java language feature.

public void onClick(View v)
{
    Button button = (Button) v;
    String info = button.getText();
    Intent intent = new Intent();
    .....
}