我正在尝试为Android创建自定义布局。它通常在屏幕上绘制,但没有内部视图。仅绘制我的group_box.xml。我如何从我的自定义布局访问内部视图(带有id测试的TextView)或如何绘制它们?
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);
}
}
答案 0 :(得分:6)
您可以通过setter和getter访问元素。
将它放在GroupBox.java
中caption = (TextView) findViewById(R.id.caption);
public void setLabel(CharSequence text) {
caption.setText(text);
}
在xml中为控件添加一个id:
<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");