当选择或扫描标签如何发送数据? [英] how to to send data when tab is selected or swipe?

查看:209
本文介绍了当选择或扫描标签如何发送数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做的标签来看一个简单的例子使用。我想送从一个片段发送数据到另一个片段,当用户使用Tab键片段和传呼机。我会给你更多的细节我有一个标签一个列表视图。在我需要一个数组列表中显示的列表中view.I数据要发送在另一个片段列表视图。所以,我做一个接口,并实现它的主要活动。但我不知道如何发送到发送的事件片段。当用户选择选项卡我想送数组列表,第二个片段

I make a simple example of tab view using fragment and pager .I want to send to send data from one fragment to another fragment when user use tab button. I will give you more detail I have one list view in one tab . In that i take one array list to display the data in list view.I want to send that list view in another fragment . So I make one interface and implement it on main activity .But I don’t know how to send on which event to send fragment .when user select tab I want to send array list to second fragment

这是我的code mainActivity

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
    ViewPager viewPager;
    FragmentpagerAdapter fragmentpagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ActionBar actionBar =getActionBar();
        viewPager = (ViewPager) findViewById(R.id.pager);
        fragmentpagerAdapter =new FragmentpagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(fragmentpagerAdapter);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionBar.addTab(actionBar.newTab().setText("Stations").setTabListener(this));
        actionBar.addTab(actionBar.newTab().setText("fav Station").setTabListener(this));

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                actionBar.setSelectedNavigationItem(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

    }


    @Override
    public void onTabSelected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {

        Fragmentone fragmentOne = (Fragmentone) getSupportFragmentManager().findFragmentByTag(makeFragmentName(R.id.pager,0));
// get your arraylist using method of FragmentOne
        ArrayList<DataModel> yourArrayList = fragmentOne.getData();

        // refer your second fragment and set the above arraylist in that
        FragmentTwo fragmentTwo = (FragmentTwo) getSupportFragmentManager().findFragmentByTag(makeFragmentName(R.id.pager, 1));
        fragmentTwo.setData(yourArrayList);
        viewPager.setCurrentItem(tab.getPosition());

    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {

    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {

    }
    private static String makeFragmentName(int viewPagerId, int index) {
        return "android:switcher:" + viewPagerId + ":" + index;
    }

}

fragmentone

public class Fragmentone  extends Fragment {

    ArrayList<DataModel> name;
    boolean isPressed=false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one, container, false);
        name=new ArrayList<DataModel>();
        name.add(new DataModel("First Station",false));
        name.add(new DataModel("Second Station",false));





        ListView listView = (ListView) view.findViewById(R.id.list_view);

        CustomAdapter customAdapter =new CustomAdapter(getActivity(),name);
        listView.setAdapter(customAdapter);




        return view;
    }

    public ArrayList getData() {
        return name;
    }



    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

FragmentTwo

public class FragmentTwo extends Fragment {

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


        return  inflater.inflate(R.layout.fragment_two, container, false);
    }

    public void methodInFragmentB(ArrayList arrayList){

       for (int i=0;i<arrayList.size();i++){

       }

    }

    public void setData(ArrayList<DataModel> yourArrayList){
        Toast.makeText(getActivity(), "ArrayList Size: " + yourArrayList.size(), Toast.LENGTH_SHORT).show();
    }



}

PagerAdaper

public class FragmentpagerAdapter extends FragmentPagerAdapter {


    public FragmentpagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {

        switch (i) {

            case 0:
                return new Fragmentone();
            case 1:
                return new FragmentTwo();
            default:
                break;



        }
        return  null;
    }

    @Override
    public int getCount() {
        return 2;
    }
}

customAdapater

public class CustomAdapter extends BaseAdapter implements View.OnClickListener {

    private Activity activity;
    private ArrayList data;
    private static LayoutInflater inflater = null;
    boolean isPressed=false;


    public CustomAdapter(Activity a, ArrayList d) {

        /********** Take passed values **********/
        activity = a;
        data = d;
        inflater = (LayoutInflater) activity.
                getSystemService(Context.LAYOUT_INFLATER_SERVICE);


    }


