【问题标题】:How to get the position of the child of the child of a linear layout?如何获取线性布局的子节点的位置?
【发布时间】:2018-07-19 14:32:14
【问题描述】:

这是我的 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>

我想在所有按钮上单击侦听器,并且希望在单击按钮时获得位置。我尝试了几件事都没有成功。确实,我无法获得点击按钮的位置。

【问题讨论】:

  • 你需要什么职位?单击的Button 之一或您单击的触摸屏点之一(忽略特定的视图元素)。
  • 被点击的按钮之一
  • 请看this question关于getLocationOnScreen()getLocationInWindow(),它们是Android中View类的方法
  • 我看不懂这个例子。我看不出与我想做的事情的关系......
  • 它为您提供视图元素(在您的情况下为Button)相对于显示或父视图的坐标。如果这不是您想要的,请描述您在问题中使用的 position 想法。

标签: java android


【解决方案1】:

试试这个逻辑:

在您的活动中,执行以下操作:

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;
    }
}            

同样的逻辑也可以应用于LinearLayoutcol2

【讨论】:

  • 哦,我必须把名字和按钮一样多?所以我让代码成倍增加,我觉得一点都不好。
  • 您也可以使用相同的for loop(不带if)来初始化按钮,前提是您使用了一组按钮。声明类似于:buttons[i] = layout.getChildAt(i);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多