2011-01-24 65 views

回答

60

你与该ID包括标签分配给包括布局的根视图。 首先使用findViewByid获取对该视图的引用。然后,您可以在该特定视图上调用findViewById以获取对布局中的View的引用。所以:

View myLayout = findViewById(R.id.cell1); // root View id from that link 
View myView = myLayout.findViewById(R.id.someinnerview); // id of a view contained in the included file 
+1

为什么这不是正确的答案! – 2017-06-02 04:38:45

2

你知道包含的id。你可以得到这个完整的元素,然后从那里开始让它的一个孩子开始。

0

其实include标签包含您的根布局中的所有元素。所以你可以随时在你的活动上使用findViewById访问它们。

假设您有一个alayout.xml其中有一个include布局。现在在您的活动A之一onCreate内宣布setContentView(R.layout.alayout)现在在您的包含版式中,您可能会有一个ID为myBtn的按钮。您可以访问内部onCreate中,你可以访问它,如果它是在主要布局以同样的方式:findViewById(R.id.myBtn)

12

所有你需要的是父视图的id:

enter image description here

在这个例子中, LinearLayout是我想从包含的视图中获得的TextView的父项。

我现在可以这样做:

View view = findViewById(R.id.include_title_layout); 
    TextView titleTV = (TextView) view.findViewById(R.id.newsTitleTextView); 
    titleTV.setText("Whatever"); 
0

我觉得你的意思是NavigationView。你可以通过这种方式访问​​内部布局:

NavigationView ngv= (NavigationView) findViewById(R.id.navigation_id); 
View innerview = ngv.getHeaderView(0); 
TextView user_view= (TextView)innerview.findViewById(R.id.nav_name); //any you need 
user_view.setText(user);