将结果(可序列化类)从DialogFragment传递到Fragment

时间:2016-08-11 18:43:59

标签: java android listview android-fragments serialization

我有包含片段的主要活动。其中一个片段是为新项目条目调用dialogFragment。这个新项由Serializable类指定。 更具体一点: item.java

public class Item implements Serializable {
private String mTitle;
private String mDescription;
private Boolean mTrue;


//getters and setters

public String getTitle() {
    return mTitle;
}
public void setTitle(String mTitle) {
    this.mTitle = mTitle;
}
public String getDescription() {
    return mDescription;
}
public void setDescription(String mDescription) {
    this.mDescription = mDescription;
}
public Boolean isTrue() {
    return mTrue;
}
public void setTrue(Boolean mTrue) {
    this.mTrue = mTrue;
}
}

DialogNewItem

public class DialogNewItem extends DialogFragment {


//filters state holder
Boolean isTrue = false;
//filters state end

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

@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View dialogView = inflater.inflate(R.layout.new_item, null);

    final EditText editTitle = (EditText) dialogView.findViewById(R.id.editTitle);
    final EditText editDescription = (EditText) dialogView.findViewById(R.id.editDescription)

    //filter icons
    final ImageView ivIsTrue = (ImageView) dialogView.findViewById(R.id.filterTrue);
    //filter icons end

    //onClickListener for filter icons
    ivIsTrue.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            if (isTrue == false) {
                ivIsTrue.setBackgroundResource(R.drawable.border_white);
                ivIsTrue.setImageResource(R.drawable.true_white);
                isTrue = true;
            } else {
                ivIsTrue.setBackgroundResource(R.drawable.border_green);
                ivIsTrue.setImageResource(R.drawable.true_green);
                isTrue = false;
            }
        }
    });


    Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
    Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);


    builder.setView(dialogView);

    //cancel button
    btnCancel.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            dismiss();
        }
    });

    //give button
    btnOK.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            //new item
            final Item newItem = new Item();

            //Set its variables to match the users entries on the form
            newItem.setTitle(editTitle.getText().toString());
            newItem.setDescription(editDescription.getText().toString());
            newItem.setTrue(isTrue);



            dismiss();
        }
    });
    return builder.create();
}

}

现在,我想将newItem从DialogNewItem(btnOK)传递给listView Fragment。换句话说,我想创建一个listView Fragment,它将包含在DialogNewItem中创建的所有新项目。 我正在尝试不同的方法(set / getFragment,ArrayList,不同的接口等),但有些方法是如何工作的。将newItem传递给活动中的listView没有问题:

//get the reference to dashboard
Dashboard callingActivity = (Dashboard) getActivity();
//pass new item back to dashboard
callingActivity.createNewItem(newItem);

然后是仪表板活动:

 public class Dashboard extends AppCompatActivity {

private ItemAdapter mItemAdapter;

public void createNewItem(Item n) {
    mItemAdapter.addItem(n);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);

    mItemAdapter = new ItemAdapter();
    ListView listItem = (ListView) findViewById(R.id.listView);
    listItem.setAdapter(mItemAdapter);
}

//handle clicks on listView
listItem.setOnItemClickListener(new AdapterView.OnItemClickListener(){
    @Override
    public void onItemClick (AdapterView<?> adapter, View view, int whichItem, long id ){
        //creating temporary item which is reference to the clicked item
        Item tempItem = mItemAdapter.getItem(whichItem);
        //new dialog window
        DialogShowItem dialog = new DialogShowItem();
        //send reference to the item to be shown
        dialog.sendItemSelected(tempItem);
        //show the dialog window with the item
        dialog.show(getFragmentManager(),"");
    }
});

@Override
public View getView(int whichItem, View view, ViewGroup viewGroup){
    //has been inflated already
    if (view==null){
        //creating layout inflater
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //instantiate view by inflating inflater (listItem layout)
        view = inflater.inflate(R.layout.listitem, viewGroup, false);
    }

    Item tempItem = itemList.get(whichItem);

    //grabbing the refrence to all variables
    TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
    TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);

    ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);


    //setting text variables
    txtTitle.setText(tempItem.getTitle());
    txtDescription.setText(tempItem.getDescription());

    //hide not relevant images
    if (!tempItem.isTrue()){
        ivTrue.setVisibility(View.INVISIBLE);
    } else {ivTrue.setVisibility(View.VISIBLE);}
    //category with different image src


    return view;
}

