android - 基于现有布局的自定义布局

标签 android android-layout custom-controls

我正在尝试为 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/

相关文章:

c# - 字体导致自定义控件中的 GDI 泄漏

c# - 使用自定义绘制的控件滚动面板

java - 使缓存失效并重新启动并不能修复 BR 导入错误...数据绑定(bind)问题

java - 关于 Activity 回调中的@override 注解

android - 如何在自定义适配器中更改可绘制形状的背景颜色

android - Roboguice 应用程序 @InjectView

java - 安卓 : implementing complex ArrayAdapter item with ability switch the views inside the row

安卓自定义设置

Android - 选项卡作为 Activity 的一部分

java - WebDriverException : It is impossible to create a new session because 'createSession' which takes HttpClient, InputStream 和 long 未找到