如何使用FragmentTransaction从数组适配器到片段

时间:2016-07-26 07:41:43

标签: java android bundle

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

这是我的代码:

ARRAY ADAPTER:

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;

   /* 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 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(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);
                        String 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);


                            //frag.setArguments(bundleUp);
                            String tag = fragment.getClass().getName();
                            FragmentManager fm = getActivity().getSupportFragmentManager();
                            fragment.setArguments(bundle);
                            FragmentTransaction ft = fm.beginTransaction();
                            ft.replace(R.id.fragmentContainer, fragment);
                            ft.addToBackStack(tag);
                            ft.commit();

                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }






                    });
                    SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = states.edit();
                    editor.putBoolean("holder.chkBox" + finalHolder.planetName.getText().toString(), true);
                    editor.commit();
                    finalHolder.edit.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            p.setQuantità(finalHolder.edit.getText().toString().trim());
                            SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = states.edit();
                            editor.putString("finalHolder.edit" + finalHolder.planetName.getText().toString(), finalHolder.edit.getText().toString().trim());
                            editor.commit();


                        }
                    });

                  /*  SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = states.edit();
                    editor.putBoolean("holder.chkBox" + finalHolder.planetName.getText().toString(), true);
                    editor.commit();*/
                    //Utility.putPizzaItem(p);
                    //Utility.getPizzaItem(p);


                } else {
                    finalHolder.edit.setVisibility(View.GONE);
                    finalHolder.edit.setEnabled(false);
                    finalHolder.edit.setText("");
                    finalHolder.spinner.setVisibility(View.GONE);


                }

            }
        });
        /*holder.chkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (finalHolder.chkBox.isChecked()) {
                    finalHolder.edit.setVisibility(View.VISIBLE);
                    finalHolder.edit.setEnabled(true);
                    SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = states.edit();
                    editor.putBoolean("holder.chkBox", true);
                    //pizzaSelected.put(p.getId(), p);
                    System.out.println(p.getId());
                } else {

                    finalHolder.edit.setVisibility(View.GONE);
                    finalHolder.edit.setEnabled(false);
                    finalHolder.edit.setText(null);
                    pizzaSelected.remove(p.getId());

                }

            }
        });
*/


       /* finalHolder.edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                p.setQuantità(finalHolder.edit.getText().toString().trim());
                SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = states.edit();
                editor.putString("finalHolder.edit" + finalHolder.planetName.getText().toString(), finalHolder.edit.getText().toString().trim());
                editor.commit();


            }
        });
*/

       // 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.edit.setEnabled(false);
        //  holder.id.setId(p.getId());

        return row;
    }




    private FragmentManager getSupportFragmentManager() {
        return null;
    }


    ArrayList<Planet> getBox() {
        ArrayList<Planet> box = new ArrayList<Planet>();
        for (Planet p : planetList) {
            if (p.isSelected())
                box.add(p);
        }
        return box;
    }



    }

FRAGMENT:

     public  class MyListFragment extends Fragment{

    String user="";


        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);
.
.
.
planetList.add(new Planet(getActivity.getSupportFragmentManager(),"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(getSupportFragmentManager(),planetList, getContext(),imageId) 

1 个答案:

答案 0 :(得分:0)

这里有一些有用的方法来帮助分解你的逻辑。

public Fragment buildFragment(String data) {
    MyListFragment fragment = new MyListFragment();
    Bundle bundle = new Bundle();
    bundle.putString("key", data);
    fragment.setArguments(bundle);
    return fragment;
} 

// Display Fragment in a View with ID of "menu_frame" 
public void replaceFragment(Fragment fragment, String tag) {
    FragmentManager fm = getContextFragmentManager(this.context);
    fm.beginTransaction()
       .replace(R.id.menu_frame, fragment) // Make sure this ID can be found in the XML for the activity 
       .addToBackStack(tag)
       .commit();
} 

// Helper method to get the FragmentManager within the adapter 
public FragmentManager getContextFragmentManager(Context context) {
    FragmentManager fm = null;
    if(context instanceof Activity){
        fm = ((Activity)context).getSupportFragmentManager();
    }
    return fm;
} 

你如何在Fragment中收到参数看起来很好。

你应该能够像这样使用这些方法

finalHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        finalHolder.spinner.setSelection(position);
        String selState = finalHolder.spinner.getSelectedItem().toString();

        Fragment fragment = buildFragment(selState);

        String tag = fragment.getClass().getName();
        replaceFragment(fragment, tag);
 } 

注意:

在适配器内部,适配器中没有getActivity()方法,因此您必须强制转换上下文。

getSupportFragmentManager()getFragmentManager()最终取决于您使用的Fragment类 - 支持v4片段或android.app.Fragment

请从适配器删除此方法。

private FragmentManager getSupportFragmentManager() {
    return null;
}