labatyo
labatyo

Reputation: 486

Android - how to use a custom TextView?

I created a class that extends TextView

public class EmployeeTextView extends TextView {

    private String employeeId;

    private String employeeName;

    public EmployeeTextView( Context context, String employeeId,
            String employeeName ) {
        super( context );
        this.employeeId = employeeId;
        this.employeeName = employeeName;
    }

    public String getEmployeeId( ) {
        return employeeId;
    }

    public void setEmployeeId( String employeeId ) {
        this.employeeId = employeeId;
    }

    public String getEmployeeName( ) {
        return employeeName;
    }

    public void setEmployeeName( String employeeName ) {
        this.employeeName = employeeName;
    }

    @Override
    public CharSequence getText( ) {
        return this.employeeId + " - " + this.employeeName;
    }

}

How would I implement this class in my main activity? Do I have to create these "EmployeeTextView"s programmatically? Or is there a way to create a custom widget and add it via XML, then call my getter and setter on it?

The reason I need this custom TextView is that I need to get the employeeId or employeeName individually.

Thanks

Upvotes: 0

Views: 84

Answers (3)

Stefan de Bruijn
Stefan de Bruijn

Reputation: 6319

Use it as you would normally with a TextView, also within the XML. Just add your package name before it.

Upvotes: 1

drdrej
drdrej

Reputation: 908

Use the full qualified name in your layout.xml.

In your case:

<com.example.EmployeeTextView ... />

Upvotes: 1

stinepike
stinepike

Reputation: 54682

in layout.xml add like following

<your_package_name.EmployeeTextView 
      android:id="@+id/view_id"
      other attributes
/>

here your_package_name is the src package of the class EmployeeTextView

in class cast using

EmployeeTextView v = (EmployeeTextView ) findViewById(R.id.view_id);

Upvotes: 3

Related Questions