Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/195.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在android中设置自定义EditTextField属性?_Android - Fatal编程技术网

如何在android中设置自定义EditTextField属性?

如何在android中设置自定义EditTextField属性?,android,Android,我是android新手。有人能解决以下问题吗? 我只需要创建如下所示的类。我需要知道如何设置编辑文本字段的属性 public class CustomEditText extends EditText{ public CustomEditText(Context context) { super(context); // TODO Auto-generated constructor stub } } 注:我指的是像这样的物业 setText(“演示”); 提前感谢。 您需要

我是android新手。有人能解决以下问题吗? 我只需要创建如下所示的类。我需要知道如何设置编辑文本字段的属性

public class CustomEditText extends EditText{

public CustomEditText(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
}
}

注:我指的是像这样的物业 setText(“演示”); 提前感谢。


您需要在CustomEditText中创建成员变量和方法。

一旦你有了它们,你就可以访问它

因此,有几种方法可以解释这一点,我将尝试涵盖所有这些方法

EditText有多个构造函数。您已经覆盖的一个实例要求您作为开发人员在代码中为其余实例设置属性。因此,实际上您可以从这个类中调用setText(someString),或者因为该方法是公共的,所以可以直接在类的实例上调用它

如果重写包含attributeSet的构造函数

 EditText(Context, AttributeSet)
您可以将组件用作xml布局的一部分,并在其中设置属性,就像它是另一个EditText一样(只要您调用super(context,attributeSet)。如果您想在此基础上定义自己的自定义属性,那么这实际上是非常简洁的方法

在项目层次结构中,从根目录开始,您应该或需要在该文件夹中创建一个名为“res/values”的文件夹,并创建一个名为attr.xml的文件

<declare-styleable name="myCustomComponents">
<!-- Our Custom variable, optionally we can specify that it is of integer type -->
<attr name="myCustomAttribute" format="integer"/>
...
<!-- as many as you want -->
</declare-styleable>
现在我们已经声明了我们的新属性,并有了读取它的设置代码,我们实际上可以通过编程或在XML布局中使用它

<ViewGroup 
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:custom="http://schemas.android.com/apk/res/com.my.apk.package"
>

...

<com.my.full.apk.package.CustomEditText
   android:id="@+id/custom_edit"
   ...
   custom:myCustomAttribute="12"
/>
...
</ViewGroup>

...
...

因此,在本例中,我们创建了一个与普通布局类似的布局,但请注意,我们声明了一个新的xml命名空间。这是用于新组件和apk的。因此,在使用“自定义”的情况下,它将在定义的样式标签中查找新参数。通过使用attr.xml执行前面的步骤,您已经声明了“myCustomAttribute”作为命名空间之外的组件属性。之后,由您决定要公开哪些属性以及这些属性的实际含义。希望这会有所帮助。

为什么需要在
custom:myCustomAttribute
中使用
custom
之类的内容?我可以将其重命名为
xyz:custom:myCustomAttribute
<ViewGroup 
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:custom="http://schemas.android.com/apk/res/com.my.apk.package"
>

...

<com.my.full.apk.package.CustomEditText
   android:id="@+id/custom_edit"
   ...
   custom:myCustomAttribute="12"
/>
...
</ViewGroup>