EditText setOnFocusChangeListener on all EditTexts

别来无恙 提交于 2019-11-28 08:28:01
tyczj

Well, you could have your activity implement OnFocusChangeListener. That way, all your changes will be on that one metho,d but you will have to check which view changed focus by getting the view id with v.getId() and handle accordingly.

@Override
public void onFocusChange(View v, boolean hasFocus) {
    switch(v.getId()){
    case r.id.editText1:
    break;

    ...etc
    }
}

There's plenty of ways you could make this simpler. For one, how about abstracting this into a method and calling it for each TextView you want to add the event for:

private void setOnFocusChangeListener(TextView textView, String name){

    textView.setOnFocusChangeListener(new OnFocusChangeListener() {          
        public void onFocusChange(View v, boolean hasFocus) {
            if(!hasFocus) {
                saveThisItem(txtClientID.getText(), name, 
                             textView.getText());
            }
        }
    });
}

Then you can call this method for each of your TextView instances:

setOnFocusChangeListener(txtName, "name");
setOnFocusChangeListener(txtCompany, "company");
setOnFocusChangeListener(txtPosition, "position");

My suggestion would be to use a custom EditText to handle this for you:

public class SaveEditText extends EditText implements View.OnFocusChangeListener {
    private String mDataKey;
    private String mClient;

    public SaveEditText (Context context) {
        super(context);
        setOnFocusChangeListener(this);
    }

    public SaveEditText (Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnFocusChangeListener(this);
    }

    public void setDataKey (String dataKey) {
        mDataKey = dataKey;
    }

    public void setClient (String client) {
        mClient = client;
    }

    @Override
    public void onFocusChange (View v, boolean hasFocus) {
        saveThisItem(mClient, mDataKey, getText().toString());
    }
}

You might decide to handle the client and data keys differently, but the idea is that you use a custom base class that will handle it automatically.

Or even simpler

OnFocusChangeListener listener;

listener = new new OnFocusChangeListener() {          
    public void onFocusChange(View v, boolean hasFocus) {
...        }
    }
});

textbox1. setOnFocusChangeListener(listener);
textbox2. setOnFocusChangeListener(listener);
textbox3. setOnFocusChangeListener(listener);

Since onFocusChange(View v, boolean hasFocus) has the parameter View you can use that to tell which view called it

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