在RecyclerView Fragment中添加项目

时间:2017-09-13 17:54:39

标签: java android android-fragments android-recyclerview

道歉首先是因为这将是一个很长的问题。

我正在创建一个待办事项列表,使用2个片段中的2个RecyclerViews代码。

MainActivity.java

public class MainActivity extends AppCompatActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;


private ViewPager mViewPager;
private TaskDbHelper mHelper;

public Tab1 incompleteTasks;
public Tab2 completedTasks;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);


    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try{

                final EditText taskEditText = new EditText(MainActivity.this);
                AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("Add a new task")
                        .setMessage("What do you want to do next?")
                        .setView(taskEditText)
                        .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                try{
                                    mHelper = new TaskDbHelper(MainActivity.this);
                                    String task = String.valueOf(taskEditText.getText());
                                    mHelper.adddata(MainActivity.this, task);

                                    //incompleteTasks.addTask(mHelper.getAddedTask("0").get(0));

                                    incompleteTasks.updateUI();

                                }
                                catch(Exception ex1){
                                    Toast.makeText(MainActivity.this, (String)ex1.getMessage(), Toast.LENGTH_LONG).show();
                                }
                            }
                        })
                        .setNegativeButton("Cancel", null)
                        .create();
                dialog.show();
            }catch (Exception ex) {
                Log.d("MainActivity", "Exception: " + ex.getMessage());
            }
        }
    });

}



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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}



/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        switch (position){
            case 0:
                //Tab1 incompleteTasks = new Tab1();
                incompleteTasks = new Tab1();
                incompleteTasks.setContext(MainActivity.this);
                return incompleteTasks;
            case 1:
                //Tab2 completedTasks = new Tab2();
                completedTasks = new Tab2();
                completedTasks.setContext(MainActivity.this);
                return completedTasks ;
            default:
                return  null;
        }

    }
    @Override
    public int getItemPosition(Object object) {

        // POSITION_NONE makes it possible to reload the PagerAdapter
        return POSITION_NONE;
    }
    @Override
    public int getCount() {
        // Show 3 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Incomplete";
            case 1:
                return "Completed";

        }
        return null;
    }
}

}

