在片段之间传递值

时间:2016-07-26 12:13:01

标签: java android android-fragments

当我在两个fragment之间传递参数时,字符串用户的值不在日志中打印...为什么?

这是我的代码:

ARRAY ADAPTER CLASS:

 public abstract class PlanetAdapter extends ArrayAdapter<Planet> implements CompoundButton.OnCheckedChangeListener

{
    private List<Planet> planetList;
    private Context context ;
    ArrayList<Birra> objects;
    public boolean Checked;
    private Integer[] imageId;
    String ciao;
    static PlanetAdapter plAdapter;
    String selState ;
    private FragmentManager fragmentManager;

   /* public PlanetAdapter(Context context) {
        super(context, R.layout.single_listview_item);
    }
*/

    /*public PlanetAdapter(FragmentManager fm,List<Planet> planetList, Context context,Integer[] imageId) {


        super(context, R.layout.single_listview_item,planetList);


        this.fm=fm;
        this.planetList = planetList;
        this.context = context;
        this.imageId = imageId;
    }
*/
    public PlanetAdapter(List<Planet> planetList, Context context,Integer[] imageId) {
        super(context, R.layout.single_listview_item,planetList);
        this.planetList = planetList;
        this.context = context;
        this.imageId = imageId;
    }

    public FragmentManager getFragmentManager() {
        return fragmentManager;
    }


    public class PlanetHolder {
        public TextView planetName;
        public TextView distView;
        public TextView valuta;
        public CheckBox chkBox;
        public EditText edit;
        public TextView caratteristica;
        public boolean checked;
        public TextView id;
        public ImageView imageView;
        public Spinner spinner;
    }

    @Override
    public int getCount() {
        return planetList.size();
    }

    @Override
    public Planet getItem(int position) {
        return planetList.get(position);
    }




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

        View row = convertView;
        PlanetHolder holder = null;

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(R.layout.single_listview_item, parent, false);
            holder = new PlanetHolder();
            holder.planetName = (TextView) row.findViewById(R.id.name);
            holder.distView = (TextView) row.findViewById(R.id.dist);
            holder.valuta = (TextView) row.findViewById(R.id.valuta);
            holder.chkBox = (CheckBox) row.findViewById(R.id.chk_box);
            holder.edit = (EditText) row.findViewById(R.id.editText);
            holder.spinner = (Spinner) row.findViewById(R.id.simpleSpinner);

            holder.caratteristica=(TextView) row.findViewById(R.id.caratteristica);
            holder.imageView = (ImageView) row.findViewById(R.id.ivImage);
            holder.edit.setVisibility(View.GONE);
            holder.edit.setEnabled(false);
            holder.spinner.setVisibility(View.GONE);

            // holder.id = (TextView) row.findViewById(R.id.id);


            row.setTag(holder);

        } else {
            holder = (PlanetHolder) row.getTag();
        }

        final Planet p = planetList.get(position);
        holder.imageView.setImageResource(imageId[position]);
        holder.planetName.setText(p.getName());
        holder.distView.setText("" + p.getDistance());
        holder.valuta.setText("" + p.getValuta());
        holder.chkBox.setChecked(p.isSelected());
        holder.chkBox.setTag(p);
        holder.caratteristica.setText(p.getCaratteristica());
       holder.edit.setEnabled(false);
        SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
        boolean isChecked = states.getBoolean("holder.chkBox" + holder.planetName.getText().toString(), false);
        System.out.println(isChecked);
        if (isChecked) {
            holder.chkBox.setChecked(true);
            holder.edit.setVisibility(View.VISIBLE);
            holder.edit.setEnabled(true);
            holder.spinner.setVisibility(View.VISIBLE);

            SharedPreferences statess = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
            String string = statess.getString("finalHolder.edit" + holder.planetName.getText().toString(), holder.edit.getText().toString().trim());
            holder.edit.setText(string);


        } else {
            holder.chkBox.setChecked(false);
            holder.edit.setVisibility(View.GONE);
            holder.edit.setEnabled(false);
            holder.spinner.setVisibility(View.GONE);


         }

        holder.chkBox.setOnCheckedChangeListener(PlanetAdapter.this);
       // final BirraHolder finalHolder = birraHolder;
        final PlanetHolder finalHolder = holder;

        holder.chkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (finalHolder.chkBox.isChecked()) {
                    finalHolder.edit.setVisibility(View.VISIBLE);
                    finalHolder.edit.setEnabled(true);
                    finalHolder.spinner.setVisibility(View.VISIBLE);
                    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                            getContext(),
                            R.array.country_arrays,
                            android.R.layout.simple_spinner_item);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    //finalHolder.spinner.setAdapter(adapter);

                    finalHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            finalHolder.spinner.setSelection(position);
                            selState = finalHolder.spinner.getSelectedItem().toString();
                            System.out.println(selState);
                            Toast.makeText(
                                    getContext(),
                                    "Clicked on Planet: " + selState + "", Toast.LENGTH_SHORT).show();