并且一切都很完美,但是当我想用Fragment而不是Activity做同样的事情时,不知何故我无法使它工作。 我将不胜感激任何帮助。感谢名单

片段(使用listview):     公共类ListItems扩展了ListFragment {

private ItemAdapter mItemAdapter;

public void createNewItem(Item i) {
    mItemAdapter.addItem(i);
}

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstatceState) {
    View view = inflater.inflate(R.layout.list_items, container, false);

    //Item adapter
    mItemAdapter = new ItemAdapter();
    final ListView listItems = (ListView) view.findViewById(R.id.listView);
    listItems.setAdapter(mItemAdapter);


    //floating give button
    FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DialogNewItem dialog = new DialogNewItem();
            dialog.show(getFragmentManager(), "");
        }
    });

    //handle clicks on itemList
    listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int whichItem, long id) {
            Item tempItem = mItemAdapter.getItem(whichItem);
            DialogShowItem dialog = new DialogShowItem();
            dialog.sendItemSelected(tempItem);
            dialog.show(getFragmentManager(), "");
        }
    });

    return view;
}

@Override
protected void onPause() {
    super.onPause();
    mItemAdapter.saveItems();
}

public class ItemAdapter extends BaseAdapter {
    List<Item> itemList = new ArrayList<Item>();

    private JSONSerializer mSerializer;

    public ItemAdapter() {
        mSerializer = new JSONSerializer("myProject.json", getActivity().getApplicationContext());
        try {
            itemList = mSerializer.load();
        } catch (Exception e) {
            itemList = new ArrayList<Item>();
            Log.e("Error loading items: ", "", e);
        }
    }

    public void saveItems() {
        try {
            mSerializer.save(itemList);
        } catch (Exception e) {
            Log.e("Error saving items: ", "", e);
        }
    }

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

    @Override
    public Item getItem(int whichItem) {
        return itemList.get(whichItem);
    }

    @Override
    public long getItemId(int whichItem) {
        return whichItem;
    }

    public void addItem(Item n) {
        itemList.add(n);
        notifyDataSetChanged();
    }

    @Override
    public View getView(int whichItem, View view, ViewGroup viewGroup) {
        if (view==null) {
            LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.list_items, viewGroup, false);
        }

        Item tempItem = itemList.get(whichItem);

        TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
        TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);

        ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);

        //setting text variables
        txtTitle.setText(tempItem.getTitle());
        txtDescription.setText(tempItem.getDescription());

        //hide  irrelevant images
        if (!tempItem.isTrue()){
            ivTrue.setVisibility(View.INVISIBLE);
        } else {ivTrue.setVisibility(View.VISIBLE);}

        return view;
    }

}
}

这是抽屉活动,所以我在抽屉项目点击后显示它:

private void switchFragment(int position) {
Fragment fragment = null;
    String fragmentID = "";
    switch (position) {
        case 0:
            fragmentID = "LISTITEMS";
            fragment = new ListItems();
            break;
        case 1:
            fragmentID = "PROFILE";
            fragment = new Profile();
            break;
        default:
            break;
    }
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.fragmentHolder, fragment, fragmentID).commit();
    //close the drawer
    mDrawerLayout.closeDrawer(mNavDrawerList);
}

1 个答案:

答案 0 :(得分:0)

您可以在ListItems片段类中创建一个公共方法,在该类中接收Item类对象并将其添加到适配器中。然后在您的DialogNewItem片段中,点击OK按钮,您可以使用SupportFragmentManager使用其标签搜索ListItems并调用您编写的公共方法。

以下代码可能对您有所帮助。

DialogNewItem类

btnOK.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //new item
            final Item newItem = new Item();

            //Set its variables to match the users entries on the form
            newItem.setTitle(editTitle.getText().toString());
            newItem.setDescription(editDescription.getText().toString());
            newItem.setTrue(isTrue);

            FragmentManager manager = getActivity().getSupportFragmentManager();

            ListItems fragment = (ListItems)manager.findFragmentByTag("LISTITEMS");

            if(fragment != null){
               fragment.createNewItem(newItem);
            }            

            dismiss();
        }
    });

在ListItems片段中,以下代码将ItemAdapter描述为ListViewFragment类的数据成员,下面是您可以调用以在适配器中添加项目的方法。

private ItemAdapter mItemAdapter;

public void createNewItem(Item n) {
    mItemAdapter.addItem(n);
}