使用降低音量的硬件键从RecyclerView中选择项目

时间:2019-01-21 23:23:22

标签: java android

美好的一天。我正在尝试通过RecyclerView中的菜单移动突出显示的选择。这是我的RecyclerView XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".MainActivity"
    tools:showIn = "@layout/activity_main">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical" />

这是我的MainActivity:

public class MainActivity extends AppCompatActivity {

private List<MenuOption> menuOptionList = new ArrayList<>();
private RecyclerView recyclerView;
private RModeAdapter modeAdapter;

private int optionSelected = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    recyclerView = findViewById(R.id.recycler_view);

    modeAdapter = new RModeAdapter(menuOptionList);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));

    recyclerView.setAdapter(modeAdapter);

    prepare();

}

private void prepare() {

    MenuOption option = new MenuOption("OPTION 1");
    menuOptionList.add(option);

    option = new MenuOption("OPTION 2");
    menuOptionList.add(option);

    option = new MenuOption("OPTION 3");
    menuOptionList.add(option);

    option = new MenuOption("OPTION 4");
    menuOptionList.add(option);

    option = new MenuOption("OPTION 5");
    menuOptionList.add(option);

    modeAdapter.notifyDataSetChanged();
}

@Override
public boolean dispatchKeyEvent(KeyEvent event) {

    int action = event.getAction();
    int keyCode = event.getKeyCode();

    switch (keyCode) {
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            if (action == KeyEvent.ACTION_DOWN) {
                //recyclerView.findViewHolderForPosition(optionSelected).itemView.setPressed(true);
                //recyclerView.findViewHolderForAdapterPosition(optionSelected).itemView.setPressed(true);
                //recyclerView.findViewHolderForLayoutPosition(optionSelected).itemView.setPressed(true);
            }
        case KeyEvent.KEYCODE_VOLUME_UP:
            if (action == KeyEvent.ACTION_UP) {

            }
        default:
            return super.dispatchKeyEvent(event);
    }

}

}

正如您在我的dispatchKeyEvent中看到的那样,我尝试了三种方法,但是都没有突出显示RecyclerView元素。如果我仅单击一个项目,则该提示将起作用。

我正在模拟器上进行尝试,这可能是它无法正常工作的原因吗?感谢您的帮助。

编辑:我设法使其与以下行一起使用:   recyclerView.getLayoutManager().findViewByPosition(newOption).setPressed(true);

0 个答案:

没有答案