从片段中ListView的onItemClick开始Activity

Posted

技术标签:

【中文标题】从片段中ListView的onItemClick开始Activity【英文标题】:Start Activities from onItemClick of ListView in fragments 【发布时间】:2014-04-05 14:13:18 【问题描述】:

所以我有两个片段链接到显示 ListViews 的布局文件。 ListViews 在 xml 中定义,并具有来自字符串数组的条目。我想单击 ListView 中的项目并打开新活动。一个 ListView 中有 8 个项目,另一个中有 9 个项目。在 onItemClick 代码中,如何根据单击的项目创建启动活动的意图?我将为每个项目创建 1 个类作为其自己的活动。如何通过此代码的 onItemClick 方法中的意图启动类中的活动?

class CommunityFragment extends Fragment

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

        View view = inflater.inflate(R.layout.community_fragment, container, false);
        ListView lv = (ListView) view.findViewById(R.id.communityListView);
        lv.setOnItemClickListener(new OnItemClickListener()
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
                // TODO Auto-generated method stub

            
        );
        return view;
    

class ResourcesFragment extends Fragment
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

        View view = inflater.inflate(R.layout.resources_fragment, container, false);
        ListView lv = (ListView) view.findViewById(R.id.resourcesListView);

        lv.setOnItemClickListener(new OnItemClickListener() 

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
                // TODO Auto-generated method stub

            
        );
        return view;
    

【问题讨论】:

***.com/questions/7177633/… 看到这个.. 【参考方案1】:

像下面这样实现你的OnItemClickListener()

listview.setOnItemClickListener(new OnItemClickListener() 

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) 
            // TODO Auto-generated method stub

                    Intent intent = new Intent(getActivity(), nextactivity.class);
                    startActivity(intent);

        
    );

【讨论】:

【参考方案2】:

为每个项目创建 switch 语句,并相应地打开活动,如下所示:

   lv.setOnItemClickListener(new OnItemClickListener() 

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
            // TODO Auto-generated method stub
                     int itm=arg0.getItemAtPosition(arg2);
                switch (itm) 
                case 0:
                Toast.makeText(m_context, "Position Zero", Toast.LENGTH_SHORT).show();
                                 Intent intent = new Intent(getActivity(), FirstActivity.class);
                startActivity(intent);
                    break;
                case 1:
                  Intent intent1 = new Intent(getActivity(), SecondActivity.class);
                   startActivity(intent1);
                              break;
                case 2:
                          //..............................

        
    );

【讨论】:

@GrlsHu 这些指令序列有什么问题:lv.setOnItemClickListener(null); lv.setOnItemClickListener( new OnItemClickListerner()@Override onItemClick(...)...); 它不能工作。我虽然可以将事件注册到Listener @Stallman 通过写lv.setOnItemClickListener(null); 表示您尚未将列表视图注册给任何听众。您必须首先相应地实现一个侦听器,然后才能将其应用于查看。你不能传递空值。【参考方案3】:

在项目单击上,您将根据可以开始片段的位置获得位置

listView.setOnItemClickListener(new OnItemClickListener() 
  @Override
  public void onItemClick(AdapterView<?> parent, View view,
    int position, long id) 
    Toast.makeText(getApplicationContext(),
      "Click ListItem Number " + position, Toast.LENGTH_LONG)
      .show();
       switch(position) 
        case CONST_FRAGMENT_1 :
                  //Start fragment 1
            ...
            ...
       
  
);

【讨论】:

【参考方案4】:

一个通用解决方案可以是..

创建一个包含您要打开的活动的类名的项目数组.. 喜欢..

Class[] activityArray = new Class[numberOfItemsInListView];
            activityArray[0] = Activity1.class;

//添加所有类似的活动........

现在在 ListView onItemCLick 上:

lv.setOnItemClickListener(new OnItemClickListener() 

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view,
                int position, long arg3) 


                    Intent intent = new Intent(CommunityFragment.this.getActivity(), activityArray[postion]);
                    CommunityFragment.this.getActivity.startActivity(intent);

        
    );

【讨论】:

【参考方案5】:

使用它在 onItemClickListener 中启动下一个意图:

Intent intent = new Intent(getActivity(), nextactivity.class);
                    startActivity(intent);

【讨论】:

【参考方案6】:

我认为下面的代码对你有帮助。