/*
                            Fragment fragment = new Fragment();
                             Bundle bundle = new Bundle();
                            bundle.putString("key", selState);
                            Log.i("BUNDLE", bundle.toString());
                            fragment.setArguments(bundle);*/
                            MyListFragment fragment = MyListFragment.newInstance("my_string");

FRAGMENT:

public  class MyListFragment extends Fragment implements
        CompoundButton.OnCheckedChangeListener{

    ListView lv;
    ArrayList<Planet> planetList;
    static PlanetAdapter plAdapter;
    private TextView txtName;
    private TextView txtEmail;
    private Button btnLogout;
    ListView listView;
    String user="";

    private SQLiteHandler db;
    private SessionManager session;
    BirraAdapter biAdapter;
    PlanetAdapter.PlanetHolder holder;
    private static Context context = null;
    private static FragmentActivity mInstance;

    Integer[] imageId = {
            R.mipmap.androtuto,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ok,
            /*R.drawable.image6,
            R.drawable.image7*/

    };
    public static MyListFragment newInstance(String tagName) {
        MyListFragment fragment = new MyListFragment ();
        Bundle args = new Bundle();
        args.putString("key", tagName);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            user = getArguments().getString("key");
        }

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the custom_spinner_items for this fragment
        //super.onDestroy();

        SharedPreferences settings = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.clear();
        editor.commit();

        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list2, container, false);

        /*Bundle bundle = this.getArguments();
        String strtext = bundle.getString("key", " ");
        System.out.println(strtext);*/
        System.out.println("prima ancora");

        Bundle arguments = this.getArguments();
        System.out.println("prima");
        if (arguments != null) {
            System.out.println("dopo");

            //String userId = arguments.getString("key");
                //System.out.println("finalmente:"+userId);
             user = getArguments().getString("Key");


        } /*else {
            Log.i("BUNDLE == null", "NULL");
        }*/
        System.out.println("finalmente:"+user);
        Log.d("finalmente:", "" + user);



        lv = (ListView) rootView.findViewById(R.id.listview);
        ListAdapter listAdapter = new MyListAdapter(getContext());
        lv.setAdapter(listAdapter);



        context = getActivity();
        mInstance = getActivity();
        txtName = (TextView) rootView.findViewById(R.id.name);
        txtEmail = (TextView) rootView.findViewById(R.id.numero_telefonico);
        btnLogout = (Button) rootView.findViewById(R.id.btnLogout);

        // SqLite database handler
        db = new SQLiteHandler(context.getApplicationContext());


        // session manager
        session = new SessionManager(context.getApplicationContext());
/*

        if (!session.isLoggedIn()) {
            logoutUser();
        }
*/

        // Fetching user details from SQLite
        HashMap<String, String> user = db.getUserDetails();

        String name = user.get("name");
        //String email = user.get("email");
