将数据从一个设计标签传递到另一个标签

时间:2016-06-21 11:42:34

标签: android android-viewpager android-support-library android-tabs

我使用的材料设计标签如下:

以下是我的MainActivity.class:

 public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {

    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(this);
        tabLayout.setupWithViewPager(viewPager);

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        System.out.println("onPageSelected Called");
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

我的ViewPagerAdapter如下:

    public class ViewPagerAdapter extends FragmentPagerAdapter {

    private static int count = 2;

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

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                 return new FragmentOne();
            case 1:
                return new FragmentTwo();
        }
        return null;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position)
        {
            case 0 :
                return "Tab One";
            case 1 :
                return "Tab Two";
        }
        return null;
    }
}

这是我的碎片:

这是我的第一个片段名称是FragmentOne:

    public class FragmentOne extends Fragment {

    private EditText editText;
    private Button btnSendData;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        System.out.println("IN FRAGMENT ONE");
        View view = inflater.inflate(R.layout.fragment_one,container,false);

        editText = (EditText) view.findViewById(R.id.et_name);
        btnSendData = (Button) view.findViewById(R.id.btn_send);

        btnSendData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                FragmentTwo fragment = new FragmentTwo();
                Bundle bundle = new Bundle();
                bundle.putString("username",editText.getText().toString());
                fragment.setArguments(bundle);
                getFragmentManager.beginTransaction.replace(R.id.frag_second,fragment).commit();

            }
        });

        return view;
    }
}

这是另一个名为FragmentTwo的片段:

 public class FragmentTwo extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        System.out.println("IN FRAGMENT TWO");
        View view = inflater.inflate(R.layout.fragment_two,container,false);
        Bundle bundle = getArguments();
        if(bundle!= null)
        {
            String value = getArguments().getString("username");
        }
        return  view;
    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println("onResume gets called");
    }
}

在第二个片段中我获取数据但是它添加了另一个视图与前一个。 看图像:

enter image description here

所以我想在两种情况下将数据从FragmentOne传递到FragmentTwo:
1.当我点击按钮时,我想传递数据 2.当我滑动到Fragment时,应传递数据

当我尝试滑动到FragmentTwo时,FragmentTwo中没有任何东西被调用?为什么会这样? 此外,当我点击第二个标签时,没有任何人被调用 请帮助我如何在点击按钮时将数据传递给FragmentTwo?

以下是布局文件: 这是fragment_one

<LinearLayout 
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:gravity="center"
       android:orientation="vertical">
           <EditText
               android:layout_marginLeft="16dp"
               android:layout_marginRight="16dp"
               android:id="@+id/et_name"
               android:hint="Username"

               android:layout_width="match_parent"
               android:layout_height="wrap_content"/>

           <Button
                android:padding="16dp"
                android:text="Send Data"
                android:layout_marginLeft="16dp"
                android:layout_marginRight="16dp"
                android:id="@+id/btn_send"
                android:layout_height="wrap_content"
                android:layout_width="match_parent"/>

和第二个片段,fragment_second.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/second_frag"
android:gravity="center">
<TextView
    android:textSize="24sp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Fragment Two"
    android:id="@+id/textView2" />

4 个答案:

答案 0 :(得分:2)

每个片段都与父活动相关联。所以你不能直接从一个片段传递到另一个片段。您需要使用界面浏览Parent Activity。

检查此文档:https://developer.android.com/training/basics/fragments/communicating.html

在按钮上单击将值传递给自定义界面中的方法,并在第二个片段中访问这些方法。

  

当我尝试滑动到FragmentTwo时,在FragmentTwo中调用任何东西

为此,您需要实现片段生命周期 - https://developer.android.com/reference/android/app/Fragment.html

<强>更新

完成代码中的一些修改后,只需查看下面的内容即可。代码 -

<强> Manifex.xml

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:theme="@style/Theme.AppCompat.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

<强> MainActivity.java

package com.app.onkar.tabdemo;

import android.support.v4.app.Fragment;
import android.support.design.widget.TabLayout;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;

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

public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);


        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

        adapter.addFragment(new FragmentOne(), "ONE");
        adapter.addFragment(new FragmentTwo(), "TWO");
        viewPager.setAdapter(adapter);

        viewPager.addOnPageChangeListener(this);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        System.out.println("onPageSelected Called");
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    public static class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();
        private static int count = 2;

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

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

        @Override
        public Fragment getItem(int position) {

            switch (position) {
                case 0:
                    return new FragmentOne();
                case 1:
                    return new FragmentTwo();
            }
            return null;
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Tab One";
                case 1:
                    return "Tab Two";
            }
            return null;
        }
    }
}

<强> FragmentOne.java

package com.app.onkar.tabdemo;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class FragmentOne extends Fragment {
    private EditText editText;
    private Button btnSendData;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        System.out.println("IN FRAGMENT ONE");
        View view = inflater.inflate(R.layout.fragment_one,container,false);

        editText = (EditText) view.findViewById(R.id.et_name);
        btnSendData = (Button) view.findViewById(R.id.btn_send);

        btnSendData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                FragmentTwo fragment = new FragmentTwo();
                Bundle bundle = new Bundle();
                bundle.putString("username",editText.getText().toString());
                fragment.setArguments(bundle);
                getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.second_frag,fragment).commit();
            }
        });

        return view;
    }
}

<强> FragmentTwo.java

package com.app.onkar.tabdemo;


