Roger
Roger

Reputation: 4269

findViewById in specific layout?

Instead of prefixing id's in xml, is it possible to specify the particular layout in code? For example, if I have 3 layouts, each with a button that has an id of "btn". Is it possible to specify which layout to findViewById(R.id.btn) in?

Upvotes: 3

Views: 11043

Answers (4)

Rafael T
Rafael T

Reputation: 15689

if you have your btns inside different Viewgroups, it is possible, but requires to give ViewGroups a different name! Easyiest will be for that purpose to define the Layout of the Button inside its own XML (i.e button_layout.xml) inside your Activity you can do this:

public MyActivity extends Activity{

  Button btn1, btn2, btn3;

  public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);

    LinearLayout ll = new LinearLayout(this);
    setContentView(ll);

    btn1 = (Button)inflater.inflate(R.layout.button_layout, ll);
    btn2 = (Button)inflater.inflate(R.layout.button_layout, ll);
    btn3 = (Button)inflater.inflate(R.layout.button_layout, ll);

  }
}

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234857

If your content view is a complex hierarchy that has several views with id btn, you will need to navigate to a subtree of the hierarchy and search from there. Suppose you have three LinearLayout views, each with a btn view somewhere in it. If you can first select the correct LinearLayout (by id, tag, position, or some other means), you can then find the correct btn view. If the relevant LinearLayout has id of branch1, for instance:

View parent = findViewById(R.id.branch1); // Activity method
View btn = parent.findViewById(R.id.btn); // View method

Upvotes: 0

asenovm
asenovm

Reputation: 6517

findViewById is a method of the View class. You can specify where the view should be searched for like that

final View container = new View(context); 
container.findViewById(R.id.btn);

Upvotes: 3

WarrenFaith
WarrenFaith

Reputation: 57702

The basic context is defined via setContentView(R.lyaout.my_layout). If you inflate another layout using LayoutInflater.inflate() you get a layout object, lets call it buttonLayout. You can now differ between this.findViewById(R.id.button) and buttonLayout.findViewById(R.id.button) and both will give you different button references.

Upvotes: 5

Related Questions