只是试图将我的 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">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
这里是java代码:
mRecyclerView = findViewById(R.id.recycler_view);
itemLayoutManager = new GridLayoutManager(this, 6);
mRecyclerView.setLayoutManager(itemLayoutManager);
...
mItemAdapter = new ItemAdapter(MainActivity.this, mItemList);
mRecyclerView.setAdapter(mItemAdapter);
Run Code Online (Sandbox Code Playgroud)
当我运行应用程序时,回收器视图左对齐。我究竟需要做什么才能使内容居中,以便左右边距相同,如右侧示例图片所示?
我尝试创建一个在同一个按钮上启动和停止的 MediaPlayer,如下所示:
public void song1(View view){
if(mp.isPlaying() == true){
mp.pause();
}else{
mp = MediaPlayer.create(this, R.raw.song1);
mp.start();
}
}
Run Code Online (Sandbox Code Playgroud)
但我的应用程序崩溃,如果我尝试按一下按钮,所以我souroundet它try和Catch这样的:
public void song1(View view){
try{
if(mp.isPlaying() == true){
mp.pause();
}else{
mp = MediaPlayer.create(this, R.raw.song1);
mp.start();
}
}catch (Exception e){
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
这是 Logcat:
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.media.MediaPlayer.isPlaying()' on a null object reference
W/System.err: at com.example.exampleapp.MainActivity.sound1(MainActivity.java:129)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
W/System.err: at android.view.View.performClick(View.java:5264)
W/System.err: at android.view.View$PerformClick.run(View.java:21297)
W/System.err: at android.os.Handler.handleCallback(Handler.java:743) …Run Code Online (Sandbox Code Playgroud)