如何在导航抽屉中的两个片段之间传递数据

Posted

技术标签:

【中文标题】如何在导航抽屉中的两个片段之间传递数据【英文标题】:How to communicate data between two fragments in a navigation drawer 【发布时间】:2014-05-24 20:20:17 【问题描述】:

我有一个包含不同片段的导航抽屉(每个项目显示一个片段),我想将数据从一个片段传递到另一个片段。(我只有一个包含导航抽屉的活动,其中有一个列表碎片)。

我尝试了许多解决方案(捆绑和意图),但我无法解决我的问题。

谁能帮帮我。

这是我的第一个片段 A: 包 com.tutecentral.navigationdrawer;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class setting extends Fragment implements OnItemSelectedListener, View.OnClickListener

Button button_validate;
EditText editText;
Spinner spinner;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) 
    // TODO Auto-generated method stub
    View view;
    view=inflater.inflate(R.layout.setting, container, false);

    spinner=(Spinner) view.findViewById(R.id.spinnerSetting);
    ArrayAdapter adapter=ArrayAdapter.createFromResource(getActivity(), R.array.listMenu, android.R.layout.simple_spinner_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

    editText=(EditText) view.findViewById(R.id.price);

    button_validate=(Button) view.findViewById(R.id.buttonValidatePrices);
    button_validate.setOnClickListener(this);

    return view;

@Override
public void onItemSelected(AdapterView<?> adapter, View view, int position,long arg3) 
    // TODO Auto-generated method stub
    TextView myText=(TextView) view;
    switch (position) 
    case 0:
        editText.setText("0");
        break;
    case 1:
        editText.setText("1");
        break;
    case 2:
        editText.setText("2");
        break;
    case 3:
        editText.setText("3");
        break;
    case 4:
        editText.setText("4");
        break;
    case 5:
        editText.setText("5");
        break;
    case 6:
        editText.setText("6");
        break;
    case 7:
        editText.setText("7");
        break;
    case 8:
        editText.setText("8");
        break;
    case 9:
        editText.setText("9");
        break;
    default:
        editText.setTag(getResources().getString(R.string.Default_prices));
    

@Override
public void onNothingSelected(AdapterView<?> arg0) 
    // TODO Auto-generated method stub


@Override
public void onClick(View view) 
    // TODO Auto-generated method stub
    if(view.getId()==R.id.buttonValidatePrices) 
        //SharedPreferences preferences=this.getActivity().getSharedPreferences("MyData", Context.MODE_PRIVATE);
        //SharedPreferences.Editor editor=preferences.edit();
        //editor.remove("price_"+spinner.getSelectedItem().toString());
        //editor.putString("price_"+spinner.getSelectedItem().toString(), editText.getText().toString());
        //editor.commit();

        Bundle bundle=new Bundle();
        bundle.putString("price_"+spinner.getSelectedItem().toString(), editText.getText().toString());
        Menu menu=new Menu();
        menu.setArguments(bundle);
    

这是我应该获取数据的 FragmentB(请参阅 getarguments): 包 com.tutecentral.navigationdrawer;

/** * 一个简单的 @link android.support.v4.app.Fragment 子类。 * */ 公共类 Menu 扩展 Fragment 实现 OnClickListener、TabListener

public Menu()
    // TODO Auto-generated constructor stub


public static final String Default="20";

public static ActionBar actionBar;
Button order, add, remove;
Gallery gallery;
ImageView imageView;
TextView descriptionTextView;
TextView textViewPrice;
TextView totalPrice;
Bundle args = new Bundle();
int total=0, price=0;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
    // Inflate the layout for this fragment
    View view=inflater.inflate(R.layout.fragment_menu, container, false);       

    actionBar=getActivity().getActionBar();
    actionBar.setNavigationMode(actionBar.NAVIGATION_MODE_TABS);



    order=(Button) view.findViewById(R.id.commander);
    order.setOnClickListener(this);
    add=(Button) view.findViewById(R.id.addMenu);
    add.setOnClickListener(this);
    remove=(Button) view.findViewById(R.id.removeMenu);
    remove.setOnClickListener(this);

    gallery=(Gallery)view.findViewById(R.id.gallery);
    imageView=(ImageView)view.findViewById(R.id.imageView);
    gallery.setAdapter(new ImageAdapter(getActivity(), 0));

    descriptionTextView=(TextView)view.findViewById(R.id.descriptionText);
    textViewPrice=(TextView) view.findViewById(R.id.priceMenu);
    textViewPrice.setOnClickListener(this);

    totalPrice=(TextView) view.findViewById(R.id.TotalFieldMenu);

    price=Integer.parseInt(textViewPrice.getText().toString());

    gallery.setOnItemClickListener(new OnItemClickListener()           

        @Override
        public void onItemClick(AdapterView<?> adapter, View arg1, int position,long arg3) 
            // TODO Auto-generated method stub
            String price1;
            SharedPreferences preferences=getActivity().getSharedPreferences("MyData", Context.MODE_PRIVATE);
            switch (actionBar.getSelectedNavigationIndex()) 
            case 0:
                imageView.setImageResource(ImageAdapter.ThumbsIds[position]);
                break;
            case 1:
                imageView.setImageResource(ImageAdapter.ThumbsIds2[position]);
                break;
            case 2:
                imageView.setImageResource(ImageAdapter.ThumbsIds3[position]);
                break;

            default:
                imageView.setImageResource(ImageAdapter.ThumbsIds[position]);

                break;
            
            ChangeData(position);
            switch (ImageAdapter.ThumbsIds[position]) 
            case R.drawable.pizza:
                //price1=preferences.getString("price_"+"pizza", Default);
                Log.i("bundlebundlebundle", getArguments().getString("price_"+"pizza",Default));
                price1=getArguments().getString("price_"+"pizza", Default);
                break;
            case R.drawable.fishsoup:
                price1=preferences.getString("price_"+"Fish soup", Default);
                break;
            case R.drawable.frenchfries:
                price1=preferences.getString("price_"+"French fries", Default);
                break;
            case R.drawable.chakhchoukha:
                price1=preferences.getString("price_"+"Chakhchoukha", Default);
                break;
            case R.drawable.couscous:
                price1=preferences.getString("price_"+"couscous", Default);
                break;
            case R.drawable.zlabia:
                price1=preferences.getString("price_"+"zlabia", Default);
                break;
            case R.drawable.juice:
                price1=preferences.getString("price_"+"juice", Default);
                break;
            case R.drawable.salade_fruit:
                price1=preferences.getString("price_"+"salade fruit", Default);
                break;
            case R.drawable.salade_fromage:
                price1=preferences.getString("price_"+"salade fromage", Default);
                break;
            case R.drawable.salade_verte:
                price1=preferences.getString("price_"+"salade verte", Default);
                break;
            default:
                price1=preferences.getString("price_"+"pizza", Default);
                break;


            
            if(price1.equals(String.valueOf(Default)))
                textViewPrice.setText(String.valueOf(Default));
            
            else
                textViewPrice.setText(price1);
            
            price=Integer.parseInt(price1);
        

    );

    ActionBar.Tab tab1=actionBar.newTab();
    tab1.setText(getResources().getString(R.string.Starter));
    tab1.setTabListener(this);

    ActionBar.Tab tab2=actionBar.newTab();
    tab2.setText(getResources().getString(R.string.Maindisk));
    tab2.setTabListener(this);

    ActionBar.Tab tab3=actionBar.newTab();
    tab3.setText(getResources().getString(R.string.Desert));
    tab3.setTabListener(this);

    actionBar.addTab(tab1);
    actionBar.addTab(tab2);
    actionBar.addTab(tab3);

    return view;


public ActionBar getActionBar() 
    return actionBar;


public void setActionBar(ActionBar actionBar) 
    this.actionBar = actionBar;


//This methode allow us to change the data according to the index of listView.
public void ChangeData(int index)
    String [] description=getResources().getStringArray(R.array.Description);
    descriptionTextView.setText(description[index]);
 

/*public void orderMenu(View view)

*/


@Override
public void onClick(View v) 
    switch (v.getId()) 
    case R.id.commander:
        //args.putString("price", textViewPrice.getText().toString());  
        //FragmentManager manager=getFragmentManager();
        //MyDialog dialog=new MyDialog();
        //dialog.setArguments(args);
        //dialog.show(manager, "MyDialog");
        Bundle args=new Bundle();
        args.putString("priceTotal", totalPrice.getText().toString());


        //haredPreferences preferences=this.getActivity().getSharedPreferences("Order_Price", Context.MODE_PRIVATE);
        //haredPreferences.Editor editor=preferences.edit();
        //ditor.putString("price1"+textViewPrice.toString(), String.valueOf(R.string.Default_prices));

        //ditor.commit();

        //imageView.setImageResource(ImageAdapter.ThumbsIds[0]);
        //ChangeData(0);
        break;
        case R.id.removeMenu :

            break;
        case R.id.addMenu :

            total=Integer.parseInt(totalPrice.getText().toString())+price;
            totalPrice.setText(String.valueOf(total));
            Toast.makeText(getActivity(), "dish added", Toast.LENGTH_SHORT).show();
            break;
    


@Override
public void onViewCreated(View view, Bundle savedInstanceState) 
    // TODO Auto-generated method stub
    super.onViewCreated(view, savedInstanceState);
    Log.i("bundlebundlebundle", getArguments().getString("price_"+"pizza",Default));


@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) 
    // TODO Auto-generated method stub



