![](/img/trans.png)
[英]How to dynamically add a linear layout (as a child) to a constraint layout (parent)?
[英]How to get the position of the child of the child of a linear layout?
這是我的xml:
<?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:orientation="vertical"
android:gravity="top"
android:rotation="180">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:id="@+id/cols">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/col1">
<Button .../>
<Button .../>
<Button .../>
<Button .../>
<Button .../>
<Button .../>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/col2">
<Button .../>
<Button .../>
<Button .../>
<Button .../>
<Button .../>
<Button .../>
</LinearLayout>
</LinearLayout>
</LinearLayout>
我想在所有按鈕上單擊偵聽器,並且我想在單擊按鈕時擁有位置。 我嘗試了好幾次都沒有成功。的確,我無法確保按鈕的位置。
嘗試以下邏輯:
在您的活動中,執行以下操作:
LinearLayout layout = findViewById(R.id.col1);
然后,在每個按鈕的onClick
:
for(int i=0; i<layout.getChildCount(); i++) {
if(layout.getChildAt(i).equals(thisButton))//Replace thisButton with the variable name
{
//do something
// i represents the button's position in its immediate parent.
break;
}
}
相同的邏輯也可以適用於LinearLayout col2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.