2015-06-07 73 views
0

我設計了一個RelativeLayout,其中包含兒童元素,如TextViewImageView。我想要做的是從XML中創建的RelativeLayout對象中創建RelativeLayout對象,這樣我就可以訪問其子元素並對其進行修改(從ImageView更改圖像並將文本從TextView更改)。我怎樣才能做到這一點?它會是這樣的。訪問Java文件中的Android視圖

RelativeLayout lay = new "myrelativelayout"; 
ImageView img = lay.children[0]; 
TextView txt = lay.children[1]; 

謝謝!

回答

1

XML:

<RelativeLayout 
    android:id="@+id/relative_layout_id" 
     ...> 
    <TextView 
     android:id="@+id/textview_id" 
     .../> 
</RelativeLayout> 

活動的onCreate:

RelativeLayout lay = (RelativeLayout) findViewById(R.id.relative_layout_id); 

要改變孩子使用:

TextView child = (TextView) findViewById(R.id.textview_id); 
child.setText(text); 

或:

View child = lay.getChildAt(i); 
+0

很好的答案。我不得不使用「inflater」,因爲我的RelativeLayout在「佈局」文件夾中,而不是「可繪製的」文件夾中。謝謝! – ProtectedVoid

0

要訪問佈局,我們使用findViewById方法。因此,要更改ImageView中的圖像,您並不需要訪問RelativeLayout

我們通過它的id訪問任何元件的方法是如下:

View v = (View)findViewById(R.id.view_id); 

其中view_id是視圖的ID。

要訪問RelativeLayout,因此,這段代碼是:

RelativeLayout lay = (RelativeLayout) findViewById(R.id.relative_layout_id); 

但是如果你只想要更改TextView文本,你真的不需要上面的代碼。

TextView textView = (TextView) findViewById(R.id.id_of_textview); 
textView.setText(text); 

訪問任何資源的方法,一般可以發現here:如果你這樣做了TextView一個類似的訪問就足夠了。