public class PdfListViewFragment extends Fragment 
    ListView listView;
    Activity rootView;
    Activity context;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) 
        //returning our layout file
        //change R.layout.yourlayoutfilename for each of your fragments
        View rootView = inflater.inflate(R.layout.pdf_list_view, container, false);
        context = getActivity();
        // Get ListView object from xml
        listView = (ListView) rootView.findViewById(R.id.list);

        // Defined Array values to show in ListView
        String[] values = new String[]"android List View",
                "Adapter implementation",
                "Simple List View In Android",
                "Create List View Android",
                "Android Example",
                "List View Source Code",
                "List View Array Adapter",
                "Android Example List View"
        ;

        // Define a new Adapter
        // First parameter - Context
        // Second parameter - Layout for the row
        // Third parameter - ID of the TextView to which the data is written
        // Forth - the Array of data

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
                android.R.layout.simple_list_item_1, android.R.id.text1, values);


        // Assign adapter to ListView
        listView.setAdapter(adapter);

        // ListView Item Click Listener
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() 

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) 
                if (position == 0) 
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
                    startActivityForResult(myIntent, 0);
                

                if (position == 1) 
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
                    startActivityForResult(myIntent, 0);
                

                if (position == 2) 
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
                    startActivityForResult(myIntent, 0);
                

                if (position == 3) 
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
                    startActivityForResult(myIntent, 0);
                

                if (position == 4) 
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
                    startActivityForResult(myIntent, 0);
                

                if (position == 5) 
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
                    startActivityForResult(myIntent, 0);
                

                if (position == 6) 
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
                    startActivityForResult(myIntent, 0);
                

                if (position == 7) 
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
                    startActivityForResult(myIntent, 0);
                


                // ListView Clicked item index
                int itemPosition = position;

                // ListView Clicked item value
                String itemValue = (String) listView.getItemAtPosition(position);

                // Show Alert

                Toast.makeText(context.getApplicationContext(), "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG).show();

            

        );

        return rootView;
    

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) 
        super.onViewCreated(view, savedInstanceState);
        //you can set the title for your toolbar here for different fragments different titles
        getActivity().setTitle("XYZ");
    



【讨论】:

【参考方案7】:

如果您使用适配器来显示列表中的项目,区分以下内容很重要:

列表 AdapterView#getId() 的 ID 与列表 ArrayAdapter&lt;String&gt;#getId() 中的项目 ID 不同,因为列表的视图包含元素的视图。

假设您要启动具有用户角色的活动的示例。您必须针对您的特定情况进行转换。

public class SignInFragment extends Fragment implements AdapterView.OnItemClickListener 

    //TODO: Declare constants (GUEST, HOST, EMPLOYEE...)    

    private ArrayAdapter<String> userRolesAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) 
        View root = inflater.inflate(R.layout.fragment_sign_in, container, false);

//            ListView Instance
        ListView userRolesList = root.findViewById(R.id.user_roles_list);

        String[] userRoles = 
                GUEST,
                HOST,
                EMPLOYEE
        ;

//            Initialize the adapter
        userRolesAdapter = new ArrayAdapter<>(
                getActivity(),
                android.R.layout.simple_list_item_1,
                userRoles
        );

//            Link to the list with the adapter. This reference starts the process of filling the list.
        userRolesList.setAdapter(userRolesAdapter);

//            Events
        userRolesList.setOnItemClickListener(this);

        return root;
    

    /**
     * @param adapterView: View using the adapter from the list
     * @param view: View of the item that has been pressed
     * @param i: Refers to the position of the item that the adapter handles
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) 
        if (adapterView.getId() == R.id.user_roles_list) 

//              Obtain the item pressed on the adapter with the entry position
            String currentUserRol = userRolesAdapter.getItem(i);

            assert currentUserRol != null;
            switch (currentUserRol) 
                case GUEST:
                    startActivity(Host.class);
                    break;
                case HOST:
                    startActivity(Host.class);
                    break;
                case EMPLOYEE:
                    startActivity(Employee.class);
                    break;
                default:
                    Log.d("Error", "The activity passed as an argument to startActivity() does not exist");
                    break;
            
        
    

    /**
     * PRECONDITION: The class given as an argument exists.
     */
    public void startActivity(Class<?> cls) 
        Intent intent = new Intent(getActivity(), cls);
        startActivity(intent);
    
    

最好的:)

【讨论】:

以上是关于从片段中ListView的onItemClick开始Activity的主要内容,如果未能解决你的问题,请参考以下文章

Android ListView 在 onItemClick 之后修改

OnItemClick 如何从列表视图中获取单击项目的文本值

如何基于 JSON 对象构建 ListView 并在 onItemClick 之后传递其数据

在片段中与 onItemClick 斗争

OnItemClick 永远不会被调用 ListView 中的按钮

在片段中使用 onItemClick 占据位置