简体   繁体   English

Android:交换 2 个视图的 position

[英]Android: Swap the position of 2 views

On my TableLayout, one TableRow has a TextView, and another has a Spinner.在我的 TableLayout 上,一个 TableRow 有一个 TextView,另一个有一个 Spinner。 When the user checks a checkbox, I want to swap the positions of these 2 views.当用户选中一个复选框时,我想交换这两个视图的位置。 The Spinner needs to move to the position of the TextView, and the TextView needs to move to the position of Spinner. Spinner需要移动到TextView的position,TextView需要移动到Spinner的Z4757FE07FD4962A8BEEZEA6A76D的position。

Animation doesn't matter. Animation 没关系。 The preference would be that it happens instantly, but I could make it a super-fast animation if necessary.首选是它会立即发生,但如有必要,我可以将其设为超快 animation。

I have been surprised at how much trouble I've had trying to locate a solution to this problem:/ On a similar note, the Android dev ref could really use some simple examples a la the MSDN library.我很惊讶我在试图找到解决这个问题的方法时遇到了多少麻烦:/在类似的说明中,Android 开发参考确实可以使用一些简单的示例,例如 MSDN 库。

Thanks!谢谢!

You can try to remove the first TextView and then add back to the end of the linear layout using addView. 您可以尝试删除第一个TextView,然后使用addView添加回线性布局的末尾。

TextView tv = (TextView)layout.getChildAt(0);
layout.removeView(tv);
layout.addView(tv);

It's not a really clean code, but I thing might work :) 这不是一个很干净的代码,但是我可能会工作:)

Here is the code I ended up using to swap the views: 这是我最终用来交换视图的代码:

import android.widget.TableRow;

TableRow trI = (TableRow) findViewById(R.id.tr_input_row);
TableRow trO = (TableRow) findViewById(R.id.tr_output_row);
View v1 = (View) findViewById(R.id.View1);
View v2 = (View) findViewById(R.id.View2);

if (isInput()) {
    trO.removeView(v1);
    trI.removeView(v2); 
    trO.addView(v2);
    trI.addView(v1);
} else {
    trO.removeView(v2);
    trI.removeView(v1); 
    trO.addView(v1);
    trI.addView(v2);
}

In my case, the views were in two different rows of a TableLayout. 就我而言,视图位于TableLayout的两个不同行中。 I'm using TableRow because it is the type of the parent of the views I want to swap. 我正在使用TableRow,因为它是我要交换的视图的父级的类型。 I assume this could be updated to be whatever type of parent the target views have. 我认为可以将其更新为目标视图具有的任何父类型。

Here is a generic Kotlin function to swap the positions of 2 views - I have not tested whether it works for your case of Spinner and TextView , but I don't currently see why not这是一个通用的 Kotlin function 来交换 2 个视图的位置 - 我没有测试它是否适用于您的SpinnerTextView的情况,但我目前不明白为什么

fun swapViews(view1: View, view2: View){
    val view1Parent = view1.parent as ViewGroup
    val view1Params = view1.layoutParams
    val view2Parent = view2.parent as ViewGroup
    val view2Params = view2.layoutParams
    view1Parent.removeView(view1)
    view2Parent.removeView(view2)
    view2Parent.addView(view1)
    view1Parent.addView(view2)
    view1.layoutParams = view2Params
    view2.layoutParams = view1Params
}

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

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