我正在尝试为 android 创建自定义布局。它通常在屏幕上绘制,但没有内部 View 。只绘制我的 group_box.xml。我如何从我的自定义布局访问内部 View (带有 id 测试的 TextView)或如何绘制它们?
主.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>
组框.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);
}
}
最佳答案
您可以通过 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>
然后在主要 Activity 中找到您的控件并执行此操作:
yourcontrol = (GroupBox) findViewById(R.id.mycontrol)
yourcontrol.setLabel("test");
关于android - 基于现有布局的自定义布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5740989/