简体   繁体   English

如何获得线性布局的子对象的位置?

[英]How to get the position of the child of the child of a linear layout?

This is my xml : 这是我的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>

I want click listener on the all buttons and I want to have the position when I click on a button. 我想在所有按钮上单击侦听器,并且我想在单击按钮时拥有位置。 I tried several things without success.Indeed, I can't to have the clicked button position. 我尝试了好几次都没有成功。的确,我无法确保按钮的位置。

Try this logic: 尝试以下逻辑:

In your activity, do this: 在您的活动中,执行以下操作:

LinearLayout layout = findViewById(R.id.col1);

then, in every buttons's onClick : 然后,在每个按钮的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;
    }
}            

The same logic can also apply for the LinearLayout col2 相同的逻辑也可以适用于LinearLayout col2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM