如何检查对话框中的视图是否聚焦?

时间:2014-06-20 10:30:41

标签: android android-alertdialog

我有一个警告对话框,其中包含两个 SearchView 小部件,如下所示:

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <SearchView
        android:id="@+id/sourceSearchView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:iconifiedByDefault="false" >
    </SearchView>

    <SearchView
        android:id="@+id/destinationSearchView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:iconifiedByDefault="false">
    </SearchView>

</LinearLayout>

并在下面的代码中我夸大了这个布局以获得对话框:

LayoutInflater mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View mView = mInflater.inflate(R.layout.search_layout,null);

                mSourceSearchView = (SearchView)mView.findViewById(R.id.sourceSearchView);

                mDestinationSearchView = (SearchView)mView.findViewById(R.id.destinationSearchView);

                mSourceSearchView.setQuery(mCurrentLocation, false);


                mBuilder = new AlertDialog.Builder(new ContextThemeWrapper(mContext, 
                        android.R.style.Theme_DeviceDefault_Dialog));

                mBuilder.setView(mView);

                mAlertDialog = mBuilder.create();

                mAlertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

                mAlertDialog.setCancelable(false);

我的问题:如何检查一个搜索视图是否专注于其他搜索视图。 我试过这个,但它返回 null

mAlertDialog.getWindow().getCurrentFocus().isFocused()

1 个答案:

答案 0 :(得分:0)

您可以使用View.OnFocusChangeListener

mSourceSearchView.setOnFocusChangeListener(new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if(hasFocus){
            //do something
        }else{
            //something else
        }

    }
});

如果您不想使用侦听器,则可以使用

mSourceSearchView.isFocused();

docs。希望它有所帮助:)