无法从setOnClickListener中的片段启动活动

时间:2018-01-20 12:43:54

标签: android android-fragments

我想从片段中的列表视图项开始一个新活动。但这不起作用。这是代码:

public class SettingsF extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View root = (ViewGroup) inflater.inflate(R.layout.fragment_settings, container, false);
    String[] menuitems = {"Context Setup", "Set-Up Custom Texts"};
    ListView listView = (ListView) root.findViewById(R.id.listview_settings);
    ArrayAdapter<String> listViewAdapter = new ArrayAdapter<String>(getActivity(),
                                                                    android.R.layout.simple_list_item_1, menuitems);
    listView.setAdapter(listViewAdapter);

    listView.setOnClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (position == 1){
                Intent intent;
                intent = new Intent(getActivity(), contactselect.class);
                startActivity(intent);
            }


        }
    });
    return root;
}

2 个答案:

答案 0 :(得分:1)

如果要在ListView上使用事件侦听器,则可以使用listview.setOnItemClickListener(new AdapetView)。这个(setOnClickListener)监听器无法在listview上工作。

Listview包含多个数据。

答案 1 :(得分:0)

如果要在单击的项目上打开活动,请尝试此操作:

listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {

                // your code
            }

        });