在Android

时间:2017-04-16 08:39:25

标签: java android

我的recyclerview位于左抽屉片段内。选择一个项目后,当我向下滚动时,其他项目也会被错误地选中。我需要一次只选择一个项目。我的recyclerview适配器在这里

    import android.support.v7.widget.RecyclerView;  
import android.util.Log;  
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

import static android.content.ContentValues.TAG;


public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.ViewHolder> {

private List<NavigationItem> mData;
private NavigationDrawerCallbacks mNavigationDrawerCallbacks;
private View mSelectedView;
private int mSelectedPosition;

public NavigationDrawerAdapter(List<NavigationItem> data) {
    mData = data;
}

public NavigationDrawerCallbacks getNavigationDrawerCallbacks() {
    return mNavigationDrawerCallbacks;
}

public void setNavigationDrawerCallbacks(NavigationDrawerCallbacks navigationDrawerCallbacks) {
    mNavigationDrawerCallbacks = navigationDrawerCallbacks;
}

@Override
public NavigationDrawerAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.drawer_row, viewGroup, false);
    final ViewHolder viewHolder = new ViewHolder(v);
    viewHolder.itemView.setClickable(true);
    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                                               @Override
                                               public void onClick(View v) {
                                                   if (mSelectedView != null) {
                                                       mSelectedView.setSelected(false);
                                                   }
                                                   mSelectedPosition = viewHolder.getAdapterPosition();
                                                   v.setSelected(true);
                                                   mSelectedView = v;
                                                   if (mNavigationDrawerCallbacks != null)
                                                       mNavigationDrawerCallbacks.onNavigationDrawerItemSelected(viewHolder.getAdapterPosition());
                                               }
                                           }
    );
    viewHolder.itemView.setBackgroundResource(R.drawable.row_selector);
    return viewHolder;
}

@Override
public void onBindViewHolder(NavigationDrawerAdapter.ViewHolder viewHolder, int i) {
    viewHolder.textView.setText(mData.get(i).getText());
    viewHolder.textView.setCompoundDrawablesWithIntrinsicBounds(mData.get(i).getDrawable(), null, null, null);
    if (mSelectedPosition == i) {
        if (mSelectedView != null) {
            mSelectedView.setSelected(false);

        }

        mSelectedPosition = i;
        mSelectedView = viewHolder.itemView;
        mSelectedView.setSelected(true);
    } 
}


public void selectPosition(int position) {
    mSelectedPosition = position;
    notifyItemChanged(position);
}

@Override
public int getItemCount() {
    return mData != null ? mData.size() : 0;
}

public static class ViewHolder extends RecyclerView.ViewHolder {
    public TextView textView;

    public ViewHolder(View itemView) {
        super(itemView);
        textView = (TextView) itemView.findViewById(R.id.item_name);
    }
}

}

这是片段

import android.app.Activity; 
import android.app.Fragment;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import static android.content.ContentValues.TAG;
import static android.content.Context.MODE_PRIVATE;

/**
 * Fragment used for managing interactions for and presentation of a         navigation drawer.
 * See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
 * design guidelines</a> for a complete explanation of the behaviors implemented here.
 */
public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks {

/**
 * Remember the position of the selected item.
 */
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

/**
 * Per the design guidelines, you should show the drawer on launch until the user manually
 * expands it. This shared preference tracks this.
 */
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";

/**
 * A pointer to the current callbacks instance (the Activity).
 */
private NavigationDrawerCallbacks mCallbacks;

/**
 * Helper component that ties the action bar to the navigation drawer.
 */
private ActionBarDrawerToggle mActionBarDrawerToggle;

private DrawerLayout mDrawerLayout;
private RecyclerView mDrawerList;
private View mFragmentContainerView;

private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;

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

    // Read in the flag indicating whether or not the user has demonstrated awareness of the
    // drawer. See PREF_USER_LEARNED_DRAWER for details.
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

    if (savedInstanceState != null) {
        mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
        mFromSavedInstanceState = true;
    }
    SharedPreferences prefs = this.getActivity().getSharedPreferences("sub", MODE_PRIVATE);
    mCurrentSelectedPosition = prefs.getInt("c", 0);



}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
    mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    mDrawerList.setLayoutManager(layoutManager);
    mDrawerList.setHasFixedSize(true);

    SharedPreferences prefs = this.getActivity().getSharedPreferences("sem", MODE_PRIVATE);
    int b = prefs.getInt("b", 0);


    List<NavigationItem> navigationItems;
    if(b==0) {
        navigationItems = getMenu();
    }
    else{
        navigationItems = getMenu1();
    }
    NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems);
    adapter.setNavigationDrawerCallbacks(this);
    mDrawerList.setAdapter(adapter);
    selectItem(mCurrentSelectedPosition);


    return view;
}

public boolean isDrawerOpen() {
    return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}

public ActionBarDrawerToggle getActionBarDrawerToggle() {
    return mActionBarDrawerToggle;
}

public DrawerLayout getDrawerLayout() {
    return mDrawerLayout;
}

