Android: Return a string from a view?

做~自己de王妃 提交于 2019-12-14 03:59:34

问题


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();
    .....
}


来源:https://stackoverflow.com/questions/5672177/android-return-a-string-from-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!