Senthil Mg
Senthil Mg

Reputation: 3313

How to get Position of an view added dynamically on LinearLayout

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 change position of text colour at 3rd position will be in different color.How can i achieve it by getting position of added views.

Upvotes: 2

Views: 4948

Answers (4)

dudeldidadum
dudeldidadum

Reputation: 1281

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

Upvotes: 2

Viren Savaliya
Viren Savaliya

Reputation: 530

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

Upvotes: 0

Nikolay Ivanov
Nikolay Ivanov

Reputation: 8935

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

Upvotes: 0

kaspermoerch
kaspermoerch

Reputation: 16570

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.

Upvotes: 0

Related Questions