如何将一个方法从活动调用到片段android

时间:2016-03-17 17:41:49

标签: android sqlite android-studio

我正在尝试从changelistner调用此片段,我最近将活动SearchBar更改为片段。它给出了错误的Inconvertible类型。

 public class CustomAutoCompleteTextChangedListener  implements TextWatcher {

public static final String TAG = "CustomAutoCompleteTextChangedListener.java";
Context context;

public CustomAutoCompleteTextChangedListener(Context context){
    this.context = context;
}

@Override
public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
                              int after) {
    // TODO Auto-generated method stub

}

@Override
public void onTextChanged(CharSequence userInput, int start, int before, int count) {

    // if you want to see in the logcat what the user types
    Log.e(TAG, "User input: " + userInput);


    SearchBar mainActivity = ((SearchBar) context);

    // query the database based on the user input
    mainActivity.item = mainActivity.getItemsFromDb(userInput.toString());

    // update the adapater
    mainActivity.myAdapter.notifyDataSetChanged();
    mainActivity.myAdapter = new ArrayAdapter<String>(mainActivity, android.R.layout.simple_dropdown_item_1line, mainActivity.item);
    mainActivity.myAutoComplete.setAdapter(mainActivity.myAdapter);

}

}

这是在线上给出错误 SearchBar mainActivity =((SearchBar)context);

1 个答案:

答案 0 :(得分:0)

由于现在SearchBar是一个片段,因此无法按照您的方式访问它。你必须使用标签名称 -

找到它
 SearchBar frag = (SearchBar) getSupportFragmentManager().findFragmentByTag(<tag_name>);
 if (profileDetailsFragment != null && frag.isAdded()) {
            frag.getItemsFromDb(userInput.toString());
 }

<tag_name>将是您用于实例化片段的标记的名称。