How do I access the views inside the layout when I reuse it multiple times?

后端 未结 2 1731
孤街浪徒
孤街浪徒 2020-12-08 19:14

I have read the Android UI trick 2 on Android developers, which tells people how to include a layout in another layout file multiple times, and give these included layouts d

2条回答
  •  萌比男神i
    2020-12-08 19:44

    Say you want to include this:

    
        
        
    
    

    so in your code you insert it like this:

    
        
        
    
    

    now you want to access the text views within the included layouts to set the text dynamically. In your code you simply type:

    LinearLayout ll = (LinearLayout)findViewById(R.id.header_1);
    TextView tv = (TextView)ll.findViewById(R.id.included_text_view);
    tv.setText("Header Text 1");
    
    ll = (LinearLayout)findViewById(R.id.header_2);
    tv = (TextView)ll.findViewById(R.id.included_text_view);
    tv.setText("Header Text 2");
    

    notice that you use the individual LinearLayouts' findViewById methods to narrow the search to only their children.

提交回复
热议问题