//      String email = user.get("email");
        String email = user.get("numero_telefonico");


        // Displaying the user details on the screen
        System.out.println(name + email);

        txtName.setText(name);
        txtEmail.setText(email);
    /*  Button mButton = (Button) rootView.findViewById(R.id.button);
        mButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showResult(v);


            }
        });*/
        //return inflater.inflate(R.custom_spinner_items.fragment_list2, container, false);
        btnLogout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                logoutUser();
            }
        });



        return rootView;
    }




    private void logoutUser() {
        session.setLogin(false);

        db.deleteUsers();

        // Launching the login activity
//      Intent intent = new Intent(MyListFragment.this, LoginActivity.class);
        Intent intent = new Intent(getActivity().getApplicationContext(), LoginActivity.class);

        startActivity(intent);
        mInstance.finish();
    }


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



        lv = (ListView)getView().findViewById(R.id.listview);
        displayPlanetList();


    }


    private void displayPlanetList() {

        planetList = new ArrayList<Planet>();
        planetList.add(new Planet("Margherita", "6", "€","(pomodoro e mozzarella),"));
        planetList.add(new Planet("Diavola", "7","€","(pomodoro,mozzarella e salsiccia piccante)"));
        planetList.add(new Planet("Bufalina", "5","€","(pomodoro e mozzarella di bufala)"));
        planetList.add(new Planet("Marinara", "5", "€","(pomodoro)"));
        planetList.add(new Planet("Viennese", "4", "€", "(pomodoro,mozzarella e wrustel)"));

        plAdapter = new PlanetAdapter(planetList, getContext(),imageId) {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                int pos = lv.getPositionForView(buttonView);
                if (pos != ListView.INVALID_POSITION) {
                    Planet p = planetList.get(pos);
                    p.setSelected(isChecked);


            /*Toast.makeText(
                    getActivity(),
                    "Clicked on Pizza: " + p.getName() + ". State: is "
                            + isChecked, Toast.LENGTH_SHORT).show();*/
                }


            }
        };

        lv.setAdapter(plAdapter);
    }




    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        /*int pos = lv.getPositionForView(buttonView);
        if (pos != ListView.INVALID_POSITION) {
            Planet p = planetList.get(pos);
            p.setSelected(isChecked);


            *//*Toast.makeText(
                getActivity(),
                "Clicked on Planet: " + p.getName() + ". State: is "
                        + isChecked, Toast.LENGTH_SHORT).show();*//*
        }*/

    }


    @TargetApi(Build.VERSION_CODES.KITKAT)
    /*public String showResult(View v) throws IOException {
    *//*    //String  result = "Selected Product are :";
        String  result = "";

    //  int totalAmount=0;
        //String  result2 = "";
        //int totalAmount2=0;

        //String a="";
        //String z="";

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                result += "\n" + p.getName()+" "+p.getDistance()+"€"+"q.tà :"+p.getQuantità();
            }
        }


        //Toast.makeText(context, result + "\n" + "Total Amount:=" + totalAmount2 + "€", Toast.LENGTH_LONG).show();

        return result;*//*
        String  result = "";

        Gson json = new Gson();
        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                *//*json.put("name",p.getName());
                json.put("distance",p.getDistance());
                json.put("quantity",p.getQuantità());*//*
                result=result+json.toJson(p);


            }
        }
         //result=json.toString();

        String path = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/droidText/";

        //FileWriter file=null;

    *//*    try {
            file = new FileWriter(path+"filename5.json");
            file.write(result);


        }catch(IOException ie){}
        finally{


            file.flush();
            file.close();

        }*//*
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String currentDate = sdf.format(new Date());

        try(FileWriter file = new FileWriter(path  + currentDate + " - " + ".json"))  {
        //  file=new FileWriter(path+"filename100.json");
        *//*FileWriter file = new FileWriter(path+"filename31.json");
            file.write(result);
        file.close();
        *//*

            json.toJson(result, file);
        *//*catch(IOException r){

        }*//*
        }catch (IOException e){

        }
        System.out.println(result);
        return result;

    }*/
    public static String showResultTotale2(View v,String user) {

        int totalAmount=0;
        String pizzeOrdinate="";

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                pizzeOrdinate+="\n" + p.getName()+ " " + p.getDistance() + "€" + "q.tà :" + p.getQuantità()+ " " + user;

            }
        }
        return pizzeOrdinate;
    }


    public static int showResultTotale(View v) {

        int totalAmount=0;

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                int quantitaInt= Integer.parseInt(p.getQuantità() );
                int distanceInt= Integer.parseInt(p.getDistance());
                totalAmount+=distanceInt * quantitaInt;
            }
        }
        return totalAmount;
    }





}

4 个答案:

答案 0 :(得分:0)

尝试这样(在android studio中创建片段时,就这样做了):

