<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foreground="@drawable/window_foreground">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="@dimen/appbar_resting"
android:theme="@style/AppTheme.NoActionBar">
<com.ujjwal.univhub.components.SearchView
android:id="@+id/search_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/fragment_university_lsit"></include>
</FrameLayout>
app_bar_main.xml searchViewをホストするView.getContextをキャストすることはできませんcustomFrameLayout.Iが私の主な活動のxmlファイルにこのXMLファイルを使用しています。
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<include
layout="@layout/floating_action_group"/>
</FrameLayout>
これは私のMainActivityでactivity_main.xml
public class SearchView extends FrameLayout implements AdapterView.OnItemClickListener{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SuggestionAdapter.ViewHolder viewHolder = (SuggestionAdapter.ViewHolder)view.getTag();
University selectedUniversity = viewHolder.getUniversity();
String sendData = FilterBuilder.createCodeFilter(selectedUniversity.getCode()).toJson();
//may occure error here
Log.d("serach by name", "onItemClick: error");
KeyListener listener = new KeyListener((BaseActivity)getContext());//error thrown here.
listener.onClicked(sendData, Properties.LOCALHOST + Properties.UNIVERSITY_CODE);
queryInput.setText(selectedUniversity.getName());
suggestionAdapter.clear();
suggestionAdapter.notifyDataSetChanged();
}
}
setContentView(R.layout.activity_main);
java.lang.ClassCastExceptionがある:android.view.ContextThemeWrapperは、COMにキャストすることはできません.ujjwal.univhub.BaseActivity
ビューをホストしているアクティビティにコンテキストをキャストできません。
これは、基本操作のコールバックではなく、そのビュー上にあります。 BaseActivityでコールバックを実装していれば、BaseActivityを得るためにキャストする必要はありません。単に「this」キーワードで取得できます。 XMLファイルから作成したビューは、それをホストするアクティビティにキャストできます。ほとんどすべてのキャストは成功です。しかし、これで私はここに何があるのか分からない。 –
はい、私はあなたのことを知っています。「BaseActivityを得るためには、まったくキャストする必要はありません。」_これは、私があなたのコードをどんな意味で作ることができるかに基づいて最初に提案した理由です。とにかく、ビューから取得した 'Context'を' Activity'にキャストすることは、あなたが見たように安全なコードではありません。私が話していたメソッドは 'KeyListener'オブジェクトの' onClicked() 'でした。なぜなら何らかの理由で' BaseActivity'インスタンス(あなたがコンストラクタで渡したように)が必要なので、私の推論です。 – bitbybit
キャストに依存しないようにコードを変更する必要があるようです(どうして必要なのでしょうか?)、またはあなたの 'SearchView'コンストラクタにスタックトレースを記録し、' LayoutInflater'があなたのために使った 'context'ビュー。 – bitbybit