import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


public class FragmentTwo extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        System.out.println("IN FRAGMENT TWO");
        View view = inflater.inflate(R.layout.fragment_two,container,false);
        TextView txt2 = (TextView) view.findViewById(R.id.textView2);
        Bundle bundle = getArguments();
        if(bundle!= null)
        {
            String value = getArguments().getString("username");
            txt2.setText(value);
        }
        return  view;
    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println("onResume gets called");
    }

}

布局文件无变化。只需尝试上面的代码 - 它完全按照您的意愿工作。希望它会有所帮助!

<强> SCREENS enter image description here enter image description here

答案 1 :(得分:0)

ViewPagerAdapter类

public class ViewPagerAdapter extends FragmentPagerAdapter {

private static int count = 2;


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

@Override
public Fragment getItem(int position) {

switch (position) {
    case 0:
         Fragment fragmentone = new FragmentOne();
         Bundle args = new Bundle();
         args.putInt("code", 1);
         fragmentone.setArguments(args);
         return fragmentone;
    break;
    case 1:
        Fragment fragmenttwo = new FragmentTwo();
         Bundle args = new Bundle();
         args.putInt("code", 2);
         fragmenttwo.setArguments(args);
         return fragmenttwo ;
      break;
}
return null;
}

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

@Override
public CharSequence getPageTitle(int position) {
switch (position)
{
    case 0 :
        return "Tab One";
    case 1 :
        return "Tab Two";
}
return null;
}
}

args是bundle对象,你可以把String int和其他值放在Fragment的onCreateView方法代码下面的片段中使用这些值。

int codeForthisFragment = getArguments().getInt("code");

按钮点击:       FragmentTransaction ft = getFragmentManager()。beginTransaction();                         Fragment secondFragment = new FragmentTwo();

                    Bundle args = new Bundle();
                    args.putInt("code", 2);
                    secondFragment.setArguments(args);
                    ft.replace(R.id.content_frame, secondFragment);
                    ft.commit();

答案 2 :(得分:0)

  

在第二个片段中我获取数据但是它添加了另一个视图与前一个。看图像

参考@Roy Miller(https://stackoverflow.com/users/5255021/roy-miller)的回答, 你可以通过以下改变来解决它:

MainActivity.java 中,替换以下开关:

 @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                return new FragmentOne();
            case 1:
                return new FragmentTwo();
        }
        return null;
    }

使用:

@Override
public Fragment getItem(int position) {

    switch (position){
        case 0:
            return mFragmentList.get(0);
        case 1:
            return mFragmentList.get(1);
        case 2:
            return mFragmentList.get(2);
        default:
            return null;
    }

}

然后,在 FragmentOne.java

替换它:

btnSendData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            FragmentTwo fragment = new FragmentTwo();
            Bundle bundle = new Bundle();
            bundle.putString("username",editText.getText().toString());
            fragment.setArguments(bundle);
            getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.second_frag,fragment).commit();
        }
    });

使用:

btnSendData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

/*This one FragmentCollection is a Singleton class that contains list of fragments, set it during initialization itself(code is attached below this code)*/
FragmentCollection fragmentCollection=FragmentCollection.getInstance();

            FragmentTwo fragment = (FragmentTwo) FragmentCollection.getmFragmentList().get(2); //getting the second fragment

             fragment.setText(editText.getText().toString());  //add this method in fragment two             

        }
    });

现在在 FragmentTwo.java 里面 添加方法:

public void updateTextView(String data){
    Log.d("TabTwo","Update Text view");
    TextView txt = (TextView)view.findViewById(R.id.textView2);
    txt.setText(data);
}

最后,我上面提到的单身人士课程:

public class FragmentCollection {
static FragmentCollection fragmentCollection=new FragmentCollection();
private final List<Fragment> mFragmentList = new ArrayList<>();    
private FragmentCollection(){}
public static FragmentCollection getInstance(){
    if(fragmentCollection!=null) {
        return fragmentCollection;
    }else {
        return new FragmentCollection();
    }
}
public void setmFragmentList(List<Fragment> mFragmentList){
    this.mFragmentList.addAll(mFragmentList);
}
public List<Fragment> getmFragmentList(){
    return mFragmentList;
}
}

让旧视图重叠的问题是因为一次又一次地初始化片段

像新的FragmentTwo();在不止一个地方。

所以在这里我们把它放在一个列表中并访问它,这样只会改变一个片段。

答案 3 :(得分:0)

我不能从第二个片段转到第一个片段。我正在使用标签布局 这是我的代码 通过点击“第二个片段”中的按钮

            Bundle bundle = new Bundle();
            bundle.putString("uniqueList1", uniqueList.get(0));
            bundle.putString("uniqueList2", uniqueList.get(1));
            bundle.putString("kycUniquesNo", kycUniqueNum);
            CustBasicFormFragement fragObj = new CustBasicFormFragement();
            fragObj.setArguments(bundle);

第一个片段

   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle 
     savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    binding = DataBindingUtil.inflate(inflater, R.layout.cust_basic_form_fragment, container, false);
    view = binding.getRoot();

    if (getArguments() != null) {
         string1 = getArguments().getString("uniqueList1");
         string2 = getArguments().getString("uniqueList2");
         kycUnique=getArguments().getString("kycUniquesNo");
        System.out.print(string1);
        System.out.print(string2);
        System.out.print(kycUnique);
    return view;

}