public  class MyListFragment extends Fragment implements
        CompoundButton.OnCheckedChangeListener{

    ListView lv;
    ArrayList<Planet> planetList;
    static PlanetAdapter plAdapter;
    private TextView txtName;
    private TextView txtEmail;
    private Button btnLogout;
    ListView listView;
    String user="";

    private SQLiteHandler db;
    private SessionManager session;
    BirraAdapter biAdapter;
    PlanetAdapter.PlanetHolder holder;
    private static Context context = null;
    private static FragmentActivity mInstance;

    Integer[] imageId = {
            R.mipmap.androtuto,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ic_launcher,
            R.mipmap.ok,
            /*R.drawable.image6,
            R.drawable.image7*/

    };

public MyListFragment () { //Always put the empty constructor
        }

    public static MyListFragment newInstance(String tagName) {
        MyListFragment fragment = new MyListFragment ();
        Bundle args = new Bundle();
        args.putString("key", tagName);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            user = getArguments().getString("key");
        }

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the custom_spinner_items for this fragment
        //super.onDestroy();

        SharedPreferences settings = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.clear();
        editor.commit();

        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list2, container, false);

        /*Bundle bundle = this.getArguments();
        String strtext = bundle.getString("key", " ");
        System.out.println(strtext);*/
        System.out.println("prima ancora");

        Bundle arguments = this.getArguments();
        System.out.println("prima");

        System.out.println("finalmente:"+user);
        Log.d("finalmente:", "" + user);



        lv = (ListView) rootView.findViewById(R.id.listview);
        ListAdapter listAdapter = new MyListAdapter(getContext());
        lv.setAdapter(listAdapter);



        context = getActivity();
        mInstance = getActivity();
        txtName = (TextView) rootView.findViewById(R.id.name);
        txtEmail = (TextView) rootView.findViewById(R.id.numero_telefonico);
        btnLogout = (Button) rootView.findViewById(R.id.btnLogout);

        // SqLite database handler
        db = new SQLiteHandler(context.getApplicationContext());


        // session manager
        session = new SessionManager(context.getApplicationContext());
/*

        if (!session.isLoggedIn()) {
            logoutUser();
        }
*/

        // Fetching user details from SQLite
        HashMap<String, String> user = db.getUserDetails();

        String name = user.get("name");
        //String email = user.get("email");
//      String email = user.get("email");
        String email = user.get("numero_telefonico");


        // Displaying the user details on the screen
        System.out.println(name + email);

        txtName.setText(name);
        txtEmail.setText(email);
    /*  Button mButton = (Button) rootView.findViewById(R.id.button);
        mButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showResult(v);


            }
        });*/
        //return inflater.inflate(R.custom_spinner_items.fragment_list2, container, false);
        btnLogout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                logoutUser();
            }
        });



        return rootView;
    }




    private void logoutUser() {
        session.setLogin(false);

        db.deleteUsers();

        // Launching the login activity
//      Intent intent = new Intent(MyListFragment.this, LoginActivity.class);
        Intent intent = new Intent(getActivity().getApplicationContext(), LoginActivity.class);

        startActivity(intent);
        mInstance.finish();
    }


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



        lv = (ListView)getView().findViewById(R.id.listview);
        displayPlanetList();


    }


    private void displayPlanetList() {

        planetList = new ArrayList<Planet>();
        planetList.add(new Planet("Margherita", "6", "€","(pomodoro e mozzarella),"));
        planetList.add(new Planet("Diavola", "7","€","(pomodoro,mozzarella e salsiccia piccante)"));
        planetList.add(new Planet("Bufalina", "5","€","(pomodoro e mozzarella di bufala)"));
        planetList.add(new Planet("Marinara", "5", "€","(pomodoro)"));
        planetList.add(new Planet("Viennese", "4", "€", "(pomodoro,mozzarella e wrustel)"));

        plAdapter = new PlanetAdapter(planetList, getContext(),imageId) {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                int pos = lv.getPositionForView(buttonView);
                if (pos != ListView.INVALID_POSITION) {
                    Planet p = planetList.get(pos);
                    p.setSelected(isChecked);


            /*Toast.makeText(
                    getActivity(),
                    "Clicked on Pizza: " + p.getName() + ". State: is "
                            + isChecked, Toast.LENGTH_SHORT).show();*/
                }


            }
        };

        lv.setAdapter(plAdapter);
    }




    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        /*int pos = lv.getPositionForView(buttonView);
        if (pos != ListView.INVALID_POSITION) {
            Planet p = planetList.get(pos);
            p.setSelected(isChecked);


            *//*Toast.makeText(
                getActivity(),
                "Clicked on Planet: " + p.getName() + ". State: is "
                        + isChecked, Toast.LENGTH_SHORT).show();*//*
        }*/

    }


    @TargetApi(Build.VERSION_CODES.KITKAT)
    /*public String showResult(View v) throws IOException {
    *//*    //String  result = "Selected Product are :";
        String  result = "";

    //  int totalAmount=0;
        //String  result2 = "";
        //int totalAmount2=0;

        //String a="";
        //String z="";

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                result += "\n" + p.getName()+" "+p.getDistance()+"€"+"q.tà :"+p.getQuantità();
            }
        }


        //Toast.makeText(context, result + "\n" + "Total Amount:=" + totalAmount2 + "€", Toast.LENGTH_LONG).show();

        return result;*//*
        String  result = "";

        Gson json = new Gson();
        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                *//*json.put("name",p.getName());
                json.put("distance",p.getDistance());
                json.put("quantity",p.getQuantità());*//*
                result=result+json.toJson(p);


            }
        }
         //result=json.toString();

        String path = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/droidText/";

        //FileWriter file=null;

    *//*    try {
            file = new FileWriter(path+"filename5.json");
            file.write(result);


        }catch(IOException ie){}
        finally{


            file.flush();
            file.close();

        }*//*
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String currentDate = sdf.format(new Date());

        try(FileWriter file = new FileWriter(path  + currentDate + " - " + ".json"))  {
        //  file=new FileWriter(path+"filename100.json");
        *//*FileWriter file = new FileWriter(path+"filename31.json");
            file.write(result);
        file.close();
        *//*

            json.toJson(result, file);
        *//*catch(IOException r){

        }*//*
        }catch (IOException e){

        }
        System.out.println(result);
        return result;

    }*/
    public static String showResultTotale2(View v,String user) {

        int totalAmount=0;
        String pizzeOrdinate="";

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                pizzeOrdinate+="\n" + p.getName()+ " " + p.getDistance() + "€" + "q.tà :" + p.getQuantità()+ " " + user;

            }
        }
        return pizzeOrdinate;
    }


    public static int showResultTotale(View v) {

        int totalAmount=0;

        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()){
                int quantitaInt= Integer.parseInt(p.getQuantità() );
                int distanceInt= Integer.parseInt(p.getDistance());
                totalAmount+=distanceInt * quantitaInt;
            }
        }
        return totalAmount;
    }





}

