java - 如何制作像 WhatsApp 聊天 Activity 一样的 RecyclerView?

标签 java android android-recyclerview android-cardview linearlayoutmanager

我构建了一个应用程序,其布局应与 WhatsApp 聊天 Activity 中使用的布局几乎相同。它应该有一个文本输入、相机和视频录制选项。项目应在回收器内居中,当数据集更改时,回收器应滚动到最后添加的项目。当用户单击 Editext 键盘时,应调整 View 大小,向上移动回收器并聚焦于数据集中的最后一项。

对于滚动部分,我使用了 SmoothScrollToPosiotion,但是当包含图像或视频的项目时, View 被切碎,自动滚动也会停止工作。一个奇怪的错误是,当我通过单击 editText 打开键盘时,回收器几乎滚动到最后一个项目,但不完全滚动,只有多次重新打开键盘时,它才会完全显示该项目。

已经尝试过在谷歌上找到的解决方案,但这里没有预期的结果:(

<小时/>

编辑:几乎解决了,我刚刚将 SmoothScrollToposition 移动到每个按钮的 onClickListener 内。现在它不会滚动到最后一项,而是完全滚动到最后一项之前的项目:D

这里有一些代码: (如果需要完整代码,请访问https://github.com/MikeSys/ChatApp)

<小时/>

主 Activity 布局

<android.support.constraint.ConstraintLayout   
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">


<android.support.v7.widget.RecyclerView
    android:background="@drawable/sfondo"
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/linearLayout"
    app:layout_constraintTop_toTopOf="parent"
    />


<LinearLayout
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="55dp"
    app:layout_constraintBottom_toBottomOf="parent"
    android:orientation="horizontal">

    <EditText
        android:layout_gravity="center_vertical"
        android:id="@+id/editText"
        android:layout_width="255dp"
        android:layout_height="55dp"
        android:background="#0003A9F4"
        android:hint="Scrivi"
        android:padding="10dp" />




    <Button
        android:layout_gravity="center_vertical"
        android:id="@+id/camera"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="@drawable/camera"
      />

    <Button
        android:layout_gravity="center_vertical"
        android:id="@+id/video"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="@drawable/video"
        />

    <Button
        android:id="@+id/send"
        android:layout_width="55dp"
        android:layout_height="55dp"
        android:background="@drawable/send" />


</LinearLayout>


</android.support.constraint.ConstraintLayout>
<小时/>

主要 Activity 代码

public class MainActivity extends AppCompatActivity {

private ArrayList<ModelloDati> dati = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private static final String VIDEO_DIRECTORY = "/Chat";
private myAdapter adapter;
public  Uri passUri;

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


    // Variables-----------------------------------------

    final RecyclerView recyclerView = findViewById(R.id.recyclerView);
    Button video = findViewById(R.id.video);
    Button camera = findViewById(R.id.camera);
    Button send = findViewById(R.id.send);
    final EditText editText = findViewById(R.id.editText);


    // Layout Manager------------------------------------------------

    linearLayoutManager = new LinearLayoutManager(MainActivity.this);
    linearLayoutManager.setReverseLayout(true);
    recyclerView.setLayoutManager(linearLayoutManager);


    // Adapter-----------------------------------------

    if(dati.size()> 1){
        adapter =  new myAdapter(dati, this);
        //Removed SmoothScroll form here
        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);

    }

    else{
        Collections.reverse(dati);
        adapter =  new myAdapter(dati,this);
        recyclerView.setAdapter(adapter);
    }


    // Click Listener Video button---------------------------------------------
    video.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            startActivityForResult(intent,0);
            //Added here SmotthScroll
            recyclerView.smoothScrollToPosition(dati.size());
        }
    });

    // Click Listener Camera button--------------------------------------------
    camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent,1);
            //Added here SmotthScroll
            recyclerView.smoothScrollToPosition(dati.size());
        }
    });

    // Click Listener Send button----------------------------------------------
    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String string = editText.getText().toString();
            dati.add(new ModelloDati(0,string));
            editText.getText().clear();
            //Added here SmotthScroll
            recyclerView.smoothScrollToPosition(dati.size());
            closeKeyboard();
        }
    });



}

private void closeKeyboard() {
    View view = getCurrentFocus();
    if(view != null){
        InputMethodManager imm =  
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(),0);
    }
}


@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable 
Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode){
        case 0:
            try {
                Uri contentURI = data.getData();
                passUri = contentURI;
                String recordedVideoPath = getPath(contentURI);
                Log.d("frrr", recordedVideoPath);
                saveVideoToInternalStorage(recordedVideoPath);
                dati.add(new ModelloDati(2, contentURI));
            }catch (Throwable o){Log.i("CAM","User aborted action");}
        case 1:
            try {
                Bitmap bitmap = (Bitmap)data.getExtras().get("data");
                dati.add(new ModelloDati(1,bitmap));
            }catch(Throwable o){
                Log.i("CAM","User aborted action");
            }
    }


}

