【问题标题】:Android Passing String from fragment to fragmentAndroid在片段之间传递字符串
【发布时间】:2019-08-17 19:01:38
【问题描述】:

我在导航抽屉中有两个片段 ListNav 和 SwipeNav。 ListNav 显示来自字符串数组的数据的列表视图。 SwipeNav 将数据显示为字符串数组中相同数据的滑动视图。

我正在使用单个片段进行 viewpager 滑动查看多个选项卡。

我的问题是:

When I click on B in List View, it shows A in SwipeNav,
When I click on C in List View, it shows A in SwipeNav,
When I click on D in List View, it shows A in SwipeNav,
When I click on E in List View, it shows A in SwipeNav,

我想得到结果:

If I click on B in List View, it will show B in SwipeNav,
If I click on C in List View, it will show C in SwipeNav,
If I click on D in List View, it will show D in SwipeNav

字符串数组:

<string-array name="tab_titles">
    <item>A</item>
    <item>B</item>
    <item>C</item>
    <item>D</item>
    <item>E</item>
    <item>F</item>
    <item>G</item>
    <item>H</item>
    <item>I</item>
    ........
</string-array>

我使用 ListNav 在下面用 OnItemClickListener 替换为 SwipeNav:

列表导航:

public class ListNav extends Fragment {

    @Nullable
    @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
        return inflater.inflate(R.layout.nav_lis_layout, container, false);

    }

 @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        FragmentManager fm=getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.fragment12, new ListNavAdapter());
        ft.commit();

ListNavAdapter:

public class ListNavAdapter extends ListFragment {

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.nav_list_layout, container, false);
    return view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
            R.array.tab_titles, android.R.layout.simple_list_item_1);
    setListAdapter(adapter);
    getListView().setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            String[] tabTitlesArray = getContext().getResources().getStringArray(R.array.tab_titles);
            Bundle bundle = new Bundle();
            bundle.putString("tab_titles", tabTitlesArray[i].toString());

            SwipeNav fragobj = new SwipeNav();
            fragobj.setArguments(bundle);

            FragmentManager fm=getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(((ViewGroup)(getView().getParent())).getId(), fragobj);
            ft.addToBackStack(null);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            ft.commit();
        }
    });
}

在 SwipeNav 中:

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

    if (getArguments() != null && !getArguments().isEmpty()) {
        Bundle bundle = this.getArguments();
        String myInt = bundle.getString("tab_titles");
    }
        return inflater.inflate(R.layout.nav_swipe, container, false);

}


@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    myPagerAdapter = new MyPagerAdapter(getChildFragmentManager(),getContext());
    viewPager = (ViewPager) view.findViewById(R.id.pager);

    viewPager.setAdapter(myPagerAdapter);

}

这是 MyPagerAdapter:

public class MyPagerAdapter extends FragmentStatePagerAdapter {
private Context context;


private String[] tabTitlesArray = null;
public MyPagerAdapter(FragmentManager fm, Context context) {
    super(fm);

    tabTitlesArray = context.getResources().getStringArray(R.array.tab_titles);
    this.context= context;
}

@Override
public Fragment getItem(int i) {
    Fragment fragment = new AFragment();
    Bundle args = new Bundle();

    args.putString(AFragment.ARG_OBJECT, tabTitlesArray[i]);
    fragment.setArguments(args);
    return fragment;
}

@Override
public int getCount() {
    return tabTitlesArray.length;
}

@Override
public CharSequence getPageTitle(int position) {


    return "OBJECT " + (position + 1);
}
}

选项卡式活动的单个片段 AFragment:

public class AFragment extends Fragment {
public static final String ARG_OBJECT = "object";

public AFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // The last two arguments ensure LayoutParams are inflated
    // properly.


    View rootView = inflater.inflate(R.layout.fragment_a, container, false);
    Bundle args = getArguments();
    ((TextView) rootView.findViewById(R.id.text1)).setText(args.getString(ARG_OBJECT));
    return rootView;


}

nav_lis_layout:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment12"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

nav_list_layout:

<?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" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>
</LinearLayout>

我在 Stackoverflow 中搜索了所有答案。但未能解决我的问题,为什么特定项目单击不显示相同项目到下一个片段。 我需要你的帮助。

【问题讨论】:

  • 据我了解 - 您有 ViewPager 和两 (2) 个片段。你必须在片段之间传递数据吗?点击first fragment 显示second fragment 有正确的数据?
  • 你能把代码上传到某个地方吗?没有完整的类,代码很多,很难理解。
  • @Boken 我添加了单片段AFragment。我将单个片段用于多个选项卡。

标签: java android arrays string android-fragments


【解决方案1】:

在您的 SwipeNav 中,设置 ViewPager 后,您还没有使用 viewPager.setCurrentItem() 来更改您想要的页面。由于 setCurrentItem() 需要一个整数参数,所以列表中的点击位置需要从 ListNavAdapter 传递到 SwipeNav。

