我有一個FrameLayout
表,其中每個幀包含ImageView
或TextView
。無論幀中的內容如何,我都希望onClick
事件能被幀上設置的OnClickListener
檢測到。如何讓點擊事件傳遞給Android中的容器?
我怎樣才能做到這一點?
這是我的一些佈局,我總共有5行(這裏只顯示1)。 如上所述,每行有5個FrameLayouts,每個包含一個TextView。我無法將我的OnClickListener放在TextView上,因爲這可能會在運行時更改爲ImageView。因此我想要FrameLayout上的OnClickListener。
看來,FrameLayout的內容阻止它檢測到點擊事件。
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/gateContainer"
android:stretchColumns="*">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/door1"
android:clickable="true">
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="New Text"
android:id="@+id/textView"
android:layout_gravity="center" />
</FrameLayout>
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/door2" >
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="New Text"
android:id="@+id/textView5"
android:layout_gravity="center" />
</FrameLayout>
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/door3" >
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="New Text"
android:id="@+id/textView4"
android:layout_gravity="center"/>
</FrameLayout>
</TableLayout>
下面是我如何設置OnClickListeners一個例子:
View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v){
// do something
}
};
TableLayout tableLayout = (TableLayout) findViewById(R.id.gateContainer);
// Go through all TableRows
for (int i = 0; i < tableLayout.getChildCount(); i++){
TableRow tableRow = (TableRow) tableLayout.getChildAt(i);
// Set listener for each FrameView
for (int j = 0; j < tableRow.getChildCount(); j++){
FrameLayout frame = (FrameLayout) tableRow.getChildAt(j);
frame.setOnClickListener(clickListener);
}
}
哪裏是你的代碼? – GrIsHu
發佈一些代碼給我們看看你迄今爲止所嘗試過的。 –
@GrIsHu代碼已添加。 – frmi