Reputation: 25
public void onClick(View v) {
int id = v.getId();
switch(id) {
case R.id.a :
String textans = ans.getText().toString();
ans.setText(textans +id);
}
}
I am creating an android application in which i have 5 ImageButton
s and a TextView
.
ImageButton
s are having alphabet images i.e A, B, C, D, E and their ID's in XML are a, b, c, d, e as follows
<ImageButton
android:id="@+id/a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="170dp"
android:layout_marginLeft="18dp"
android:src="@drawable/a" />
<ImageButton
android:id="@+id/b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/imageButton5"
android:layout_toRightOf="@+id/imageButton5"
android:src="@drawable/b" />
<ImageButton
android:id="@+id/c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/imageButton2"
android:layout_toRightOf="@+id/imageButton2"
android:src="@drawable/c" />
<ImageButton
android:id="@+id/d"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/imageButton3"
android:layout_toRightOf="@+id/imageButton3"
android:src="@drawable/d" />
<ImageButton
android:id="@+id/e"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/a"
android:layout_toRightOf="@+id/a"
android:src="@drawable/e" />
What I want is when I click an ImageButton
the respective letter must be set in TextView
. For this purpose I have used a switch
in onClick
method and tended to get the ID of the button and set it in TextView
but id is something in int
.
My question is this "How can I get the name of the ID of button clicked". For example when Iclick button having image A, the id of ImageButton
is "a", so it must be stored in a variable and then it is set to TextView
.
Hopefully my question is much clear.
Upvotes: 1
Views: 3488
Reputation: 20513
If you want to set the ID of the clicked button to your TextView
you could use something like this
String resourceName = getResources().getResourceEntryName(int resId);
Use in your solution
public void onClick(View v) {
int id = v.getId();
switch(id) {
case R.id.a:
String resourceName = getResources().getResourceEntryName(id);
textView.setText(resourceName);
break;
}
}
Upvotes: 2