    @Override
    public int getCount() {
        if (data.size() <= 0)
            return 1;
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public void onClick(View v) {



    }

    /*********
     * Create a holder Class to contain inflated xml file elements
     *********/
    public static class ViewHolder {

        public TextView text;

        public ImageButton imageButton;

    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        View vi = convertView;
        final ViewHolder holder;

        if (convertView == null) {

            /****** Inflate tabitem.xml file for each row ( Defined below ) *******/
            vi = inflater.inflate(R.layout.row_layout, null);

            /****** View Holder Object to contain tabitem.xml file elements ******/

            holder = new ViewHolder();
            holder.text = (TextView) vi.findViewById(R.id.station_name);

            holder.imageButton = (ImageButton) vi.findViewById(R.id.favorite);
            holder.imageButton.setBackgroundResource(R.drawable.off);

            /************  Set holder with LayoutInflater ************/
            vi.setTag(holder);
        } else
            holder = (ViewHolder) vi.getTag();

        if (data.size() <= 0) {
            holder.text.setText("No Data");

        } else {

            DataModel dataModel = (DataModel) data.get(position);

            /************  Set Model values in Holder elements ***********/

            holder.text.setText(dataModel.getText());

            // this is for overall row click
            vi.setOnClickListener(new View.OnClickListener() {



                @Override
                public void onClick(View v) {
                    Log.d("row is click","row click"+position);
                }
            });
            // this is for image button onclick
            holder.imageButton.setOnClickListener(new View.OnClickListener() {
                DataModel dataModel = (DataModel) data.get(position);
                @Override
                public void onClick(View v) {
                    if(dataModel.isselected()){
                        holder.imageButton.setBackgroundResource(R.drawable.off);
                        dataModel.setIsselected(false);
                    }else{
                        holder.imageButton.setBackgroundResource(R.drawable.on);
                        dataModel.setIsselected(true);
                    }
                    isPressed = !isPressed; // reverse

                }
            });
            ;


        }
        return vi;
    }
}

MainActivity.xml

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/pager"
   >


</android.support.v4.view.ViewPager>

fragmentone.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#325633"
   >

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list_view">
    </ListView>

</LinearLayout>

Fragmenttwo.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ee2333">

</LinearLayout>

rowlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:descendantFocusability="blocksDescendants">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/station_name"
        android:padding="10dp"
        android:textColor="#eee345"
        android:textAppearance="?android:textAppearanceLarge"
        />

    <ImageButton android:id="@+id/favorite"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"

        android:background="#00ffffff"
     />


</LinearLayout>

我要发的 ArrayList的名称; 在第二个片段..我使用的接口,但我不知道的情况下如何获取数组列表的价值就当标签查看用户刷卡或标签在第二个片段?

I need to to send ArrayList name; in second fragment ..I used interface but I don't know on event how to get value of that array list when user swipe or tab on tab view in second fragment?

推荐答案

我在这里张贴一些code,可能会帮助,看到的情况是这样的,

Here i am posting some code that might help, see the scenario is like this,

您标签在你的活动这样的点击和滑动事件将被处理,有这么宣称接口不会帮助,你可以不火的标签在回调方法刷卡或点击,那么你可以做的就是创建一个方法在 FragmentOne 将返回你的ArrayList 象下面这样

Your tabs are in your Activity so the click and swipe events would be handled there so declaring Interface will not help as you can not fire that Callback method in Tab swipe or click, so what you can do is create a method in FragmentOne which will return you ArrayList like below

public ArrayList<String> getData(){
   return yourArrayList();
}

现在 FragmentTwo 创建将接收的方法的的ArrayList FragmentOne 象下面这样

now in FragmentTwo create a method that will receive the ArrayList from FragmentOne like below

public void setData(ArrayList<String> yourArrayList){
  Toast.makeText(YourActivity.this,"ArrayList Size: "+yourArrayList.size(),Toast.LENGTH_SHORT).show();
}

现在如何引用片段活动你可以做这样的事情:

Now about how to reference the Fragments in your Activity you can do something like this:

private static String makeFragmentName(int viewPagerId, int index) {
   return "android:switcher:" + viewPagerId + ":" + index;
}

现在在设置页滑动或点击拨打上面的​​方法,请参阅您的片段像下面

Now in Tab Swipe or click call above method to Refer your fragments like below

ArrayList<String> yourArrayList = new ArrayList<>();
FragmentOne fragmentOne = getSupportFragmentManger().findFragmentByTag(makeFragmentName(viewPagerId,0))
if(fragmentOne != null){
// get your arraylist using method of FragmentOne
    yourArrayList = fragmentOne.getData();
}
// refer your second fragment and set the above arraylist in that
FragmentTwo fragmentTwo = getSupportFragmentManger().findFragmentByTag(makeFragmentName(viewPagerId,1))
if(fragmentTwo != null){
   fragmentTwo.setData(yourArrayList);
}

和你做

见上0和1适配器片段的指数,你将需要管理的 让我知道如果你需要进一步的帮助

see above 0 and 1 are index of fragments in adapter you will need to manage that let me know if you need further help

这篇关于当选择或扫描标签如何发送数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