如何为布局定义 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>
类:
public class MainActivity extends Activity {
//....
public void btnHandler(View v){
switch(v)
{
case R.id.????? :
}
}
}
最佳答案
既然你有这个
<LinearLayout
android:id="@+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:onClick="btnHandler" >
</LinearLayout>
你可以按照下面的方式做
public void btnHandler(View v)
{
switch(v.getId()) // use v.getId()
{
case R.id.linearlayout :
break; // also don't forget the break;
}
}
编辑:
如果你有按钮,那么你可以按照下面的方式做。
<?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>
然后在你的 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;
}
}
关于Android 将 ID 添加到布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17471808/