I am trying to take a screenshot of a LinearLayout that has an image view inside and take a screenshot of that image, but when I press the button it takes a screenshot of the entire screen and I would like to save just the LinearLayout with the image inside since I've been looking for a solution for almost 2 days
The code used:
LinearLayout ll;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_meme, container, false);
Button downloadButton = view.findViewById(R.id.downloadButton);
ll = view.findViewById(R.id.rootView);
downloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
}
});
return view;
}
public Bitmap takeScreenshot() {
View rootView=ll.getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
try {
FileOutputStream fos = new FileOutputStream(new File(Environment
.getExternalStorageDirectory().toString(), "SCREEN"
+ System.currentTimeMillis() + ".png"));
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".fragments.MemesFragment">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ProfileActivity">
<Button
android:id="@+id/downloadButton"
android:layout_width="41dp"
android:layout_height="41dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:drawableBottom="@drawable/download"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="@+id/rootView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/memeRandomView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
tools:layout_editor_absoluteX="0dp">
</androidx.viewpager2.widget.ViewPager2>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>