How do I define an ID to a layout?
I am trying to add an ID to a linearlayout and setting an onclick listener:
XML:
<LinearLayout
android:id="@+id/?????????"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:onClick="btnHandler" >
</LinearLayout>
Class:
public class MainActivity extends Activity {
//....
public void btnHandler(View v){
switch(v)
{
case R.id.????? :
}
}
}
Assign id via XMLAdd an attribute of android:id="@+id/ somename " to your view. When your application is built, the android:id will be assigned a unique int for use in code. Reference your android:id 's int value in code using " R.id.
attributes: android:id. Resource ID. A unique resource name for the element, which you can use to obtain a reference to the View from your application.
This is no longer possible,android lint checks prevent you from adding same ids in the same xml file. A work-around would be to use the include tag to include other xmls with repeating ids. Nevertheless this is an approach that should be avoided. Save this answer.
Difference between “@+id/” and “@id/” in Android. The first one is used for to create the ID of the particular ui component and the another one is used for to refer the particular component. Follow this answer to receive notifications.
Since you have this
<LinearLayout
android:id="@+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:onClick="btnHandler" >
</LinearLayout>
You can do as below
public void btnHandler(View v)
{
switch(v.getId()) // use v.getId()
{
case R.id.linearlayout :
break; // also don't forget the break;
}
}
Edit:
If you have button then you can do as below.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/linearlayout"
android:onClick="clickEvent"
android:orientation="vertical" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt1"
android:text="button"
android:onClick="clickEvent"
/>
</LinearLayout>
Then in your activity
public void clickEvent(View v)
{
switch(v.getId())
{
case R.id.linearlayout :
Log.i("......"," linear layout clicked");
break;
case R.id.bt1 :
Log.i("......"," button clicked");
break;
}
}
Instead of
switch(v)
use
switch(v.getId())
and set your id from the xml
android:id="@+id/idValue"
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