EditText 获取焦点的方法为:setOnFocusChangeListener
下面写一个EditText 编辑框获取焦点之后改变背景颜色
主要代码如下
public class MainActivity extends AppCompatActivity {private EditText editText;private LinearLayout linearLayout;@Overrideprotected 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() {@Overridepublic 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="/apk/res/android"xmlns:tools="/tools"android:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"><EditTextandroid:id="@+id/edt"android:layout_width="match_parent"android:layout_height="100dp"android:hint="点击编辑框获取焦点改变背景颜色" /></LinearLayout>