How to get Position of an view added dynamically on LinearLayout

前端 未结 4 1089
庸人自扰
庸人自扰 2020-12-12 00:39

I need to get an dynamically added view position in LinearLayout with vertical orientation. For example i have 4 TextViews added dynamically on LinearLayout, then i need to

相关标签:
4条回答
  • 2020-12-12 01:18

    I got simple option.

    suppose you add

    View v;//any view

    linearlayout.addview(v);//add in layout

    While u want to modify view.

    simpaly remove old view.

    linearlayout.removeView(v);

    add new update view object

    v-updated new view

    linearlayout.addview(v);

    0 讨论(0)
  • 2020-12-12 01:19

    I see following options:

    • Declare some id's in resources in form of <item type="id">first</item> and assign them to views in adding to layout, after that use normal findViewById() mechanism
    • Assign some tags to views you're adding to a layout via setTag method and after that use findViewWithTag mechanism
    • Remeber position of your views and use them vie getChildAt method
    0 讨论(0)
  • 2020-12-12 01:30

    You can do it just like that

    ViewGroup parent;
        int position;
    
        for(int i = 0; i < parent.getChildCount(); ++i) {
            int currentViewId = parent.getChildAt(i).getId();
    
            if(currentViewId == wantendViewId) {
                position = i;
            }
        }
    

    That's (in my opinion) the simplest way

    0 讨论(0)
  • 2020-12-12 01:41

    If you always know the number of TextViews in your LinearLayout, you can just use the function getChildAt( int position ). This returns a View which you can then cast to a TextView to be able to perform the desired operations.

    If you do not know the number of elements you could set the id of each TextView (in order to be able to identify a particular one) and then run through them like this:

    for( View view : myLinearLayout )
      if( view instanceof TextView && view.getId().equals( idToSearchFor ) )
        //Do what needs to be done.
    
    0 讨论(0)
提交回复
热议问题