In my android app, when I create a button with java code, I want to be able to store a string inside it, and then later when it is pressed, get that string again.
Can anyone show me how to do this?
Thanks,
Add meta-data: Add metadata to the app module's AndroidManifest. xml file under the application tag. You can add as many metadata elements as you want and you can also add metadata under the activity, service, broadcast receiver, content provider tags. The metadata tag has name , value , and resource .
To define the click event handler for a button, add the android:onClick attribute to the <Button> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
Applications just need to define meta-data in their AndroidManifest which can later be used by the library. This is used by both Crashlytics and Google Admobs for Android. Once defined, library can fetch these values from PackageManager which returns a bundle having values defined by applications in their manifest.
TextView displays a formatted text label. ImageView displays an image resource. Button can be clicked to perform an action.
You can use View.setTag()
and View.getTag()
to store and retrive String. So when your button pressed, you probably have a callback to OnClickListener, with method onClick(View v)
, so you can retrive your String there using v.getTag()
.
Start by creating the button in the xml file (assuming activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btnMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Click" />
</LinearLayout>
Then from your own activity you can find it and add/retrieve information from it.
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find button by id
Button btn = (Button)findViewById(R.id.btnMessage);
// enclose secret message
btn.setTag("Bruce Wayne is Batman");
}
// this function is triggered when the button is pressed
public void onClick(View view) {
// retrieve secret message
String message = (String) view.getTag();
// display message in the console
Log.d("Tag", message);
}
}
This method is useful to hide information (such as database keys or superheroes' secret identities).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With