EditText 获取焦点的方法为:setOnFocusChangeListener
下面写一个EditText 编辑框获取焦点之后改变背景颜色
主要代码如下
public class MainActivity extends AppCompatActivity {
private EditText editText;
private LinearLayout linearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.edt);
linearLayout = findViewById(R.id.main);
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
linearLayout.setBackgroundColor(Color.RED);
} else {
linearLayout.setBackgroundColor(Color.WHITE);
}
}
});
}
}
xml 中代码就写了一个编辑框如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/edt"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="点击编辑框获取焦点改变背景颜色" />
</LinearLayout>