Creating and setting custom EditText attributes

2019-09-17 14:28发布

I would like to add a custom property to a group of EditTexts that are created programmatically. I have three different sensors set up via an Arduino, and I would like this custom attribute to be used by the app to dictate which sensor to read from.

Is there a way to create a custom attribute so that I can declare the setting like editTextX.setSensorType(0)?

Here is the code that I'd be using this with:

if (check for certain j value) {
  rowjlabel.setText(" %");

  // read from tilt sensor, or "dimensionj.setSensorType(tilt);"
} else if (check for other j value) {
  rowjlabel.setText(" in.");

  // read from height sensor, or "dimensionj.setSensorType(height);"
} else {
  rowjlabel.setText(" in.");

  //read from distance sensor, or "dimensionj.setSensorType(distance);"
}

1条回答
男人必须洒脱
2楼-- · 2019-09-17 14:57

Sure, you can subclass EditText and add any fields or methods you need. Something like this (note, you will need a bit more code than this, like a constructor):

public class MyEditText extends EditText {

    ...

    private int mSensorType;

    public void setSensorType(int type){
        mSensorType = type;
    }

    public int getSensorType(){
        return mSensorType;
    }
}

Then you just have to use that class in place of EditText in your application.

查看更多
登录 后发表回答