简体   繁体   English

将片段添加到RecyclerView中

[英]Add item to RecyclerView in Fragment

At present, I have an application with a RecyclerView in a fragment. 目前,我有一个片段中带有RecyclerView的应用程序。 My problem currently is that I am not able to add an element to this RecyclerView . 我目前的问题是我无法向此RecyclerView添加元素。 I am currently using a DialogFragment to get input from the user, and when the user pushes the "create" button, a method in the MainActivity is called 我当前正在使用DialogFragment从用户那里获取输入,并且当用户按下“创建”按钮时, MainActivity的方法被调用

CreateRecipeFragment DialogFragment class: CreateRecipeFragment DialogFragment类:

public class CreateRecipeFragment extends DialogFragment {

    public CreateRecipeFragment() {
        // Required empty public constructor
    }

    EditText newName, newIngredients, newMethod, newNotes;

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();

        // Inflate and set the layout for the dialog
        final View view = inflater.inflate(R.layout.fragment_create_recipe, null);

        // Pass null as the parent view because its going in the dialog layout

        Bundle mArgs = getArguments();
        final String parentBook = mArgs.getString("parentBook");

        builder.setView(view)
                // Add action buttons
                .setPositiveButton("Create Recipe", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {

                        newName = (EditText) view.findViewById(R.id.editTitle);
                        newIngredients = (EditText) view.findViewById(R.id.editIngredients);
                        newMethod = (EditText) view.findViewById(R.id.editMethod);
                        newNotes = (EditText) view.findViewById(R.id.editNotes);

                        String recipe_name = newName.getText().toString();
                        String recipe_ingredients = newIngredients.getText().toString();
                        String recipe_method = newMethod.getText().toString();
                        String recipe_notes = newNotes.getText().toString();

                        Recipe recipe = new Recipe(recipe_name, "Description", recipe_ingredients, recipe_method, recipe_notes, parentBook);

                        Log.d("Name:  ", recipe_name);
                        MainActivity callingActivity = (MainActivity) getActivity();
                        callingActivity.addRecipeFromFragment(recipe);
                        dialog.dismiss();

                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        CreateRecipeFragment.this.getDialog().cancel();
                    }
                });

        // Create the AlertDialog object and return it
        return builder.create();
    }

    public void onClick(DialogInterface dialog, int position) {


    }

    }

The onClick listener in the fragment that has the RecyclerView 具有RecyclerView的片段中的onClick侦听器

fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CreateRecipeFragment createRecipeFragment = new CreateRecipeFragment();
            MainActivity callingActivity = (MainActivity) getActivity();
            createRecipeFragment.show(callingActivity.getSupportFragmentManager(), "DialogBOX2");
            recipes.add(callingActivity.tempRecipe);
            m2Adapter.notifyDataSetChanged();
            // m2Adapter is the adapter for the RecyclerView in the fragment
        }
    });

The add Method in the MainActivity MainActivity的add方法

public Recipe tempRecipe;
public void addRecipeFromFragment(Recipe recipe) {
    dbManager.addRecipe(recipe);
    tempRecipe = recipe;

}

addRecipe method in DBManager class (SQLite) DBManager类中的addRecipe方法(SQLite)

public void addRecipe(Recipe recipe) {

    ContentValues values = new ContentValues();
    values.put(COLUMN_RECIPE_NAME, recipe.getRecipeTitle());
    values.put(COLUMN_RECIPE_DESCRIPTION, recipe.getRecipeDescription());
    values.put(COLUMN_RECIPE_INGREDIENTS, recipe.getIngredients());
    values.put(COLUMN_RECIPE_METHOD, recipe.getMethod());
    values.put(COLUMN_RECIPE_NOTES, recipe.getNotes());
    if (COLUMN_IMAGE_ID != null) {
        values.put(COLUMN_IMAGE_ID, recipe.getImageId());
    }
    values.put(COLUMN_PARENT_BOOK, recipe.getParentBook());

    SQLiteDatabase db = this.getWritableDatabase();
    db.insert(TABLE_RECIPES, null, values);
    db.close();
}

Thanks! 谢谢!

First of all there is no point in creating dialog fragment when you are using alert dialog inside it. 首先,当您在其中使用警报对话框时,创建对话框片段毫无意义。 You can remove the Alert dialog creation code from the dialog fragment and have the custom layout for dialog fragment as per requirement. 您可以从对话框片段中删除“警报”对话框创建代码,并根据需要为对话框片段定制布局。 This is same as fragments . 这与片段相同。 Second you should use Interfaces to communicate from fragment to activity.Have a look at the below link http://developer.android.com/training/basics/fragments/communicating.html http://simpledeveloper.com/how-to-communicate-between-fragments-and-activities/ 其次,您应该使用Interfaces从片段到活动进行通信。请看下面的链接http://developer.android.com/training/basics/fragments/communicating.html http://simpledeveloper.com/how-to-片段与活动之间的沟通/

Third have the recycler adapter globally in the activity and have public method in the adapter which will add the newly added item to the list add call notifyItemInserted(0); 第三,在活动中全局具有回收器适配器,并在适配器中具有公共方法,该方法将新添加的项目添加到列表中。add调用notifyItemInserted(0); I can also see that you are inserting data in db . 我还可以看到您正在db中插入数据。 If so you can write a public method in adapter and get all the recipies from db and put it into List model maintained in the adpater and call notifyDataSetChanged 如果是这样,您可以在适配器中编写一个公共方法,并从db获取所有配方,并将其放入adpater中维护的List模型中,然后调用notifyDataSetChanged

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android Fragment Recyclerview 添加带有对话框的项目 - Android Fragment Recyclerview add item with dialog Android RecyclerView片段中的项目宽度 - Android RecyclerView item width in fragment 是否有任何方法可以调用 SecondActivity 在具有 Recyclerview 的 FirstActivity.Fragment 上的 Arraylist 上添加新项目? - Is there any method that i can call on SecondActivity to add a new item on Arraylist on FirstActivity.Fragment that has Recyclerview? 从 RecyclerView 项更新片段中的 WebView - Update WebView in Fragment from RecyclerView Item RecyclerView不使用项目上的片段替换详细信息窗格 - RecyclerView not replacing detail pane with fragment on item click 单击RecyclerView中的项目后分段交易 - Fragment transaction after clicking item in RecyclerView 将项目添加到RecyclerView的最佳方法 - Best way to add item to RecyclerView 在 RecyclerView 中添加 static 默认项 - Add static default item in RecyclerView 如何在片段中设置OnclickListener FAB,该片段将在RecyclerView中添加卡片 - How to setOnclickListener FAB in a fragment that will add a card in a RecyclerView SearchView 过滤器按预期工作,但在片段中检索 RecyclerView 上的旧项目位置 - SearchView filter is working as intented, but retrieves old item position on RecyclerView in fragment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM