【发布时间】:2021-06-15 15:25:55
【问题描述】:
tried to solve a similar question to mine, but I failed.
在activity中运行的代码不在fragment中运行。我试图通过参考stackoverflow中的文章来解决它,但是失败了请教我方法。到底是什么问题?
片段
public class Fragment_Result extends Fragment {
EditText et_search;
ListView lv_search;
public Fragment_Result() {
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.result_fragment, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1);
lv_search = (ListView) view.findViewById(R.id.lv_search);
lv_search.setAdapter(adapter);
adapter.add("Adam Smith");
adapter.add("Bryan Adams");
adapter.add("Chris Martin");
adapter.add("Daniel Craig");
adapter.add("Eric Clapton");
adapter.add("Frank Sinatra");
et_search = (EditText) view.findViewById(R.id.et_search);
et_search.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable edit) {
String filterText = edit.toString();
if (filterText.length() > 0) {
lv_search.setFilterText(filterText);
} else {
lv_search.clearTextFilter();
}
((ArrayAdapter) lv_search.getAdapter()).getFilter().filter(filterText);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
}
}
fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_marginTop="60dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="23sp"
android:layout_marginLeft="25dp"
android:layout_marginRight="8dp"
android:id="@+id/tv_search"
android:text="search : " />
<EditText
android:layout_marginTop="60dp"
android:layout_marginRight="25dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/tv_search"
android:id="@+id/et_search"/>
<ListView
android:layout_marginTop="60dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/et_search"
android:textFilterEnabled="true"
android:id="@+id/lv_search"/>
</RelativeLayout>
在活动和分片中使用的代码只有一部分不同。
活动列表视图:ArrayAdapter 适配器 = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
片段列表视图:最终的 ArrayAdapter 适配器 = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1);
【问题讨论】:
标签: android listview android-fragments