ListNavAdapter.java:

public class ListNavAdapter extends ListFragment {

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.nav_list_layout, container, false);
    return view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
            R.array.tab_titles, android.R.layout.simple_list_item_1);
    setListAdapter(adapter);
    getListView().setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            //Toast.makeText(getActivity(), "Item: " + (i +1), Toast.LENGTH_SHORT).show();
            String[] tabTitlesArray = getContext().getResources().getStringArray(R.array.tab_titles);
            Bundle bundle = new Bundle();
            bundle.putString("tab_titles", tabTitlesArray[i].toString());

            bundle.putInt("tab_int", i);    //Added

            // set Fragmentclass Arguments
            SwipeNav fragobj = new SwipeNav();
            fragobj.setArguments(bundle);

            FragmentManager fm=getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(((ViewGroup)(getView().getParent())).getId(), fragobj);
            ft.addToBackStack(null);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            ft.commit();

            //Fragment f=getFragmentManager().findFragmentById(R.id.fragment12);
           // if(f==null){
               // getFragmentManager().beginTransaction().replace(((ViewGroup)(getView().getParent())).getId(), new SwipeNav()).commit();
           // }

        }
    });
}





  // Toast.makeText(getActivity(), "Item: " + (position +1), Toast.LENGTH_SHORT).show();
    // Create new fragment and transaction



}

SwipeNav.java:

public class SwipeNav extends Fragment {

private MyPagerAdapter myPagerAdapter;
private ViewPager viewPager;

private int tab_int;    //Added


@Nullable
@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
    //String passingString = getArguments().getString("TAG");
    if (getArguments() != null && !getArguments().isEmpty()) {
        Bundle bundle = this.getArguments();
        String myInt = bundle.getString("tab_titles");

        tab_int = bundle.getInt("tab_int"); //Added

        return inflater.inflate(R.layout.nav_swipe, container, false);
    } else {
        return inflater.inflate(R.layout.nav_swipe, container, false);
    }
}


@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    myPagerAdapter = new MyPagerAdapter(getChildFragmentManager(),getContext());
    viewPager = (ViewPager) view.findViewById(R.id.pager);
    //viewPager.setId( R.id.pager );
    viewPager.setAdapter(myPagerAdapter);

    viewPager.setCurrentItem(tab_int);  //Added

    //you can set the title for your toolbar here for different fragments different titles
    getActivity().setTitle("Satyanusaran Bengali");
}

}

希望有帮助!

【讨论】:

    【解决方案2】:

    当我在列表视图中单击 B 时,它会在 SwipeNav 中显示 A,

    问题是因为您发送的是相同的对象但具有不同的键。

    您要做的是,在您的onClick 中获取适配器的位置并将其放到您的bundle

    bundle.putString("tab_titles", tabTitlesArray[i].toString());
    

    然后你使用String myString = bundle.getString("tab_titles");获取值

    然后当你创建适配器时,你可以通过参数发送String并将文本放在你的适配器中,反正代码是一团糟......很难理解。

    【讨论】:

    • 感谢您的支持。我编辑并添加了问题中的所有类。我添加了您的代码,但同样的问题仍然存在。
    • @achalnaskar 请始终使用相同的密钥,这是什么:args.putString(AFragment.ARG_OBJECT, tabTitlesArray[i]); 请听我说,如果您想获取数据,请使用您发送和接收的相同密钥!我的意思是如果你做 putString(Key1,value) 不要在你的 getString(key777777,value) 中使用是没有意义的,好吗?检查这个。
    • 感谢先生的建议。我必须执行你的建议。直到现在问题仍然相同。没有得到改善。我单击 ListNav 并打开 Swipenav。但传递字符串来自 ListNavAdapter。是不是有问题?
    • 我建议您将此代码放入 github 并发布在您的问题中,以便我深入了解
    • 我已将所有内容上传到此链接,请检查。 github.com/achalnaskar/Navigation-with-swipe-views
    【解决方案3】:

    你不应该使用字符串逗号

     "tabTitlesArray[i]"
    

    试试

     ""+tabTitlesArray[i]
    

    【讨论】:

    • 感谢您的建议。我改变了,但我的问题仍然存在。
    • 如果您多次使用 affragment,则获取数据如下: bundle.getString("object");
    • 我试过你的建议,比如: bundle.putString("object", "A");和 bundle.getString("object");但没有解决办法。
    • 我想你没明白我的意思。您正在使用此键发送数据:args.putString(AFragment.ARG_OBJECT, tabTitlesArray[i]);所以我希望你用相同的键来获取它:bundle.getString("object");
    • 我使用相同但没有结果。我将数据从 ListNavAdapter 传递到 SwipeNav。是问题吗?我用 bundle.putString(AFragment.ARG_OBJECT, tabTitlesArray[i].toString());和 String myString = bundle.getString(AFragment.ARG_OBJECT);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    相关资源
    最近更新 更多