2012-04-30 57 views
2

我有3個嵌套佈局,我在訪問其中的視圖時遇到困難。下面的主要xml(A.xml)包含B的單個實例,其中包含多個C.xml。有在C.xml 3個圖像訪問Android中的嵌套佈局

A.XML - >這是主要的XML

<include 
     android:id="@+id/b" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     layout="@layout/B" /> 

B.XML - >這是第2級

<include 
     android:id="@+id/c1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     layout="@layout/C" /> 

    <include 
     android:id="@+id/c2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     layout="@layout/C" /> 

    <include 
     android:id="@+id/c3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     layout="@layout/C" /> 

C.xml - 這是3級

<ImageView 
     android:id="@+id/a1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/img1" /> 

    <ImageView 
     android:id="@+id/a2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/img2" /> 

    <ImageView 
     android:id="@+id/a3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/img3" /> 

所以在這裏,main包含B上的一個實例,它又包含了C的多個實例。所以如果我想從B訪問c3和C3,我想讓a2可見,我該怎麼去關於它。

+0

你有這方面的一個實施在java代碼?我認爲這是不可能的,因爲即使c的「包含」有一個id,你也無法抓住它們,因爲它們不是視圖(至少據我所知)。 – MikeIsrael

回答

3

您可以通過獲取每個視圖和子視圖的引用來訪問所有視圖,如下例所示。

 View view = findViewById(R.id.b); 
     view = view.findViewById(R.id.c1); 
     ((TextView)view.findViewById(R.id.txt1)).setText("Got the First one"); 

     view = findViewById(R.id.b); 
     view = view.findViewById(R.id.c1); 
     ((TextView)view.findViewById(R.id.txt2)).setText("Got the Second one"); 

     view = findViewById(R.id.b); 
     view = view.findViewById(R.id.c2); 
     ((TextView)view.findViewById(R.id.txt1)).setText("Got the forth one"); 

同樣,您也可以訪問其他元素。

0

我有一個嵌套的佈局結構類似於在問題中描述的,並沒有遇到問題獲取視圖嵌套從我的主視圖一個或兩個級別。我把我的活動的是a.xml,然後找到我需要從我的活動的直接意見內容視圖(而無需找到第二級的視圖第三級視圖),具體如下:

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.a); 
    ImageView a1 = (ImageView)findViewById(R.id.a1); 
}