2016-11-23 3 views
0

Когда я нажимаю на список, узел может получить значение, но передать его второму фрагменту невозможно. Первый фрагментПередача данных из списка во фрагменте в фрагмент

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

      final String category = ((TextView) view.findViewById(R.id.mainproductitem)).getText().toString(); 
      details_fragment ldf = new details_fragment(); 
      Bundle args = new Bundle(); 
      args.putString("category", category); 
      ldf.setArguments(args); 
     } 
    }); 
     return view; 

} 

Второй фрагмент

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 

    view=inflater.inflate(R.layout.my_fragment2, container, false); 
    test = (TextView)view.findViewById(R.id.textView); 

    Bundle args = getArguments(); 
    if (args != null && args.containsKey("category")){ 
     String userId = args.getString("category"); 
     test.setText(userId); 
    } 
    return view; 
} 
+0

sry, должен получить значение во втором фрагменте ** –

+1

Я думаю, что вы не начинаете свой второй фрагмент в транзакции фрагмента. –

ответ

0

HomeActivity.xml

<?xml version="1.0" encoding="utf-8"?> 
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:context="com.example.activity.HomeActivity" 
    tools:showIn="@layout/app_bar_home"> 

//View that will hold all the fragments 
<FrameLayout 
    android:id="@+id/container_view" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
</FrameLayout> 

FirstFragment

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    // Inflate the layout for this fragment 

    View view = inflater.inflate(R.layout.fragment1, container, false); 
    view.setBackgroundColor(Color.WHITE); 

    listViewAdapter.SetOnItemClickListener(new OnItemClickListener() { 
        @Override 
        public void onItemClick(View view, int position) { 
         SecondFragment secondFrag = new SecondFragment(); 
         Bundle args = new Bundle(); 
         args.putString("Key","some value"); 

         secondFrag .setArguments(args); 
         getFragmentManager() 
         .beginTransaction() 
         .replace(R.id.container_view, fragment) 
         .addToBackStack(null) 
         .commit(); 
        } 
       }); 
    return view; 
} 

SecondFragment

Я попробовал это, и это работает прекрасно.

+0

Что означает R.id.container_view? –

+0

- это текст в моем втором фрагменте? –

+0

Это просто макет в вашей домашней деятельности, в котором будут храниться фрагменты. – Rajeev

1

Вы можете забыть, чтобы начать свой второй фрагмент

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

      final String category = ((TextView) view.findViewById(R.id.mainproductitem)).getText().toString(); 
      details_fragment ldf = new details_fragment(); 
      Bundle args = new Bundle(); 
      args.putString("category", category); 
      ldf.setArguments(args); 
      FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); 
      FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
      fragmentTransaction.replace(R.id.yourContainer, ldf); 
      fragmentTransaction.addToBackStack(null); 
      fragmentTransaction.commit(); 

     } 
    }); 
} 

и в вас второй активности

Bundle agrs = getArguments(); 
if (args != null) { 
    String category = agrs.getString("category"); 
    test.setText(category); 
} 
+0

sry, есть ошибка в формулировке там, фактически я не могу получить значение в моем втором фрагменте –

+0

Я отредактировал свой ответ, попробуйте и дайте мне знать –

+0

Вы уверены, что получаете значение в строке категории в первом фрагменте? –

0

Попробуйте это: в вашем приемном фрагменте:

Bundle agrs = this.getArguments(); 
if (args != null) { 
    String myStr = args.getString(key, defaultValue); 
} 
+0

sry, it dosent work for me –

0
`Use this code in your categorylist.setOnItemClickListener` 
// Create fragment and give it an argument specifying the article it should show 
    details_fragment newFragment = new details_fragment(); 
    Bundle args = new Bundle(); 
    args.putString("category", category) 

    //Note: if your are in fragment than replace getSupportFragmentManager to getFragmentManager. 

     FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 

    // Replace whatever is in the fragment_container view with this fragment, 
    // and add the transaction to the back stack so the user can navigate back 
     transaction.replace(R.id.fragment_container, newFragment); 
     transaction.addToBackStack(null); 

    // Commit the transaction 
     transaction.commit(); 
0

использовать набор. Вот пример:

Fragment fragment = new Fragment(); 
Bundle bundle = new Bundle(); 
bundle.putString(key, value); 
fragment.setArguments(bundle); 
getFragmentManager().beginTransaction().replace(R.id.container_view, bundle).commit(); 

Bundle установил методы для большого количества типов данных. См this

Затем в фрагменте, извлечения данных (например, в OnCreate() метод) с:

Bundle bundle = this.getArguments(); 
if (bundle != null) { 
    int myInt = bundle.getString(key, defaultValue); 
} 
0

В первом фрагменте

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

      final String category = ((TextView) view.findViewById(R.id.mainproductitem)).getText().toString(); 
      MainActivity main=new MainActivity(); 
        main.openSecondFrag(); 
     } 
    }); 
     return view; 

} 

В вашем MainActivity, положить() метод openSecondFrag

public void openSecondFrag(){ 
details_fragment ldf = new details_fragment(); 
       Bundle args = new Bundle(); 
       args.putString("category", category); 
       ldf.setArguments(args); 
} 

В Второй фрагмент

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 

    view=inflater.inflate(R.layout.my_fragment2, container, false); 
    test = (TextView)view.findViewById(R.id.textView); 

    Bundle args = getArguments(); 
    if (args != null && args.containsKey("category")){ 
     String userId = args.getString("category"); 
     test.setText(userId); 
    } 
    return view; 
} 

Я уверен, что он сработает.

Смежные вопросы