Creating and setting custom EditText attributes

自闭症网瘾萝莉.ら 提交于 2019-12-25 01:38:59

问题


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:


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.



来源:https://stackoverflow.com/questions/27230487/creating-and-setting-custom-edittext-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!