如何在RecyclerView.Adapter

时间:2017-11-10 03:28:31

标签: android android-fragments android-recyclerview android-adapter recycler-adapter

美好的一天当用户点击MyAdapter类中的卡片时,如何调用片段。我想从适配器替换视图。我正在使用recyclerview想要使用我的行布局中的视图执行click事件。

例如,当用户点击卡片时,它会打开一个片段,它会显示更多数据。希望你能帮助我们。

这是我的主要片段

  

AccountsFragment

     

ReceivableFragment

     

LoanAppFragment

这些片段包含不同的数据。当用户点击该片段中的卡片时,它会调用另一个片段 SLDTLFragment

  

这是MyAdapter.java

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

private List<Datas> mDataset;

// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class MyViewHolder extends RecyclerView.ViewHolder {

    public CardView mCardView;
    public TextView account_type;
    public TextView accnt_description;
    public TextView balance_label;
    public TextView account_balance;

    public MyViewHolder(View v) {
        super(v);

        mCardView = (CardView) v.findViewById(R.id.card_view);

        account_type = (TextView) v.findViewById(R.id.lblShareCapital);
        balance_label = (TextView) v.findViewById(R.id.lblAvailableBalance);

        accnt_description = (TextView) v.findViewById(R.id.sl_desc);
        account_balance = (TextView) v.findViewById(R.id.actual_balance);
    }
}
public MyAdapter(List<Datas> myDataset) {
    mDataset = myDataset;
}

// Create new views (invoked by the layout manager)
@Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
                                                 int viewType) {
    // create a new view
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.card_item, parent, false);
    // set the view's size, margins, paddings and layout parameters
    MyViewHolder vh = new MyViewHolder(v);
    return vh;
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
    //holder.account_type.setText(mDataset[position]);
    Datas datas = mDataset.get(position);
    holder.accnt_description.setText(datas.getSL_DESC());
    holder.account_balance.setText(datas.getACTUAL_BALANCE());
    holder.mCardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
         // String sl_desc = mDataset.get(position).getSL_DESC();
         // String actual_balance = mDataset.get(position).getACTUAL_BALANCE();
            String sle = mDataset.get(position).getSLE();
            String slc = mDataset.get(position).getSLC();
            String slt = mDataset.get(position).getSLT();
            String ref_no = mDataset.get(position).getREF();

            Log.d("CardView Clicked", "sle code: " + sle);
            Log.d("CardView Clicked", "slc code: " + slc);
            Log.d("CardView Clicked", "slt code: " + slt);
            Log.d("CardView Clicked", "ref no: "   + ref_no);
        }
    });
}

@Override
public int getItemCount() {
    return mDataset.size();
}

}

  

AccountsFragment.java

public class AccountsFragment extends Fragment {
private SQLiteHandler db;
    public AccountsFragment() {
        // Required empty public constructor
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_accounts, container, false);
        RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
        rv.setHasFixedSize(true);
        SQLiteHandler db = new SQLiteHandler(getActivity());
        MyAdapter adapter = new MyAdapter(db.getUserSLDetails());
        rv.setAdapter(adapter);

        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        rv.setLayoutManager(llm);

        return rootView;
    }
}
  

