我有LinearLayout
,其中包含两个RelativeLayouts
。
以下是XML代码:
<LinearLayout
android:id="@+id/SaleSwithcBarView_navigation_bar_LinrearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
<RelativeLayout
android:id="@+id/SaleSwithcBarView_users_created_bar_button_RelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/SaleSwithcBarView_users_favorite_bar_button_RelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
</LinearLayout>
现在我试图用clickListner
检测哪个视图(从这两个RelativeLayouts
被点击),我试图这样做(java代码):
navigationBar.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View navigationButton)
{
Toast.makeText(context, "hope here: " + navigationButton.getId(), Toast.LENGTH_LONG).show();
switch (navigationButton.getId())
{
case USER_CREATED_BUTTON_ID:
Toast.makeText(context, "here", Toast.LENGTH_LONG).show();
switchTodDisplay(USER_CREATED_BUTTON_ID + BINDER_OFFSET);
break;
case USER_FAVORITE_BUTTON_ID:
Toast.makeText(context, "or here", Toast.LENGTH_LONG).show();
switchTodDisplay(USER_CREATED_BUTTON_ID + BINDER_OFFSET);
break;
default:
break;
}
}
});
navigationBar
是LinearLayout
而USER_CREATED_BUTTON_ID
(final int
)是左RelativeLayout
的ID,USER_FAVORITE_BUTTON_ID
是右{id RelativeLayout
。这两个id我都是以编程方式分配的:
userCreatedSalesBarButton.setId(USER_CREATED_BUTTON_ID);
userFavoriteSalesBarButton.setId(USER_FAVORITE_BUTTON_ID);
那么我怎样才能检测出哪个LinearLayout
子视图被点击了。我不想为每个clickListeriner
创建RelativeLayout
。
谢谢
答案 0 :(得分:1)
我不想为每个RelativeLayout创建一个clickListeriner。
您可以使用单个OnClickListener
实施,但是您必须将OnClickListener
实际分配给要在其点击时找到的小部件。
或者:
将现有的OnClickListener
匿名内部类转换为常规内部类,然后创建该内部类的两个实例以用于每个“按钮”,或者
将您的OnClickListener
匿名内部类的实例存储在数据成员中,然后在setOnclickListener()
中为每个“按钮”使用该数据成员