@Override
protected void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.activity_filter);
etColor1 = (EditText) findViewById(R.id.etColor1);
etColor1.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
etColor1.setEnabled(false);
}
});
btnEdit1 = (Button) findViewById(R.id.btnEdit1);
btnEdit1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
etColor1.setEnabled(true);
etColor1.requestFocus();
}
});
etColor2 = (EditText) findViewById(R.id.etColor2);
etColor2.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
etColor2.setEnabled(false);
}
});
btnEdit2 = (Button) findViewById(R.id.btnEdit2);
btnEdit2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
etColor2.setEnabled(true);
etColor2.requestFocus();
}
});
etColor3 = (EditText) findViewById(R.id.etColor3);
etColor3.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
etColor3.setEnabled(false);
}
});
btnEdit3 = (Button) findViewById(R.id.btnEdit3);
btnEdit3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
etColor3.setEnabled(true);
etColor3.requestFocus();
}
});
你好!所以我有这个代码检测Focus for EditText。最初,所有EditTexts都被禁用,然后当我点击'编辑'它旁边的按钮,它将被聚焦(其他EditTexts仍然禁用),然后当我点击其他'编辑'按钮,我已经点击的EditText将再次被禁用。
代码完成了我想要的,但我相信它可以缩短。对不起,对于新问题。感谢大家!
答案 0 :(得分:1)
正如@Stephan所提到的,您可以利用在回调中为您提供设置监听器的视图这一事实。只需让您的Activity实现这些接口,您可以简化这一点:
public class MyActivity extends Activity implements
View.OnFocusChangeListener, View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.activity_filter);
int[] editTexts = new int[] { R.id.etColor1, R.id.etColor2, R.id.etColor3 };
for (int editText : editTexts) {
findViewById(editText).setOnFocusChangeListener(this);
}
int[] buttons = new int[] { R.id.btnEdit1, R.id.btnEdit2, R.id.btnEdit3 };
for (int button : buttons) {
findViewById(button).setOnClickListener(this);
}
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
v.setEnabled(false);
}
@Override
public void onClick(View v) {
v.setEnabled(true);
v.requestFocus();
}
}