B
B
Behtold_A2017-05-14 13:00:00
Android
Behtold_A, 2017-05-14 13:00:00

How to get the coordinates of a View element in Android after it has been created?

I create screen elements programmatically. There was a need to determine the coordinates of the newly created element. However, requests for getTop(), getBottom(), etc. always return zero. Tell me where to dig?

public class Main extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // ------------------------------- Создаем корневой лайаут
        RelativeLayout rootLayout = new RelativeLayout(this);
        ViewGroup.LayoutParams rootParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        setContentView(rootLayout, rootParams); 
        //---------------------------------- лайаут под элементы
        LinearLayout menu = new LinearLayout(this);
        RelativeLayout.LayoutParams menuParam = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                                                 ViewGroup.LayoutParams.WRAP_CONTENT);
        menuParam.addRule(RelativeLayout.CENTER_IN_PARENT); // В центр
        rootLayout.addView(menu,menuParam);
        // ----------------------------- Элементы
        LinearLayout.LayoutParams itemParam = new LinearLayout.LayoutParams // Создаем настройку для элементов
                (ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);

        String[] items = {"Item1", "Item2", "Item3"};
        TextView[] text = new TextView[items.length]; // Создаем массив элементов

        for (int i=0; i<items.length; i++) {
            text[i] = new TextView(this);
            text[i].setText(items[i]+" ");
            menu.addView(text[i], itemParam);

            int x0 = text[i].getLeft(),
                    y0 =text[i].getTop(),
                    x1 = text[i].getRight(),
                    y1 = text[i].getBottom();

            System.out.println("Создали элемент с координатами: [" + x0 + "," + y0 + "]-[" + x1 + "," + y1 + "]");
        }

    }
}

This code displays the elements normally, but in the console it gives:
I/System.out: Created element with coordinates: [0,0]-[0,0]
I/System.out: Created element with coordinates: [0,0]-[0,0]
I/System.out: Created element with coordinates: [0,0]-[0,0]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2017-05-14
@Behtold_A

View.getViewTreeObserver().addOnGlobalLayoutListener(...);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question