我使用RecyclerView
在我的Navigation Drawer
中显示我的抽屉列表项。抽屉列表项的OnClick
,我可以打开不同的活动,但是我希望能够打开将替换主要活动布局的片段。
有办法做到这一点吗?
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {
private LayoutInflater inflater;
private Context context;
List<Information> data = Collections.emptyList();
public AdapterClass(Context context, List<Information> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Information current = data.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
}
@Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
title = (TextView) itemView.findViewById(R.id.listText);
icon = (ImageView) itemView.findViewById(R.id.listIcon);
itemView.setClickable(true);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
final Intent intent;
switch (getPosition()) {
case 0:
intent = new Intent(context, next.class);
break;
case 1:
intent = new Intent(context, next.class);
break;
case 2:
intent = new Intent(context, next.class);
break;
default:
intent = new Intent(context, next.class);
break;
}
context.startActivity(intent);
}
}
};
MainActivity.java
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
}
@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);
}
}
NavigationDrawerFragment.java
public class NavigationDrawerFragment extends Fragment {
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";
private View containerView;
private AdapterClass adapter;
private RecyclerView recyclerView;
public NavigationDrawerFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mFromSavedInstanceState = true;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new AdapterClass(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public static List<Information> getData() {
List<Information> data = new ArrayList<>();
int[] icons = {R.drawable.ic_menu_check, R.drawable.ic_menu_check, R.drawable.ic_menu_check, R.drawable.ic_menu_check};
String[] titles = {"My Cart", "Lotion", "Deodorants", "Gels"};
for (int i = 0; i < titles.length && i < icons.length; i++) {
Information current = new Information();
current.iconId = icons[i];
current.title = titles[i];
data.add(current);
}
return data;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer + "");
}
}
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
@Override
public void run() {
mDrawerToggle.syncState();
}
});
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void saveToPreferences(Context context, String preferenceName, String preferenceValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferenceName, preferenceValue);
editor.apply();
}
public static String readFromPreferences(Context context, String preferenceName, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(preferenceName, defaultValue);
}
}
答案 0 :(得分:22)
如此简化的版本,这是我的onbindVH:
@Override
public void onBindViewHolder(FeedsViewHolder holder, int position) {
final Feed item = mFeeds.get(position);
holder.textView1.setText(item.getText());
holder.imageView.setImageDrawable(mContext.getResources().getDrawable(item.getImage));
holder.imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fragmentJump(item);
}
});
}
这里的fragmentJump:
private void fragmentJump(Feed mItemSelected) {
mFragment = new Fragment2();
mBundle = new Bundle();
mBundle.putParcelable("item_selected_key", mItemSelected);
mFragment.setArguments(mBundle);
switchContent(R.id.frag1, mFragment);
}
这里是适配器上的switchContent:
public void switchContent(int id, Fragment fragment) {
if (mContext == null)
return;
if (mContext instanceof MainActivity) {
MainActivity mainActivity = (MainActivity) mContext;
Fragment frag = fragment;
mainActivity.switchContent(id, frag);
}
}
最后,这里是MainActivity上的switchContent:
public void switchContent(int id, Fragment fragment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(id, fragment, fragment.toString());
ft.addToBackStack(null);
ft.commit();
}
我知道它仍然可以简化,但它可以正常工作。我希望它有所帮助。 :)
答案 1 :(得分:5)
遇到了同样的问题,但是我想向新片段发送两个字符串,该片段将从回收者视图项的textViews中获取。这是我使用的代码。在viewHolder onClick方法中:
@Override
public void onClick(View v) {
String title = titleTextView.getText().toString();
String author = authorTextView.getText().toString(); //two text views defined on top of the viewHolder
Bundle bundle = new Bundle();
bundle.putString("title", title);
bundle.putString("author", author);
BookFragment bookFragment = new BookFragment();
bookFragment.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) v.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, bookFragment).addToBackStack(null).commit();
}
在onCreateView的接收片段中
View view = inflater.inflate(R.layout.fragment_book, container, false);
Bundle bundle = this.getArguments();
if(bundle != null){
String title = bundle.get("title").toString();
String author = bundle.get("author").toString();
}
它奏效了。
答案 2 :(得分:2)
在你的OnBindViewHolder中按如下方式开始,
@Override
public void onClick(View view){
AppCompatActivity activity = (AppCompatActivity) view.getContext();
Fragment myFragment = new MyFragment();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();
}
答案 3 :(得分:-3)
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {
private LayoutInflater inflater;
private Context context;
List<Information> data = Collections.emptyList();
public AdapterClass(Context context, List<Information> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Information current = data.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
}
@Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
title = (TextView) itemView.findViewById(R.id.listText);
icon = (ImageView) itemView.findViewById(R.id.listIcon);
itemView.setClickable(true);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
final Intent intent;
switch (getPosition()) {
case 0:
intent = new Intent(context, next.class);
break;
case 1:
intent = new Intent(context, next.class);
break;
case 2:
intent = new Intent(context, next.class);
break;
default:
intent = new Intent(context, next.class);
break;
}
context.startActivity(intent);
}
}
};