2010-10-21 35 views
1

我是新来android.can任何人解决以下问题? 我只需要创建一个类象下面这样。我需要知道如何设置属性为编辑文本字段如何在android中设置自定义EditTextField属性?

public class CustomEditText extends EditText{ 

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

}

注:我的意思是这样的 Edittext.setText(“演示”属性); 在此先感谢。

回答

2

所以有一些方法可以解释,我会尽力涵盖所有这些方法。

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

如果覆盖包含一个属性集中的构造,

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> 

现在在使用AttributeSet的新构造函数中,可以读取此新属性“myCustomAttribute”。

public CustomEditText(Context context, AttributeSet set) { 
    super(context, set); 
    // This parses the attributeSet and filters out to the stuff we care about 
    TypedArray typedArray = context.obtainStyledAttributes(R.stylable.myCustomComponents); 
    // Now we read let's say an int into our custom member variable. 
    int attr = typedArray.getInt(R.styleable.myCustomComponents_myCustomAttribute, 0); 
    // Make a public mutator so that others can set this attribute programatically 
    setCustomAttribute(attr); 
    // Remember to recycle the TypedArray (saved memory) 
    typedArray.recycle(); 
} 

既然我们已经宣布我们的新属性,并有安装程序代码读它,我们实际上可以使用它编程或XML布局。所以我们可以说你在文件中的XML布局,layout.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”声明为http://schemas.android.com/apk/res/com.my.apk.package名称空间之外的组件属性。之后,由您来决定您想要公开的属性以及这些属性的实际含义。希望有所帮助。

+0

为什么你需要像'custom:myCustomAttribute'中那样使用'custom'?我可以重命名这个像'xyz:custom:myCustomAttribute'吗? – mrid 2017-11-04 07:54:31

2


您需要在CustomEditText中创建成员变量和方法。
一旦你有他们,你可以访问它。

相关问题