RecyclerAdapter.java

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.TaskHolder> {

private ArrayList<Task> mTasks;
private boolean completedStatus;
private Context contextFromTab;

private int lastPosition = -1;

private RecyclerViewAnimator mAnimator;

//1
public class TaskHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    //2
    private TextView mTask_id;
    private TextView mTask_title;
    private TextView mTask_created_date;
    private ImageButton mImageButtonDone;
    private ImageButton mImageButtonUndo;
    private ImageButton mImageButtonEdit;
    private ImageButton mImageButtonDelete;

    //3
    //private static final String PHOTO_KEY = "PHOTO";

    //4
    public TaskHolder(View v) {
        super(v);
        try{

            //v.geti
            mTask_id = v.findViewById(R.id.task_id);
            mTask_title = v.findViewById(R.id.task_title);
            mTask_created_date = v.findViewById(R.id.task_created_date);
            mImageButtonDone = v.findViewById(R.id.imageButtonDone);
            mImageButtonUndo = v.findViewById(R.id.imageButtonUndo);
            mImageButtonEdit = v.findViewById(R.id.imageButtonEdit);
            mImageButtonDelete = v.findViewById(R.id.imageButtonDelete);


            v.setOnClickListener(this);
            mImageButtonDone.setOnClickListener(this);
            mImageButtonUndo.setOnClickListener(this);
            mImageButtonEdit.setOnClickListener(this);
            mImageButtonDelete.setOnClickListener(this);

            //v.setAnimation();
        }
        catch (Exception ex){
            Log.d("TaskHolder", ex.getMessage());
        }
    }

    //5
    @Override
    public void onClick(View v) {

        if(v.equals(mImageButtonDone)){
            View parent = (View) v.getParent();
            TextView taskTextView = (TextView) parent.findViewById(R.id.task_id);
            String _id = String.valueOf(taskTextView.getText());
            TaskDbHelper mHelper = new TaskDbHelper(contextFromTab);
            mHelper.changeTaskStatus(contextFromTab,true, _id);
            removeAt(getAdapterPosition());
        }
        else if(v.equals(mImageButtonUndo)) {
            View parent = (View) v.getParent();
            TextView taskTextView = parent.findViewById(R.id.task_id);
            String _id = String.valueOf(taskTextView.getText());
            TaskDbHelper mHelper = new TaskDbHelper(contextFromTab);
            mHelper.changeTaskStatus(contextFromTab,false, _id);
        }
        else if(v.equals(mImageButtonEdit)) {
            View parent = (View) v.getParent();
            TextView taskIdTextView = (TextView) parent.findViewById(R.id.task_id);
            TextView taskTitleTextView = (TextView) parent.findViewById(R.id.task_title);
            final String _id = String.valueOf(taskIdTextView.getText());
            String _title = String.valueOf(taskTitleTextView.getText());

            /*Intent intent = new Intent(this, TaskDetails.class);
            intent.putExtra("_id", _id);
            intent.putExtra("_title", _title);
            startActivity(intent);*/
            try{

                final EditText taskEditText = new EditText(contextFromTab);
                taskEditText.setText(_title);
                AlertDialog dialog = new AlertDialog.Builder(contextFromTab)
                        .setTitle("Edit task")
                        .setView(taskEditText)
                        .setPositiveButton("Done", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                try{
                                    TaskDbHelper mHelper = new TaskDbHelper(contextFromTab);
                                    String task = String.valueOf(taskEditText.getText());
                                    mHelper.editTask(contextFromTab, task, _id);
                                    updateAt(getAdapterPosition(), _id);
                                    /*Tab1 tab1 = new Tab1();
                                    tab1.setContext(MainActivity.this);
                                    tab1.updateUI();*/
                                }
                                catch(Exception ex1){
                                    Toast.makeText(contextFromTab, (String)ex1.getMessage(), Toast.LENGTH_LONG).show();
                                }
                            }
                        })
                        .setNegativeButton("Cancel", null)
                        .create();
                dialog.show();
            }catch (Exception ex) {
                Log.d("MainActivity", "Exception: " + ex.getMessage());
            }

        }
        else if(v.equals(mImageButtonDelete)) {
            View parent = (View) v.getParent();
            TextView taskTextView = (TextView) parent.findViewById(R.id.task_id);
            String _id = String.valueOf(taskTextView.getText());
            TaskDbHelper mHelper = new TaskDbHelper(contextFromTab);
            mHelper.deleteTask(_id);
            removeAt(getAdapterPosition());
        }
        Log.d("RecyclerView", "CLICK!");
    }
    public void bindTask(Task task, boolean completedStatus) {
        try{
            mTask_id.setText(Integer.toString(task._id) );
            mTask_title.setText(task.title);
            mTask_created_date.setText("created on: " + task.created_datetime);
            if(completedStatus){
                mImageButtonDone.setVisibility(View.INVISIBLE);
                mImageButtonUndo.setVisibility(View.VISIBLE);
            }else{
                mImageButtonDone.setVisibility(View.VISIBLE);
                mImageButtonUndo.setVisibility(View.INVISIBLE);
            }
        }
        catch (Exception ex){
            Log.d("bindTask", ex.getMessage());
        }
    }
    public void addTask(Task task){
        mTasks.add(0, task);
        notifyItemInserted(0);
        //smoothScrollToPosition(0);
    }
    public void removeAt(int position) {
        mTasks.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, getItemCount());
    }
    public void updateAt(int position, String task_id){
        //mTasks.
        //mTasks.set(position);
        try{
            TaskDbHelper mHelper = new TaskDbHelper(contextFromTab);
            Task updatedTask = mHelper.getTaskById(task_id);
            mTasks.set(position, updatedTask);
            notifyItemChanged(position);
        }
        catch (Exception ex){

        }
    }
}

public RecyclerAdapter(ArrayList<Task> tasks, boolean tasksCompletedStatus, Context context, RecyclerView recyclerView) {
    mTasks = tasks;
    completedStatus = tasksCompletedStatus;
    contextFromTab = context;

    mAnimator = new RecyclerViewAnimator(recyclerView);
}
@Override
public RecyclerAdapter.TaskHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    try{
        View inflatedView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_todo, parent, false);


        mAnimator.onCreateViewHolder(inflatedView);

        return new TaskHolder(inflatedView);
    }
    catch(Exception ex){
        Log.d("onCreateViewHolder", ex.getMessage());
        return null;
    }

}

private void setAnimation(View viewToAnimate, int position)
{
    // If the bound view wasn't previously displayed on screen, it's animated
    if (position > lastPosition)
    {
        Animation animation = AnimationUtils.loadAnimation(contextFromTab, android.R.anim.slide_in_left);
        animation.setDuration(3000);

        viewToAnimate.startAnimation(animation);
        lastPosition = position;
    }
}

@Override
public void onBindViewHolder(RecyclerAdapter.TaskHolder holder, int position) {
    try{
        Task itemTask = mTasks.get(position);
        holder.bindTask(itemTask, completedStatus);

        mAnimator.onBindViewHolder(holder.itemView, position);
    }
    catch(Exception ex){
        Log.d("onBindViewHolder", ex.getMessage());

    }

}

