我想在我的应用程序的HomeFragment中开发一个搜索功能,但它告诉我吐司不能工作。
这是我的片段:
/**
* A simple {@link Fragment} subclass.
*/
public class HomeFragment extends Fragment {
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
rootView.findViewById(R.id.btnSearch).setOnClickListener(new View.OnClickListener () {
@Override
public void onClick(View v) {
new SimpleSearchDialogCompat<>(HomeFragment.this, "Search...", "What are you looking for...?",
null, initData(), new SearchResultListener<Searchable>() {
@Override
public void onSelected(BaseSearchDialogCompat baseSearchDialogCompat, Searchable searchable, int i) {
Toast.makeText(HomeFragment.this, "" + searchable.getTitle(), Toast.LENGTH_SHORT).show();
baseSearchDialogCompat.dismiss();
}
}).show();
}
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_home, container, false);
});
return rootView;
}
private ArrayList<SearchModel> initData() {
ArrayList<SearchModel>items =new ArrayList<>();
items.add(new SearchModel("Captain America"));
items.add(new SearchModel("Wonder Women"));
items.add(new SearchModel("Batman"));
items.add(new SearchModel("Iron Man"));
items.add(new SearchModel("Hulk"));
return items;
}
}
我曾尝试过各种答案:
Toast.makeText(getActivity(),&#34;&#34; + searchable.getTitle(),Toast.LENGTH_SHORT).show();
和
Toast.makeText(getActivity()。getApplicationContext(),&#34;&#34; + searchable.getTitle(),Toast.LENGTH_SHORT).show();
和
Toast.makeText(HomeFragment.this.getActivity(),&#34;&#34; + searchable.getTitle(),Toast.LENGTH_SHORT).show();
但它仍然无法为我工作。
答案 0 :(得分:0)
请试试这个: -
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
rootView.findViewById(R.id.btnSearch).setOnClickListener(new View.OnClickListener () {
@Override
public void onClick(View v) {
new SimpleSearchDialogCompat<>(HomeFragment.this, "Search...", "What are you looking for...?",
null, initData(), new SearchResultListener<Searchable>() {
@Override
public void onSelected(BaseSearchDialogCompat baseSearchDialogCompat, Searchable searchable, int i) {
Toast.makeText(getActivity(), "" + searchable.getTitle(), Toast.LENGTH_SHORT).show();
baseSearchDialogCompat.dismiss();
}
}).show();
}
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_home, container, false);
});
return rootView;
}
我已从您的代码中删除了super.onCreate(savedInstanceState);
。您错误地将此代码放在onCreateView()
方法中。