从片段中的ListView的onItemClick启动活动

时间:2014-03-04 07:12:37

标签: android listview android-intent android-listview android-fragments

所以我有两个片段链接到显示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;
    }
}

7 个答案:

答案 0 :(得分:2)

实施您的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);

        }
    });

答案 1 :(得分:1)

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

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
            ...
            ...
       }
  }
});

答案 2 :(得分:1)

为每个项目创建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:
                          //..............................

        }
    });

答案 3 :(得分:0)

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

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

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);

        }
    });

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

我认为以下代码可以帮助您。

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");
    }


}

答案 6 :(得分:0)

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

列表AdapterView#getId()的ID与列表ArrayAdapter<String>#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);
    }
}    

最佳:)