如何在"包含"布局中访问Button

cho*_*how 36 layout android onclick include

请参阅doc:http://android-developers.blogspot.com/2009/02/android-layout-tricks-2-reusing-layouts.html

我在包含的布局中有一个按钮,我该如何访问按钮?我不知道id!如何定义OnClickListener ...?

请帮忙...

Jem*_*ems 73

包含标记的id已分配给包含布局的根视图.首先使用findViewByid获取对该视图的引用.然后,您可以在该特定View上调用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
Run Code Online (Sandbox Code Playgroud)


ojo*_*ifu 18

您只需要父视图的ID:

在此输入图像描述

在此示例中,它LinearLayoutTextView包含的View中我想要的父级.

我现在可以这样做:

    View view = findViewById(R.id.include_title_layout);
    TextView titleTV = (TextView) view.findViewById(R.id.newsTitleTextView);
    titleTV.setText("Whatever");
Run Code Online (Sandbox Code Playgroud)


bk1*_*138 5

在多次包含相同的XML布局时,解决窗口小部件ID存在一个常见的缺陷.http://www.coboltforge.com/2012/05/tech-stuff-layout/上的博客文章正好解释了这个问题以及如何解决它!