Android为布局添加ID

Zba*_*ian 6 layout android

如何为布局定义ID?

我正在尝试向线性布局添加ID并设置onclick侦听器:

XML:

<LinearLayout
   android:id="@+id/?????????"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:onClick="btnHandler" >
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

类:

public class MainActivity extends Activity {
    //....

    public void btnHandler(View v){
       switch(v)
       {
          case R.id.????? :
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

Rag*_*dan 8

既然你有这个

 <LinearLayout
 android:id="@+id/linearlayout"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 android:onClick="btnHandler" >
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

你可以这样做

  public void btnHandler(View v)
  {
      switch(v.getId()) // use v.getId()
   {
      case R.id.linearlayout :
      break;  // also don't forget the break;
   }

  }  
Run Code Online (Sandbox Code Playgroud)

编辑:

如果你有按钮,那么你可以这样做.

<?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>
Run Code Online (Sandbox Code Playgroud)

然后在你的活动中

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;
       }
}
Run Code Online (Sandbox Code Playgroud)


Sce*_*Lus 5

代替

switch(v)
Run Code Online (Sandbox Code Playgroud)

使用

switch(v.getId())
Run Code Online (Sandbox Code Playgroud)

并从 xml 设置你的 id

android:id="@+id/idValue"
Run Code Online (Sandbox Code Playgroud)