ReceivableFragment.java

    public class ReceivableFragment extends Fragment {


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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_receivable, container, false);
        RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
        rv.setHasFixedSize(true);
        SQLiteHandler db = new SQLiteHandler(getActivity());
        MyAdapter adapter = new MyAdapter(db.getUserSLARLoans());
        rv.setAdapter(adapter);

        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        rv.setLayoutManager(llm);

        return rootView;
    }

}
  

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private TextView nav_header_name;
    private TextView nav_header_email;

    public TextView txtLogOut;

    private SQLiteHandler db;
    private SessionManager session;

    private Timer timer;
    private Toolbar toolbar;

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

        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //Will replace the activity_main.xml to relativelayout_for_fragment.xml
        if (savedInstanceState == null) {
            AccountsFragment f1= new AccountsFragment();
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.add(R.id.relativelayout_for_fragment, f1);// relativelayout_for_fragment is inside the content_main.xml
            fragmentTransaction.commit();
        }

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

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        View header=navigationView.getHeaderView(0);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {

                txtLogOut = (TextView) findViewById(R.id.nav_logout_menu);

                int id = item.getItemId();

                if (id == R.id.nav_deposit) {
                    // Handle the preference  action
                    AccountsFragment accounts= new AccountsFragment();
                    FragmentManager manager= getSupportFragmentManager();
                    manager.beginTransaction()
                            .replace(R.id.relativelayout_for_fragment, accounts)
                            .commit();

                    Toast.makeText(MainActivity.this, "Deposit Accounts", Toast.LENGTH_SHORT).show();

                }else if (id == R.id.nav_receivable) {
                    // Handle the Loan application();
                    ReceivableFragment receivable= new ReceivableFragment();
                    FragmentManager manager= getSupportFragmentManager();
                    manager.beginTransaction()
                            .replace(R.id.relativelayout_for_fragment, receivable)
                            .commit();

                    Toast.makeText(MainActivity.this, "AR and Loan Accounts", Toast.LENGTH_SHORT).show();

                }else if (id == R.id.nav_apply_loan_menu) {
                    // Handle the Loan application();
                    LoanAppFragment loan_app= new LoanAppFragment();
                    FragmentManager manager= getSupportFragmentManager();
                    manager.beginTransaction()
                            .replace(R.id.relativelayout_for_fragment, loan_app)
                            .commit();

                    Toast.makeText(MainActivity.this, "This module is under developement", Toast.LENGTH_SHORT).show();
                }else if (id == R.id.nav_logout_menu) {
                    // Handle the About action
                    logoutUser();
                    //Toast.makeText(MainActivity.this, "successfully Logout", Toast.LENGTH_LONG).show();
                }

                DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                drawer.closeDrawer(GravityCompat.START);
                return true;
            }
        });

        nav_header_name = (TextView) header.findViewById(R.id.nav_name);
        nav_header_email = (TextView) header.findViewById(R.id.nav_email);

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

        // session manager
        session = new SessionManager(getApplicationContext());

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

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

        String username = user.get("username");
        String email = user.get("email");
        //Displaying the user info in nav_header_main.xml
        nav_header_name.setText(username);
        nav_header_email.setText(email);

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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);
    }
    /**
     * Logging out the user. Will set isLoggedIn flag to false in shared
     * preferences Clears the user data from sqlite users table
     * */
    private void logoutUser() {
        session.setLogin(false);

        db.deleteUsers();
        db.deleteUserSLDTL();

        // Launching the login activity
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();

        timer = new Timer();
        Log.i("Main", "Invoking logout timer");
        LogOutTimerTask logoutTimeTask = new LogOutTimerTask();
        timer.schedule(logoutTimeTask, 30000); // auto logout in 30secs inactivity
        Log.i("Main", "Log out user due to inactivity");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (timer != null) {
            timer.cancel();
            Log.i("Main", "cancel timer");
            timer = null;
        }
    }

    private class LogOutTimerTask extends TimerTask {

        @Override
        public void run() {
            session.setLogin(false);

            db.deleteUsers();
            db.deleteUserSLDTL();
            //redirect user to login screen
            Intent i = new Intent(MainActivity.this, LoginActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
            finish();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您需要使用Listener / Callback模式来通知您的Activity或Fragment使用适配器的位置。不要直接调用适配器内的片段或活动,因为它会破坏适配器的用途。适配器只应用于显示数据。

要实现模式,首先要创建接口和构造函数,以在适配器中设置侦听器:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

  ...

  private List<Datas> mDataset;

  private ClickListener mListener;

  public interface ClickListener {
    void onItemClicked(YourData yourData);
  }

  public MyAdapter(List<Datas> myDataset, ClickListener listener) {
    mDataset = myDataset;
    mListener = listener;
  }

  ...
}

其次,每当点击项目数据时,请在适配器中使用以下代码告诉监听器:

@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
    ...
    holder.mCardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
         // String sl_desc = mDataset.get(position).getSL_DESC();
         // String actual_balance = mDataset.get(position).getACTUAL_BALANCE();
         //   String sle = mDataset.get(position).getSLE();
         //   String slc = mDataset.get(position).getSLC();
         //   String slt = mDataset.get(position).getSLT();
         //   String ref_no = mDataset.get(position).getREF();
         // Simplify the above to a pojo. We assume the pojo is YourData     
         YourData data = new YourData();
         // set the data from above.

         mListener.onItemClicked(yourData);
    });
}

第三,你需要在Activity / Fragment中使用适配器设置监听器:

 MyAdapter.ClickListener listener = new MyAdapter.ClickListener() {
   @Override 
   public void onItemClicked(YourData yourData) {
     // Do something with the data here.
   }
 };

 MyAdapter adapter = new MyAdapter(db.getUserSLARLoans(), listener);
 rv.setAdapter(adapter);

您需要在上面的onItemClicked()方法中处理侦听器中的数据。

答案 1 :(得分:0)

尝试使用构造函数传递getFragmentManager,然后在项目行中使用容器视图替换视图。

//constructor
public MyAdapter(FragmentManager fragment, List<Datas> myDataset) {
    mDataset = myDataset;
    mFragment  = fragment;
}

public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    public CardView mCardView;
    public TextView account_type;
    public TextView accnt_description;
    public TextView balance_label;
    public TextView account_balance;

    public MyViewHolder(View v){
            super(v);

            mCardView = (CardView) v.findViewById(R.id.card_view);

            account_type = (TextView) v.findViewById(R.id.lblShareCapital);
            balance_label = (TextView) v.findViewById(R.id.lblAvailableBalance);

            accnt_description = (TextView) v.findViewById(R.id.sl_desc);
            account_balance = (TextView) v.findViewById(R.id.actual_balance);
            mCardView.setOnClickListener(this)
        }
    @Override
    public void onClick(View view){
        mFragment.beginTransaction().replace(R.id.containerRow,new MyFragment()).commit();
    }
}

//note this is not tested code.