@Override
public void onNavigationDrawerItemSelected(int position) {
    selectItem(position);
}

public List<NavigationItem> getMenu() {
    List<NavigationItem> items = new ArrayList<NavigationItem>();
    items.add(new NavigationItem("Linear Algebra & Complex Analysis", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Mechanics of Solids", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Fluid Mechanics I", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Engineering Geology", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Surveying", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Business Economics", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Life Skills", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Civil Engineering Drafting Lab", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Surveying Lab", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("About", getResources().getDrawable(R.drawable.ic_action_name)));
    return items;
}
public List<NavigationItem> getMenu1() {
    List<NavigationItem> items = new ArrayList<NavigationItem>();
    items.add(new NavigationItem("Probability Distributions, Transforms and Numerical Methods", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Structural Analysis I", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Construction Technology", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Fluid Mechanics II", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Geotechnical Engineering I", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Life Skills", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Business Economics", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Materials Testing Lab I", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("Fluid Mechanics Lab", getResources().getDrawable(R.drawable.ic_menu_check2)));
    items.add(new NavigationItem("About", getResources().getDrawable(R.drawable.ic_action_name)));
    return items;
}

/**
 * Users of this fragment must call this method to set up the navigation drawer interactions.
 *
 * @param fragmentId   The android:id of this fragment in its activity's layout.
 * @param drawerLayout The DrawerLayout containing this fragment's UI.
 * @param toolbar      The Toolbar of the activity.
 */
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
    mFragmentContainerView = getActivity().findViewById(fragmentId);
    mDrawerLayout = drawerLayout;

    mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.myPrimaryDarkColor));

    mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);

            if (!isAdded()) return;

            getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            if (!isAdded()) return;
            if (!mUserLearnedDrawer) {
                mUserLearnedDrawer = true;
                SharedPreferences sp = PreferenceManager
                        .getDefaultSharedPreferences(getActivity());
                sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
            }
            getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }
    };

    // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
    // per the navigation drawer design guidelines.
    if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
        //mDrawerLayout.openDrawer(mFragmentContainerView);
    }

    // Defer code dependent on restoration of previous instance state.
    mDrawerLayout.post(new Runnable() {
        @Override
        public void run() {
            mActionBarDrawerToggle.syncState();
        }
    });

    mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}

private void selectItem(int position) {
    //Toast.makeText(this.getActivity(), "Menu " + String.valueOf(position), Toast.LENGTH_SHORT).show();
    mCurrentSelectedPosition = position;
    if (mDrawerLayout != null) {

        mDrawerLayout.closeDrawer(mFragmentContainerView);
    }
    if (mCallbacks != null) {
        mCallbacks.onNavigationDrawerItemSelected(position);
    }
    ((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
}

public void openDrawer() {
    mDrawerLayout.openDrawer(mFragmentContainerView);
}

public void closeDrawer() {
    mDrawerLayout.closeDrawer(mFragmentContainerView);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mCallbacks = (NavigationDrawerCallbacks) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mCallbacks = null;
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Forward the new configuration the drawer toggle component.
    mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}


public void zxc(int a){

    Log.d(TAG, "jlk "+mCurrentSelectedPosition);

    List<NavigationItem> navigationItems;
    if(a==0) {
        navigationItems = getMenu();
    }
    else{
        navigationItems = getMenu1();
    }
    NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems);
    adapter.setNavigationDrawerCallbacks(this);
    mDrawerList.setAdapter(adapter);

    SharedPreferences.Editor editor = this.getActivity().getSharedPreferences("sub",MODE_PRIVATE).edit();
    editor.putInt("c", 0);
    editor.commit();
    mCurrentSelectedPosition=0;
    selectItem(mCurrentSelectedPosition);
}

}

2 个答案:

答案 0 :(得分:0)

回收器视图正在重复使用视图,因此除了onClickListener之外,还需要说明在绘制持有者时单击/取消单击所选视图的时间。您还可以发布更多相关代码,例如活动/抽屉中的代码以获取更多详细信息希望这有帮助:)

答案 1 :(得分:0)

请按照以下步骤操作。

  • 在适配器中为LayoutManager创建一个字段。
  

私人LinearLayoutManager layoutManager;

  • 为该经理创建一个setter,并从Activity / Fragment
  • 设置它

public void setLayoutManager(LinearLayoutManager layoutManager) { this.layoutManager = layoutManager; }

  • 使用此

    更改 selectPosition(int position)方法

    public void selectPosition(int position) { mSelectedPosition = position; notifyItemRangeChanged(layoutManager.findFirstVisibleItemPosition(), getItemCount() - layoutManager.findFirstVisibleItemPosition() - 1); }

  • 在项目视图中点击更改 mSelectedPosition = viewHolder.getAdapterPosition(); selectPosition(viewHolder.getAdapterPosition())

  • 最后使用 if(mSelectedPosition == viewHolder.getAdapterPosition())更改 if(mSelectedPosition == i)。因为不可靠。

希望,按照上述步骤,您的问题将得到解决。