SetOnItemClickListener无法在Fragment

时间:2017-05-28 06:46:39

标签: android android-layout android-fragments

我正在使用RecycleView来显示名称和说明列表。我正在使用Fragment来查看所需的布局。现在,我想打开新的活动onItemClick。我已在SetOnItemClickListener内声明Fragment,即在“查看onCreateView”中。但它没有用。这是我的代码:

这是我的java类:

public class TabsHeaderActivity extends AppCompatActivity {
private static final String TAG = TabsHeaderActivity.class.getSimpleName();

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

    final Toolbar toolbar = (Toolbar) findViewById(R.id.htab_toolbar);
    setSupportActionBar(toolbar);
    if (getSupportActionBar() != null) getSupportActionBar().setTitle("TECHNOLOGY");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.htab_viewpager);
    setupViewPager(viewPager);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.htab_tabs);
    tabLayout.setupWithViewPager(viewPager);

    final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.htab_collapse_toolbar);

    try {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.header);
        Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
            @SuppressWarnings("ResourceType")
            @Override
            public void onGenerated(Palette palette) {

                int vibrantColor = palette.getVibrantColor(R.color.primary_500);
                int vibrantDarkColor = palette.getDarkVibrantColor(R.color.primary_700);
                collapsingToolbarLayout.setContentScrimColor(vibrantColor);
                collapsingToolbarLayout.setStatusBarScrimColor(vibrantDarkColor);
            }
        });

    } catch (Exception e) {
        // if Bitmap fetch fails, fallback to primary colors
        Log.e(TAG, "onCreate: failed to create bitmap from background", e.fillInStackTrace());
        collapsingToolbarLayout.setContentScrimColor(
                ContextCompat.getColor(this, R.color.primary_500)
        );
        collapsingToolbarLayout.setStatusBarScrimColor(
                ContextCompat.getColor(this, R.color.primary_700)
        );
    }

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {

            viewPager.setCurrentItem(tab.getPosition());
            Log.d(TAG, "onTabSelected: pos: " + tab.getPosition());

            switch (tab.getPosition()) {
                case 0:
                    break;
            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new DummyFragment(
            ContextCompat.getColor(this, R.color.cyan_50)), "Cyan");
    adapter.addFrag(new DummyFragment(
            ContextCompat.getColor(this, R.color.amber_50)), "Amber");
    adapter.addFrag(new DummyFragment(
            ContextCompat.getColor(this, R.color.purple_50)), "Purple");
    adapter.addFrag(new DummyFragment(
            ContextCompat.getColor(this, R.color.grey)), "Grey");
    viewPager.setAdapter(adapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    final MenuItem searchItem = menu.findItem(R.id.menuSearch);
    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){

        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return true;
        }
    });

    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

private static class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

public static class DummyFragment extends Fragment {
    int color;
    Intent intent;

    public DummyFragment() {
    }

    @SuppressLint("ValidFragment")
    public DummyFragment(int color) {
        this.color = color;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dummy_fragment, container, false);

        final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
        frameLayout.setBackgroundColor(color);

        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setHasFixedSize(true);

        DessertAdapter adapter = new DessertAdapter(getContext());
        recyclerView.setAdapter(adapter);

        adapter.SetOnItemClickListener(new DessertAdapter.OnItemClickListener(){

            @Override
            public void onItemClick(View view, int position) {
                switch (position) {
                    case 3:
                        intent = new Intent(view.getContext(), LaunchScreenActivity.class);
                        startActivity(intent);
                }
            }
        });

        return view;
    }
}
}

这是我的Adapter类:

public class DessertAdapter extends RecyclerView.Adapter<DessertAdapter.DessertVh> {

private List<Dessert> desserts = new ArrayList<>();
OnItemClickListener clickListener;
private Context context;

public DessertAdapter(Context context) {
    this.context = context;

    desserts = Dessert.prepareDesserts(
            context.getResources().getStringArray(R.array.dessert_names),
            context.getResources().getStringArray(R.array.dessert_descriptions));
}

@Override
public DessertVh onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.item_dessert, parent, false);
    return new DessertAdapter.DessertVh(view);
}

@Override
public void onBindViewHolder(DessertVh holder, int position) {
    Dessert dessert = desserts.get(position);

    holder.mName.setText(dessert.getName());
    holder.mDescription.setText(dessert.getDescription());
    holder.mFirstLetter.setText(String.valueOf(dessert.getFirstLetter()));

}

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

public class DessertVh extends RecyclerView.ViewHolder implements View.OnClickListener{

    private TextView mName;
    private TextView mDescription;
    private TextView mFirstLetter;

    public DessertVh(View itemView) {
        super(itemView);

        mName = (TextView) itemView.findViewById(R.id.txt_name);
        mDescription = (TextView) itemView.findViewById(R.id.txt_desc);
        mFirstLetter = (TextView) itemView.findViewById(R.id.txt_firstletter);
    }

    @Override
    public void onClick(View v) {
        clickListener.onItemClick(v, getPosition());
    }
}

public interface OnItemClickListener {
    public void onItemClick(View view, int position);
}

public void SetOnItemClickListener(final OnItemClickListener itemClickListener) {
    this.clickListener = itemClickListener;
}

我不确定我做错了什么。我在调试器模式下检查过它。我把断点放在了一行:

adapter.SetOnItemClickListener(new DessertAdapter.OnItemClickListener(){

现在,当我的Activity正在加载时,调试器出现在这一行上,但不会进入它。但是,当我点击某些内容时,调试器甚至不会出现在这一行上,这意味着当我点击某个项目时,SetOnItemClickListener不会被触发。

我的xml代码是:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@+id/dummyfrag_bg"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:background="@color/bg_light">

<android.support.v7.widget.RecyclerView
    android:id="@+id/dummyfrag_scrollableview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:paddingBottom="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_horizontal_margin" />
</FrameLayout>

1 个答案:

答案 0 :(得分:0)

嗯,你实现了一个普通的点击监听器

DessertVh extends RecyclerView.ViewHolder implements View.OnClickListener

但你从来没有设定它。

public DessertVh(View itemView) {
    super(itemView);

    mName = (TextView) itemView.findViewById(R.id.txt_name);
    mDescription = (TextView) itemView.findViewById(R.id.txt_desc);
    mFirstLetter = (TextView) itemView.findViewById(R.id.txt_firstletter);
}

你忘记了itemView.setOnClickListener(this)吗?