@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) 
    // TODO Auto-generated method stub
    gallery.setAdapter(new ImageAdapter(getActivity(), tab.getPosition()));
    switch (tab.getPosition()) 
    case 0:
        imageView.setImageResource(ImageAdapter.ThumbsIds[0]);
        break;
    case 1:
        imageView.setImageResource(ImageAdapter.ThumbsIds2[0]);
        break;
    case 2:
        imageView.setImageResource(ImageAdapter.ThumbsIds3[0]);
        break;

    default:
        imageView.setImageResource(ImageAdapter.ThumbsIds[0]);
        break;
    


@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) 
    // TODO Auto-generated method stub


这是我使用适配器处理导航抽屉的主要活动(请参阅 switch(switch (possition) : 包 com.tutecentral.navigationdrawer;

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

import com.tutecentral.navigationdrawer.R.menu;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class MainActivity extends Activity 

  private DrawerLayout mDrawerLayout;
  private ListView mDrawerList;
  private ActionBarDrawerToggle mDrawerToggle;

  private CharSequence mDrawerTitle;
  private CharSequence mTitle;
  CustomDrawerAdapter adapter;

  List<DrawerItem> dataList;

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

        // Initializing
        dataList = new ArrayList<DrawerItem>();
        mTitle = mDrawerTitle = getTitle();
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

     // Add Drawer Item to dataList
        dataList.add(new DrawerItem(true)); // adding a spinner to the list

        dataList.add(new DrawerItem("Main Options"));// adding a header to the list
        dataList.add(new DrawerItem("Search", R.drawable.ic_action_search));
        dataList.add(new DrawerItem("Menu", R.drawable.menu));
        dataList.add(new DrawerItem("Envoie Facture", R.drawable.bill));
        dataList.add(new DrawerItem("Affectations", R.drawable.table));

        dataList.add(new DrawerItem("Other Options")); // adding a header to the list
        dataList.add(new DrawerItem("About", R.drawable.ic_action_about));
        dataList.add(new DrawerItem("Settings", R.drawable.setting));
        dataList.add(new DrawerItem("Help", R.drawable.ic_action_help));

        dataList.add(new DrawerItem("Social")); // adding a header to the list
        dataList.add(new DrawerItem("Message", R.drawable.ic_action_email));
        dataList.add(new DrawerItem("Likes", R.drawable.ic_action_good));
        dataList.add(new DrawerItem("Twitter", R.drawable.twitter));

        adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,dataList);

        mDrawerList.setAdapter(adapter);
        mDrawerList.setBackgroundColor(R.color.background_NavAda);

        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open,R.string.drawer_close) 
              public void onDrawerClosed(View view) 
                    getActionBar().setTitle(mTitle);
                    invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
              

              public void onDrawerOpened(View drawerView) 
                    getActionBar().setTitle(mDrawerTitle);
                    invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
              
        ;

        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) 

            if (dataList.get(0).isSpinner() & dataList.get(1).getTitle() != null) 
                  SelectItem(2);
             else if (dataList.get(0).getTitle() != null) 
             SelectItem(1);

             else 
                  SelectItem(0);
            
      

  

  @Override
  public boolean onCreateOptionsMenu(Menu menu) 
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
  

  public void SelectItem(int possition) 

      Fragment fragment = null;
      Bundle args = new Bundle();
      switch (possition) 

      case 2:
            fragment = new FragmentThree();
            args.putString(FragmentThree.ITEM_NAME, dataList.get(possition).getItemName());
            args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition).getImgResID());
            break;
      case 3:
            fragment = new com.tutecentral.navigationdrawer.Menu();
            break;
      case 4:
            fragment = new bill_send();
            //args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition).getItemName());
            //args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition).getImgResID());
            break;
      case 5:
            fragment = new tables();
            //args.putString(FragmentThree.ITEM_NAME, dataList.get(possition).getItemName());
            //args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition).getImgResID());
            break;
      case 7:
            fragment = new about();
            //args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition).getItemName());
            //args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition).getImgResID());
            break;
      case 8:
            fragment = new setting();
            //args.putString(FragmentThree.ITEM_NAME, dataList.get(possition).getItemName());
            //args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition).getImgResID());
            break;
      case 9:
            fragment = new FragmentOne();
            args.putString(FragmentOne.ITEM_NAME, dataList.get(possition).getItemName());
            args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition).getImgResID());
            break;
      case 10:
            fragment = new FragmentTwo();
            args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition).getItemName());
            args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition).getImgResID());
            break;
      case 11:
            fragment = new FragmentThree();
            args.putString(FragmentThree.ITEM_NAME, dataList.get(possition).getItemName());
            args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition).getImgResID());
            break;
      case 12:
            fragment = new FragmentOne();
            args.putString(FragmentOne.ITEM_NAME, dataList.get(possition).getItemName());
            args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition).getImgResID());
            break;
      case 13:
            fragment = new FragmentThree();
            args.putString(FragmentThree.ITEM_NAME, dataList.get(possition).getItemName());
            args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition).getImgResID());
            break;
      default:
            break;
      

      if(com.tutecentral.navigationdrawer.Menu.actionBar!=null)
          if (com.tutecentral.navigationdrawer.Menu.actionBar.isShowing())
              com.tutecentral.navigationdrawer.Menu.actionBar.removeAllTabs();
          

      

        fragment.setArguments(args);
        FragmentManager frgManager = getFragmentManager();
        frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

        mDrawerList.setItemChecked(possition, true);
        setTitle(dataList.get(possition).getItemName());
        mDrawerLayout.closeDrawer(mDrawerList);

  

  @Override
  public void setTitle(CharSequence title) 
        mTitle = title;
        getActionBar().setTitle(mTitle);
  

  @Override
  protected void onPostCreate(Bundle savedInstanceState) 
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
  

  @Override
  public void onConfigurationChanged(Configuration newConfig) 
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggles
        mDrawerToggle.onConfigurationChanged(newConfig);
  

  @Override
  public boolean onOptionsItemSelected(MenuItem item) 
        // The action bar home/up action should open or close the drawer.
        // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) 
              return true;
        

        return false;
  

  private class DrawerItemClickListener implements
  ListView.OnItemClickListener 
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,long id) 
          if (dataList.get(position).getTitle() == null) 
                SelectItem(position);
          

    

