在单击项目时,使用listview中的intent打开不同的Fragment

时间:2018-03-15 15:12:55

标签: java android listview android-fragments

我使用下面的代码用包含Listview的Fragment填充我的主要活动。我正在关注http://wptrafficanalyzer.in/blog/android-itemclicklistener-for-a-listview-with-images-and-text/的教程。

我想知道,当每个项目点击Listview时,如何使用意图打开单独的活动/片段。

例如,当单击第一个项目时,它将打开一个片段,当单击第二个项目时,它将打开B片段。

package com.nepalpolice.cdp;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by Sagar on 2017/09/23.
 */


public class club extends Fragment  {
    // Array of strings storing country names
    String[] countries = new String[]{
            "India",
            "Pakistan",
            "Sri Lanka",
            "China",
            "Bangladesh",
            "Nepal",
            "Afghanistan",
            "North Korea",
            "South Korea",
            "Japan"
    };

    // Array of integers points to images stored in /res/drawable-ldpi/
    int[] flags = new int[]{
            R.drawable.eka,
            R.drawable.kat,
            R.drawable.rat,
            R.drawable.set,
            R.drawable.ann,
            R.drawable.kar,
            R.drawable.suk,
            R.drawable.sap,
            R.drawable.him,
            R.drawable.gor
    };

    // Array of strings to store currencies
    String[] currency = new String[]{
            "Indian Rupee",
            "Pakistani Rupee",
            "Sri Lankan Rupee",
            "Renminbi",
            "Bangladeshi Taka",
            "Nepalese Rupee",
            "Afghani",
            "North Korean Won",
            "South Korean Won",
            "Japanese Yen"
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_club, container, false);
// Each row in the list stores country name, currency and flag
        List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();

        for (int i = 0; i < 10; i++) {
            HashMap<String, String> hm = new HashMap<String, String>();
            hm.put("txt", "Country : " + countries[i]);
            hm.put("cur", "Currency : " + currency[i]);
            hm.put("flag", Integer.toString(flags[i]));
            aList.add(hm);
        }

        // Keys used in Hashmap
        String[] from = {"flag", "txt", "cur"};

        // Ids of views in listview_layout
        int[] to = {R.id.flag, R.id.txt, R.id.cur};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getActivity(), aList, R.layout.listview_layout, from, to);

        // Getting a reference to listview of main.xml layout file
        ListView listView = (ListView) view.findViewById(R.id.listview);

        // Setting the adapter to the listView
        listView.setAdapter(adapter);
        return view;
    }

    // Item Click Listener for the listview
    AdapterView.OnItemClickListener itemClickListener = new

            AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View container, int position, long id) {

                    if(position == 1/*or any other position*/){
                        Fragment fragment = new notices();
                        FragmentManager fragmentManager = getFragmentManager();
                        fragmentManager.beginTransaction().replace(R.id.fragment_frame, fragment).addToBackStack(null).commit();
                    }
                    else if(position == 2){


                    } // etc...

                }
            };
}

enter image description here

2 个答案:

答案 0 :(得分:1)

onItemClick内,只需拨打ifswitch即可调用您的活动

// Item Click Listener for the listview
AdapterView.OnItemClickListener itemClickListener = new 

AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
           Intent intent;

           if(position == 1/*or any other position*/){
               intent = new Intent(YourActivity.this,OtherActivity1.class); // YourActivity is the activity containing this code, if this line causes problems, use context value here
           }
           else if(position == 2){
               intent = new Intent(YourActivity.this,OtherActivity2.class);
           } // etc...

           // create intent to activity and call it


           startActivity(intent);
        }
    };

或者如果你想用不同的参数开始相同的活动(我通常用listView做),试试这个:(如果你的列表很长,我强烈推荐你这个,你的所有活动都会相似)

// Item Click Listener for the listview
AdapterView.OnItemClickListener itemClickListener = new 

AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
           Intent intent;

           intent = new Intent(YourActivity.this,SomeActivity.class);

           intent.putExtra("some_key",((TextView)container).getText.toString()); // if your container is not TextView, for example custom layout, you'll need to change this line a bit to fit your needs

           // instead of calling different activities, all one activity
           // but with different parameters. 

           startActivity(intent);
        }
    };

修改

你写了#34;我对android&#34;全新。那时我想给你一些建议 如果您有列表视图,并且想要在用户单击某个项目时执行操作,并且每个项目的操作略有不同(例如国家/地区列表,并且单击将查看有关该国家/地区的信息,则所有操作都是相同的,查看信息),
然后使用一个活动,并使用其他参数(Intent's extras)调用它们 如果为每个列表项创建单独的活动(如果列表很长),那么就像为每个用户创建SQL表一样糟糕(你知道SQL吗?)。

希望它有所帮助。如果您对代码有任何问题,或者您有什么不清楚的地方,请告诉我。

编辑2

如果你有新的意图(YourActivity.this / here /,[...])

尝试将上下文变量传递给您的片段并使用它代替YourActivity.this

//in you Activity class

final Activity a_this = this;

然后您需要将a_this传递给您的片段,并使用它代替YourActivity.this

intent = new Intent(a_this, SomeActivity.class);

如果您的片段嵌套在您的活动中,将a_this传递给片段就没有问题。

答案 1 :(得分:0)

这是工作解决方案,

我添加了

 listView.setOnItemClickListener(itemClickListener);

以上return view;

完整的代码是

&#13;
&#13;
package com.nepalpolice.cdp;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by Sagar on 2017/09/23.
 */


public class club extends Fragment  {
    // Array of strings storing country names
    String[] countries = new String[]{
            "India",
            "Pakistan",
            "Sri Lanka",
            "China",
            "Bangladesh",
            "Nepal",
            "Afghanistan",
            "North Korea",
            "South Korea",
            "Japan"
    };

    // Array of integers points to images stored in /res/drawable-ldpi/
    int[] flags = new int[]{
            R.drawable.eka,
            R.drawable.kat,
            R.drawable.rat,
            R.drawable.set,
            R.drawable.ann,
            R.drawable.kar,
            R.drawable.suk,
            R.drawable.sap,
            R.drawable.him,
            R.drawable.gor
    };

    // Array of strings to store currencies
    String[] currency = new String[]{
            "Indian Rupee",
            "Pakistani Rupee",
            "Sri Lankan Rupee",
            "Renminbi",
            "Bangladeshi Taka",
            "Nepalese Rupee",
            "Afghani",
            "North Korean Won",
            "South Korean Won",
            "Japanese Yen"
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_club, container, false);
// Each row in the list stores country name, currency and flag
        List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();

        for (int i = 0; i < 10; i++) {
            HashMap<String, String> hm = new HashMap<String, String>();
            hm.put("txt", "Country : " + countries[i]);
            hm.put("cur", "Currency : " + currency[i]);
            hm.put("flag", Integer.toString(flags[i]));
            aList.add(hm);
        }

        // Keys used in Hashmap
        String[] from = {"flag", "txt", "cur"};

        // Ids of views in listview_layout
        int[] to = {R.id.flag, R.id.txt, R.id.cur};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getActivity(), aList, R.layout.listview_layout, from, to);
        // Getting a reference to listview of main.xml layout file
        ListView listView = (ListView) view.findViewById(R.id.listview);
        // Setting the adapter to the listView
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(itemClickListener);
        return view;
    }

// Setting the adapter to the listView


    // Item Click Listener for the listview
    OnItemClickListener itemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
            // Getting the Container Layout of the ListView
            if(position == 1/*or any other position*/){
                Fragment fragment = new notices();
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.fragment_frame, fragment).addToBackStack(null).commit();
            }
            else if(position == 2){


            } // etc...
        }
    };
}
&#13;
&#13;
&#13;