更简单:

public class MyListFragment extends Fragment {


    public MyListFragment () { //Always put the empty constructor
    }


    public static MyListFragment newInstance(String tagName) {
        MyListFragment fragment = new MyListFragment ();
        Bundle args = new Bundle();
        args.putString("key", tagName);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
             user = arguments.getString("key");
            }

        }
}

您正在创建片段而不是:

MyListFragment fragment = new MyListFragment();
                            final Bundle bundle = new Bundle();
                            bundle.putString("key", selState);
                            Log.i("BUNDLE", bundle.toString());
                            fragment.setArguments(bundle);

使用此:

MyListFragment fragment = MyListFragment.newInstance("my_string");

问题真的不清楚...... 在adpater中:

private MyListFragment fragment;
    public PlanetAdapter(List<Planet> planetList, Context context,Integer[] imageId, MyListFragment myFragment) {
            super(context, R.layout.single_listview_item,planetList);
            this.planetList = planetList;
            this.context = context;
            this.imageId = imageId;
this.fragment = myFragment;
    }

当您需要时:

fragment.passValue("my string");

现在在你的片段中创建方法:

public void passValue(String myString){
//Do whatever with myString
}

答案 1 :(得分:0)

这是因为你在错误的地方调用了getArguments()。

覆盖onCreate()并输入代码以获取其中的值。

 @Override
    public void onCreate(Bundle savedInstanceState) {
            Bundle arguments = getArguments();
            if (arguments != null) {
                    //String userId = arguments.getString("key");
                    //System.out.println("finalmente:"+userId);
                 user = arguments.getString("key");


            } /*else {
                Log.i("BUNDLE == null", "NULL");
            }*/
            //System.out.println("finalmente:"+user);
            Log.e("MESSAGE","finalmente:"+user);

    }

答案 2 :(得分:0)

System.out.println("finalmente:"+user);在Android中无效。

您必须使用Log.d("MESSAGE","MY MESSAGE");

Bundle arguments = getArguments();
            if (arguments != null) {
                    //String userId = arguments.getString("key");
                    //System.out.println("finalmente:"+userId);
                 user = arguments.getString("key");


            } /*else {
                Log.i("BUNDLE == null", "NULL");
            }*/
           Log.d("finalmente:",""+user);

    }

在此处查看答案Why doesn't “System.out.println” work in Android?

答案 3 :(得分:0)

启动片段时,您正尝试使用getArguments()。最好在onViewCreated触发器

时尝试处理你的Arguments
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    handleArguments(getArguments());
}

public void handleArguments(Bundle bnd) {
    if (bnd != null) {
         if (bnd.containsKey("key")) {
         user = arguments.getString("key");
         }
    }
System.out.println("finalmente:"+user);
}