谢谢。

【问题讨论】:

【参考方案1】:

当您在NavigationDrawer 内部单击时,您可以使用setArguments() 方法通过Bundle 声明您的数据,如下所示:

// int id = 1;
MyFragment newFragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("ARG_DATA_ID", id);
newFragment.setArguments(args);
// replace and commit with fragmenttransaction  

然后,在您的 Fragment 中,使用 getArgument() 方法,如下所示:

Bundle arg = getArguments();
int id_pass = arg.getInt("ARG_DATA_ID");
// id_pass = 1;  

但是,也许您可​​以在此主题中找到一些有用的提示:Communicating with Other Fragments。


更新:

好吧,我试图从你的代码中做一个例子,但是,它是嗡嗡声.. 很难 ;)。

    您没有收到参数,因为在SelectItem 方法中,您没有使用Menu 片段发送任何参数(但是您的开关是如何做的,您走对了)。当您在setting 中单击buttonValidatePrices 时,您尝试单独发送参数,但在其他Bundle 中,它不是发送或任何东西。刚刚创建,里面存储了一个值,什么都没有。。它与FragmentTransaction无关。

    Menu 中,你尝试用这个来接收:

    Log.i("bundlebundlebundle", getArguments().getString("price_"+"pizza",Default));  
    

    但我认为这样会更好:

    Log.i("bundlebundlebundle", getArguments().getString("price_pizza"));  
    