@Override
public int getItemCount() {
    try{
        return mTasks.size();
    }
    catch(Exception ex){
        Log.d("getItemCount", ex.getMessage());
        return 0;
    }
}

public ArrayList<Task> getListTasks(){
    return mTasks;
}

}

TaskDBHelper.java

public class TaskDbHelper extends SQLiteOpenHelper{

// Table Name
public static final String TABLE_NAME = "tasks";

// Table columns
public static final String _ID = "_id";
public static final String COL_TASK_TITLE = "title";
public static final String COL_TASK_PARENT_ID = "parent_id";
public static final String COL_TASK_COMPLETED_STATUS = "completed_status";
public static final String COL_TASK_CREATED_DATETIME = "created_datetime";
public static final String COL_TASK_MODIFIED_DATETIME = "modified_datetime";

// Database Information
static final String DB_NAME = "com.sagarmhatre.simpletodo";

// database version
static final int DB_VERSION = 1;

public TaskDbHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
    try {
        String createTable = "CREATE TABLE " + TABLE_NAME + " ( " +
                _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COL_TASK_TITLE + " TEXT NOT NULL," +
                COL_TASK_PARENT_ID + " INTEGER DEFAULT 0," +
                COL_TASK_COMPLETED_STATUS + " BOOLEAN DEFAULT 0," +
                COL_TASK_CREATED_DATETIME + " DATETIME DEFAULT (DATETIME(CURRENT_TIMESTAMP, 'LOCALTIME'))," +
                COL_TASK_MODIFIED_DATETIME + " DATETIME" +");";

        db.execSQL(createTable);
    }
    catch (Exception ex){
        Log.d("TaskDbHelper", "Exception: " + ex.getMessage());
    }
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

//Insert Value
public void adddata(Context context,String task_title) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COL_TASK_TITLE, task_title);
    db.insert(TABLE_NAME, null, values);
    db.close();
}

public Task adddataWithReturnTask(Context context,String task_title) {
    try{
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COL_TASK_TITLE, task_title);
        db.insert(TABLE_NAME, null, values);
        db.close();
        ArrayList<Task> taskList = this.getAddedTask("0");
        return taskList.get(0);
    }

    catch(Exception ex){
        Log.d("MainActivity", "Exception: " + ex.getMessage());
        return null;
    }
}

//Delete Query
public void deleteTask(String id) {
    String deleteQuery = "DELETE FROM " + TABLE_NAME + " where " + _ID + "= " + id ;
    SQLiteDatabase db = this.getReadableDatabase();
    db.execSQL(deleteQuery);
}


public void changeTaskStatus(Context context,Boolean taskStatus, String id) {
    try{
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        if(taskStatus)
            values.put(COL_TASK_COMPLETED_STATUS, 1);
        else
            values.put(COL_TASK_COMPLETED_STATUS, 0);
        db.update(TABLE_NAME, values, _ID + "=" + id, null);
        db.close();
    }
    catch(Exception ex){
        Log.d("changeTaskStatus() ", "Exception: " + ex.getMessage());
    }
}
// Edit task - by me
public void editTask(Context context,String task_title, String id) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COL_TASK_TITLE, task_title);
    db.update(TABLE_NAME, values, _ID + "=" + id, null);
    db.close();
}



//Get Row Count
public int getCount() {
    String countQuery = "SELECT  * FROM " + TABLE_NAME;
    int count = 0;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    if(cursor != null && !cursor.isClosed()){
        count = cursor.getCount();
        cursor.close();
    }
    return count;
}
//Get FavList
public ArrayList<Task> getTaskList(String ParentID, Boolean completedStatus){
    try{
        String selectQuery;
        if(completedStatus){
            selectQuery = "SELECT  * FROM " + TABLE_NAME + " WHERE "+ COL_TASK_PARENT_ID + "="+ParentID+ " AND  " + COL_TASK_COMPLETED_STATUS + " = " + 1 + "  ORDER BY " + _ID + " DESC";
        }else{
            selectQuery = "SELECT  * FROM " + TABLE_NAME + " WHERE "+ COL_TASK_PARENT_ID + "="+ParentID+ " AND  " + COL_TASK_COMPLETED_STATUS + " = " + 0 + "  ORDER BY " + _ID + " DESC";
        }

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        ArrayList<Task> TaskList = new ArrayList<Task>();
        if (cursor.moveToFirst()) {
            do {
                Task task = new Task();
                task._id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(_ID)));
                task.title = cursor.getString(1);
                task.parent_id = Integer.parseInt(cursor.getString(2));
                task.completed_status = Boolean.parseBoolean(cursor .getString(3));
                task.created_datetime = cursor.getString(4);
                task.modified_datetime = cursor.getString(5);
                TaskList.add(task);
            } while (cursor.moveToNext());
        }
        return TaskList;
    }
    catch(Exception ex){
        Log.d("getTaskList() ", "Exception: " + ex.getMessage());
        return null;
    }
}

