2013-01-25 25 views
7

我有這樣如何使一個Relativelayout可點擊?

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/mainLayout" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:addStatesFromChildren="true" 
    android:clickable="true" 
    android:duplicateParentState="true" 
    android:focusable="true" 
    android:paddingBottom="10dip" > 

    <ImageView 
     android:id="@+id/imagView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_centerVertical="true" 
     android:focusable="false" 
     android:background="@drawable/imageView_bg" 
     android:focusableInTouchMode="false" /> 

    <Button 
     android:id="@+id/button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_centerVertical="true" 
     android:layout_marginLeft="18dip" 
     android:background="@drawable/button_bg" 
     android:clickable="false" 
     android:focusable="false" 
     android:focusableInTouchMode="false" 
     android:gravity="left|center_vertical" 
     android:paddingLeft="25dip" 
     android:textColor="#ffffff" 
     android:textSize="20dip" /> 

</RelativeLayout> 

button_bg.xml佈局

<?xml version="1.0" encoding="utf-8"?> 
    <selector xmlns:android="http://schemas.android.com/apk/res/android"> 
     <item android:drawable="@drawable/btn_pressed" 
      android:state_pressed="true"/> 
     <item android:drawable="@drawable/btn_normal"/> 

    </selector> 

imageView_bg.xml

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:drawable="@drawable/img_pressed" 
     android:state_pressed="true"/> 
    <item android:drawable="@drawable/img_normal"/> 

</selector> 

圖像視圖和按鈕已按下images.when在用戶點擊查看,想要同時按下圖像查看和按鈕(顯示按下的圖像)。但它不顯示按下的圖像。如何實現這一目標?哪裏有問題?

在此先感謝

+1

你附加一個OnClickListener到你的RelativeLayout? – Shark

+0

它們堆疊在一起嗎? – njzk2

+1

用佈局替換圖像視圖,在其中放置按鈕,並將重複的父狀態添加到按鈕 – njzk2

回答

4

我認爲它解決了這個問題

((RelativeLayout)findViewById(R.id.mainLayout)).setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View view) { 
    ViewGroup viewGroup = (ViewGroup) view; 
    for (int i = 0; i < viewGroup .getChildCount(); i++) { 

     View viewChild = viewGroup .getChildAt(i); 
     viewChild.setPressed(true); 

      } 
    } 
}); 
0

Simple.Place RelativeLayout在FrameLayout中。

13
RelativeLayout rl = (RelativeLayout)findViewById(R.id.mainLayout); 

rl.setOnClickListener(new View.OnClickListener(){ 
    public void onClick(View v) {} 
}); 
+0

如果您正在接收「」RelativeLayout無法解析爲某個類型「,請確保在頂部導入以下內容你的java文件:import android.widget.RelativeLayout;並導入android.view.View; – jwinn

+1

你不能只設置'android:clickable =「true」'? –