2011-04-21 84 views
3

我正在嘗試爲android創建自定義佈局。它通常在屏幕上繪製,但沒有內部視圖。僅繪製我的group_box.xml。我如何從我的自定義佈局訪問內部視圖(TextView與ID測試)或如何繪製它們?基於已有佈局的自定義佈局

main.xml中

<my.example.GroupBox 
      android:layout_width="match_parent" 
      android:layout_height="40sp"> 
     <TextView android:text="TEST" 
        android:id="@+id/test" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"/> 
    </my.example.GroupBox> 

group_box.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       style="@style/groupbox"> 
    <LinearLayout style="@style/groupboxContent" 
        android:id="@+id/content" 
        android:layout_height="match_parent" 
        android:layout_width="match_parent"/> 
    <TextView style="@style/groupboxLabel" 
       android:id="@+id/caption" 
       android:text="@string/visit"/> 
</RelativeLayout> 

GroupBox.java

public class GroupBox extends LinearLayout { 

    public GroupBox(Context context) { 
     super(context); 
     LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View view = layoutInflater.inflate(R.layout.group_box, this); 
    } 

    public GroupBox(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View view = layoutInflater.inflate(R.layout.group_box, this); 
    } 
} 

回答

6

,您可以訪問通過getter和setter方法的元素。

把這個在您的GroupBox.java

caption = (TextView) findViewById(R.id.caption); 

public void setLabel(CharSequence text) { 
     caption.setText(text); 
    } 

添加ID到您控制的xml:

<my.example.GroupBox 
      android:layout_width="match_parent" 
      android:layout_height="40sp" 
android:id="mycontrol"> 
     <TextView android:text="TEST" 
        android:id="@+id/test" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"/> 
    </my.example.GroupBox> 

然後找到在主要活動的控制和做到這一點:

yourcontrol = (GroupBox) findViewById(R.id.mycontrol) 

yourcontrol.setLabel("test"); 
+0

你不完全理解我。我想在內使用id test中的 TextView設置視圖到LinearLayout中,並在group_box.xml中使用id內容,並且希望通過xml而不是像代碼中的代碼那樣通過標題來完成。謝謝 – 2011-04-21 07:58:10

+1

確定sry。您不能將此視圖放在中,並在GroupBox類中訪問它。您只能從視圖或者使main.xml膨脹的活動訪問。想一想:您可以將添加到其他佈局。如果您在GroupBox中訪問您未添加到XML的視圖,您將得到NullPointerException。 – passsy 2011-04-21 08:02:31

+0

但Android如何在LinearLayout或其他佈局中執行此操作? – 2011-04-21 08:05:14