public Task getTaskById(String _id){
    try{
        String selectQuery;

        selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "+ _ID + "="+_id;


        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        ArrayList<Task> TaskList = new ArrayList<Task>();
        if (cursor.moveToFirst()) {
            do {
                Task task = new Task();
                task._id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(_ID)));
                task.title = cursor.getString(1);
                task.parent_id = Integer.parseInt(cursor.getString(2));
                task.completed_status = Boolean.parseBoolean(cursor .getString(3));
                task.created_datetime = cursor.getString(4);
                task.modified_datetime = cursor.getString(5);
                TaskList.add(task);
            } while (cursor.moveToNext());
        }
        return TaskList.get(0);
    }
    catch(Exception ex){
        Log.d("getTaskList() ", "Exception: " + ex.getMessage());
        return null;
    }
}

public ArrayList<Task> getAddedTask(String ParentID){
    try{
        String selectQuery;

            selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "+ COL_TASK_PARENT_ID + "="+ParentID+ " AND  " + COL_TASK_COMPLETED_STATUS + " = " + 0 + "  ORDER BY " + _ID + " DESC";


        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        ArrayList<Task> TaskList = new ArrayList<Task>();
        if (cursor.moveToFirst()) {
            do {
                Task task = new Task();
                task._id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(_ID)));
                task.title = cursor.getString(1);
                task.parent_id = Integer.parseInt(cursor.getString(2));
                task.completed_status = Boolean.parseBoolean(cursor .getString(3));
                task.created_datetime = cursor.getString(4);
                task.modified_datetime = cursor.getString(5);
                TaskList.add(task);
            } while (cursor.moveToNext());
        }
        return TaskList;
    }
    catch(Exception ex){
        Log.d("getTaskList() ", "Exception: " + ex.getMessage());
        return null;
    }
}

}

Tab1.java

public class Tab1  extends Fragment {

private static final String TAG = "Tab1";
private TaskDbHelper mHelper;
//int listResourceID;
//ViewAdapter viewAdapter;
Context incompleteListContext;
Toolbar toolbar;

private RecyclerView mRecyclerView;
private LinearLayoutManager mLinearLayoutManager;

RecyclerAdapter adapter;

public void setContext(Context context){
    this.incompleteListContext = context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab1, container, false);


    mRecyclerView = rootView.findViewById(R.id.list_todo);
    mRecyclerView.setHasFixedSize(true);
    //mRecyclerView.setItemAnimator(new SlideInLeftAnimator());
    //SlideInUpAnimator animator = new SlideInUpAnimator(new OvershootInterpolator());
    //mRecyclerView.setItemAnimator(animator);
    mLinearLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(mLinearLayoutManager);

    updateUI();
    return rootView;
}
//@Override
//public void onViewCreated(View rootView, Bundle savedInstanceState){
    //incompleteList = rootView.findViewById(R.id.list_todo_completed);
    //updateUI();
//}

public void updateUI() {
    try {
        mHelper = new TaskDbHelper(incompleteListContext);
        ArrayList<Task> taskList = mHelper.getTaskList("0",false);
        adapter = new RecyclerAdapter(taskList, false, incompleteListContext, mRecyclerView);

        mRecyclerView.setAdapter(adapter);
    }
    catch (Exception ex) {
        Log.d(TAG, "Exception: " + ex.getMessage());
    }
}
public RecyclerView getRecyclerView(){
    return mRecyclerView;
}

}

到目前为止,我成功实现了删除和更新操作,而无需重新加载Tab1中的整个列表。但是在添加项目之后我想将它添加到顶部,我无法在大多数RecyclerView教程中看到它。所以我目前正在重新加载整个列表(我知道这不合适)。

需要一种不加载整个列表并在列表顶部添加项目的方法。 作为Android开发的新手,欢迎任何形式的帮助。

1 个答案:

答案 0 :(得分:1)

阅读您的代码有点困难 - &gt;请不要混合使用camelcase pascalcase前缀和非前缀命名变量。

要在顶部添加项目,请尝试使用(PSEUDO CODE):

items.add(0, ITEM_HERE);
adapter.notifyDataSetChanged();
recyclerView.smoothScrollToPosition(0);

这个addTask方法不能像你想要的那样工作吗?

 public void addTask(Task task){
        mTasks.add(0, task);
        notifyItemInserted(0);
        smoothScrollToPosition(0);
    }