我在标签活动中的标签中有一个列表视图。假设活动的名称为“主要”。我想要它,所以当我在列表视图中(在选项卡中,在活动中)按一个项目时,它会刷新“主要”(总体活动)。
答案 0 :(得分:1)
将 onItemClickListener()用于您的列表视图,如下所示。
在以下示例中,单击“项目1”时,MainActivity将重新启动。
ListView listView=findViewById(R.id.list_view);
List<String> mList= Arrays.asList("Item 1","Item 2","Item 3");
listView.setAdapter(new ListViewAdapter(this,R.layout.list_item_layout,mList));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Restart activity when Item 1 gets clicked
if("Item 1".equals(parent.getAdapter().getItem(position).toString())){
startActivity(new Intent(MainActivity.this,MainActivity.class));
finish();
}
}
});
示例:ListViewAdapter.class
public class ListViewAdapter extends ArrayAdapter<String> {
private List<String> mList;
public ListViewAdapter(@NonNull Context context, int resource, @NonNull List<String> list) {
super(context, resource, list);
this.mList = list;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_layout,parent,false);
}
((TextView) convertView.findViewById(R.id.tv_item)).setText(getItem(position));
return convertView;
}
@Nullable
@Override
public String getItem(int position) {
return mList.get(position);
}
}
考虑到您在选项卡式活动中使用FragmentPagerAdapter, 您可以将ListView的代码放在相应片段实例的 onCreateView()中,
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView listView=rootView.findViewById(R.id.list_view);
List<String> mList= Arrays.asList("Item 1","Item 2","Item 3");
listView.setAdapter(new ListViewAdapter(rootView.getContext(),R.layout.list_item_layout,mList));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Restart activity when Item 1 gets clicked
if("Item 1".equals(parent.getAdapter().getItem(position).toString())){
if(getActivity()!=null){
startActivity(new Intent(getActivity(),MainActivity.class));
getActivity().finish();
}
}
}
});
return rootView;
}
}