简体   繁体   中英

Android: Swap the position of 2 views

On my TableLayout, one TableRow has a TextView, and another has a 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.

Animation doesn't matter. The preference would be that it happens instantly, but I could make it a super-fast animation if necessary.

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.

Thanks!

You can try to remove the first TextView and then add back to the end of the linear layout using 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. I'm using TableRow because it is the type of the parent of the views I want to swap. 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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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