private void saveVideoToInternalStorage (String filePath) {

    File new file;

    try {

        File currentFile = new File(filePath);
        File wallpaperDirectory = new 
File(Environment.getExternalStorageDirectory() + VIDEO_DIRECTORY);
        newfile = new File(wallpaperDirectory, 
Calendar.getInstance().getTimeInMillis() + ".mp4");

        if (!wallpaperDirectory.exists()) {
            wallpaperDirectory.mkdirs();
        }

        if(currentFile.exists()){

            InputStream in = new FileInputStream(currentFile);
            OutputStream out = new FileOutputStream(newfile);

            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;

            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            Log.v("vii", "Video file saved successfully.");
        }else{
            Log.v("vii", "Video saving failed. Source file missing.");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}



public String getPath(Uri uri) {
    String[] projection = { MediaStore.Video.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, 
null);
    if (cursor != null) {
        // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
        // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } else
        return null;
}




}

最佳答案

通过在 onClickListerner 内移动 smoothScrollToPosition 来解决(视频/相机按钮我必须将其移动到 onActivityResult 内)。

<小时/>

更新了主要内容

public class MainActivity extends AppCompatActivity {

private ArrayList<ModelloDati> dati = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private static final String VIDEO_DIRECTORY = "/Chat";
private myAdapter adapter;
private RecyclerView recyclerView;
private VideoView videoView;
public  Uri passUri;

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


    // Variables-----------------------------------------

     recyclerView = findViewById(R.id.recyclerView);
    Button video = findViewById(R.id.video);
    Button camera = findViewById(R.id.camera);
    Button send = findViewById(R.id.send);
    final EditText editText = findViewById(R.id.editText);


    // Layout Manager------------------------------------------------

    linearLayoutManager = new LinearLayoutManager(MainActivity.this);
    linearLayoutManager.setStackFromEnd(true);
    RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setItemAnimator(itemAnimator);


    // Adapter-----------------------------------------

        //adapter.notifyDataSetChanged();
        adapter =  new myAdapter(dati, this);
        recyclerView.setAdapter(adapter);



    // Click Listener Video button----------------------------------------------
    video.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            startActivityForResult(intent,0);
        }
    });

    // Click Listener Camera button----------------------------------------------
    camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent,1);
        }
    });

    // Click Listener Send button------------------------------------------------
    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String string = editText.getText().toString();
            dati.add(new ModelloDati(0,string));
            adapter.notifyItemInserted(dati.size());
            editText.getText().clear();
            recyclerView.smoothScrollToPosition(dati.size());
            closeKeyboard();
        }
    });


}

private void closeKeyboard() {
    View view = getCurrentFocus();
    if(view != null){
        InputMethodManager imm = 
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(),0);
    }
}


@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)  
{
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode){
        case 0:
            try {
                Uri contentURI = data.getData();
                passUri = contentURI;
                String recordedVideoPath = getPath(contentURI);
                saveVideoToInternalStorage(recordedVideoPath);
                dati.add(new ModelloDati(2, contentURI));
                adapter.notifyItemInserted(dati.size());
                recyclerView.smoothScrollToPosition(dati.size());

            }catch (Throwable o){Log.i("CAM","User aborted action");}
        case 1:
            try {
                Bitmap bitmap = (Bitmap)data.getExtras().get("data");
                dati.add(new ModelloDati(1,bitmap));
                adapter.notifyItemInserted(dati.size());
                recyclerView.smoothScrollToPosition(dati.size());


            }catch(Throwable o){
                Log.i("CAM","User aborted action");
            }

    }


}



private void saveVideoToInternalStorage (String filePath) {

    File newfile;

    try {

        File currentFile = new File(filePath);
        File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + 
VIDEO_DIRECTORY);
        newfile = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis()  
 + ".mp4");

        if (!wallpaperDirectory.exists()) {
            wallpaperDirectory.mkdirs();
        }

        if(currentFile.exists()){

            InputStream in = new FileInputStream(currentFile);
            OutputStream out = new FileOutputStream(newfile);

            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;

            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            Log.v("vii", "Video file saved successfully.");
        }else{
            Log.v("vii", "Video saving failed. Source file missing.");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}



public String getPath(Uri uri) {
    String[] projection = { MediaStore.Video.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    if (cursor != null) {
        // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
        // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } else
        return null;
}


}

关于java - 如何制作像 WhatsApp 聊天 Activity 一样的 RecyclerView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56289702/

相关文章:

android - 如何在改造 API 方法中传递 POST 参数?

android - 像 Whatsapp 配置文件一样在滚动上折叠/调整图像大小

java - 在 RecyclerView 的单个界面中使用多个 onClick 方法

Android - 滑动删除 RecyclerView

java - batik 将两个 svg 转换为单个 pdf

java - 有没有另一种方法可以不使用数组的索引来获取索引?前任。不使用数组[5]

android - Android 中的图形二叉树

android - 使用 CURL 从网页获得大量响应后,缓冲区被截断

java - Glassfish 正在执行另一个项目的代码

java - 是否有单个 XPath 表达式可用于在 CDATA 部分中导航 XML?