你应该:

First (在 MainActivity 中) = 获取从MainActivity 到您的setting 片段的点击微调器的值,创建一个捆绑并设置这个值到SelectItem方法里面的片段,如下:

switch(...) 
    case 2: 
        frag = new Menu();
        // get the value of the spinner selected from here! Something like this:
          String text = ((Spinner) findViewById(R.id.spinnerSetting)). getSelectedItem().toString();
        // String named "spinner_position", this is how you can get it after
        args.putString("spinner_position", text);
        break;
    ...

frag.setArguments(args);
// replace the fragment  

Second在菜单中)=接收这个参数如下:

// receive using the name "spinner_position", that's it. Nothing else.
String text_spinner = getArguments().getString("spinner_position");

【讨论】:

问题是我将数据更改为片段 1(例如法国的价格),然后当我单击导航抽屉的微调器时,会出现一个列表,我选择另一个片段 2,我必须找到价格。因此,如果我使用您的方法,我认为它不会起作用。 我会再试一次,我会在 createView 中调用 getArguments.getInt() 看看(我使用 Log 来显示 getId 值,它没有改变!!) .但是非常感谢,我很感激。 据我了解,您尝试通过微调器(?)调用另一个片段,您可以在事务之前设置参数,在您的应用程序中的任何位置 setInt、setString、setBoolean、等等,并在另一个片段的 oncreateview 中使用新包获取它。如果您遇到问题,您可以编辑您的问题并向我们展示您所做的事情。我会帮忙的。 这是我的 FragmentA : Fllo,很多,它就像一个魅力,我可以理解你的解决方案。谢谢;)。【参考方案2】:

您可以使用http://developer.android.com/reference/android/content/BroadcastReceiver.html

或者您可以将每个片段的侦听器设置为您的活动,并将数据从片段发送到活动并直接在活动的另一个片段上调用方法。

【讨论】:

以上是关于如何在导航抽屉中的两个片段之间传递数据的主要内容,如果未能解决你的问题,请参考以下文章

如何在导航抽屉活动模板中的片段之间传递字符串变量

如何在两个片段之间传递位图? (我正在使用 Android 导航组件)

在 NavigationUI 的同一主机活动上传递数据并更新片段文本/按钮

通过片段之间的导航传递数据android studio

通过导航组件在底部导航片段之间传递数据

导航项目已选中,传递额外信息