Android: Selecting an Image from sdcard and displaying it in Fragment - android-layout

I'm working with fragments (API 4.1) and I want to let the user press a button, access his/her gallery, select an image, and have that image display an imageview on the original fragment where the button appeared. I'm using the following code:
public class FillBox1Frag extends Fragment {
Button addPics, placeBox;
ImageView imgView;
Bitmap b;
Uri photoUri;
LinearLayout fillBoxLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
if (container == null) {
return null;
}
fillBoxLayout = (LinearLayout) inflater.inflate(R.layout.fillbox1_frag,
container, false);
newBin = new Bin();
addPics = (Button) fillBoxLayout.findViewById(R.id.bPics);
imgView = (ImageView) fillBoxLayout.findViewById(R.id.imageView1);
addPics.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent picChooser = new Intent(Intent.ACTION_GET_CONTENT,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
picChooser.setType("image/*");
startActivityForResult(picChooser, 12345);
}
});
return fillBoxLayout;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 12345:
if (resultCode == 12345) {
photoUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = FillBox1Frag.this.getActivity()
.getContentResolver()
.query(photoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
b = BitmapFactory.decodeFile(filePath);
imgView.setImageBitmap(b);
}
}
}
I access the Gallery, but upon selection, it just returns to the original fragment and doesn't display the image. Here's my XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fillbox"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="fillbox" >
<Button
android:id="#+id/bPics"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="89dp"
android:background="#drawable/buttonpics" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
I've found plenty of answers dealing with a similar question, but nothing that has been able to help me with how to create this process using fragments. Any ideas on how to get my selected image to appear in the ImageView? Thanks for the help!

Related

OnScrollChangeListener for ScrollView

I would like to make a function to intercept a certain scroll at the top of the view.
to do this I'm trying to use OnScrollChangeListener.
My view contains a ScrollView
<ScrollView 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:id="#+id/scrollViewClientPhysique"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/fond"
tools:context=".client.FicheClient">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">**strong text**
and I initialize addOnScrollChangedListener in a function I call inside onCreateView
fun initializeInfiniteScroll(){
val scrollView = myView.findViewById<View>(R.id.scrollViewClientPhysique) as ScrollView
scrollView.viewTreeObserver.addOnScrollChangedListener {
if (scrollView != null) {
val view = scrollView.getChildAt(scrollView.childCount - 1)
val diff =
view.bottom + scrollView.paddingBottom - (scrollView.height + scrollView.scrollY)
if (diff == 0) {
// do stuff
}
}
}
}
but when when I scroll the view I don't enter addOnScrollChangedListener to intercept how many dp the scroll is.
what am I doing wrong?
Please update your ScrollChangedListener as mentioned below.
public class MainActivity extends AppCompatActivity implements View.OnTouchListener,
ViewTreeObserver.OnScrollChangedListener {
ScrollView scrollView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scrollView = findViewById(R.id.scrollView);
scrollView.setOnTouchListener(this);
scrollView.getViewTreeObserver().addOnScrollChangedListener(this);
}
public void onScrollChanged(){
View view = scrollView.getChildAt(scrollView.getChildCount() - 1);
int topDetector = scrollView.getScrollY();
int bottomDetector = view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY());
//TODO: Just added for testing/understanding. Please add/replace your own logic..
if(bottomDetector == 0 ){
Toast.makeText(this,"Scroll View bottom reached",Toast.LENGTH_SHORT).show();
}
if(topDetector <= 0){
Toast.makeText(this,"Scroll View top reached",Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
}

How to turn xml layout to PDF report?

enter image description hereI already create a report layout in XML in android studio. I need to transform the layout to PDF format after clicking on Generate button on the layout. Are there any possibilities to make it possible? Thank you in advance!
I want to convert that data form the layout into pdf in that exact table
For generating pdf:
-> Add permission for reading and writing in the External Storage in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
-> On click of generate pdf button, Check Permissions are granted or not.
Try this code on click of button:
/*check read/write storage permission is granted or not*/
if(checkPermissionGranted()){
convertToPdf();
}else{
requestPermission();
}
checkPermissionGranted() method:
private boolean checkPermissionGranted(){
if((ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
&& (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
// Permission has already been granted
return true;
} else {
return false;
}
}
requestPermission() method:
private void requestPermission(){
ActivityCompat.requestPermissions(LayoutToPdfActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
Override onActivityResult metod:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
convertToPdf();
}else{
requestPermission();
}
}
}
convertToPdf() method:
private void convertToPdf(){
PdfGenerator pdfGenerator = new PdfGenerator(LayoutToPdfActivity.this);
// llLayoutToPdfMain is variable of that view which convert to PDF
Bitmap bitmap = pdfGenerator.getViewScreenShot(llLayoutToPdfMain);
pdfGenerator.saveImageToPDF(llLayoutToPdfMain, bitmap);
}
PdfGenerator Class:
public class PdfGenerator {
private static String TAG= PdfGenerator.class.getSimpleName();
private File mFile;
private Context mContext;
public PdfGenerator(Context context) {
this.mContext = context;
}
/*save image to pdf*/
public void saveImageToPDF(View title, Bitmap bitmap) {
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS);
if(!path.exists()) {
path.mkdirs();
}
try {
mFile = new File(path + "/", System.currentTimeMillis() + ".pdf");
if (!mFile.exists()) {
int height = bitmap.getHeight();
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), height, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
title.draw(canvas);
canvas.drawBitmap(bitmap, null, new Rect(0, bitmap.getHeight(), bitmap.getWidth(), bitmap.getHeight()), null);
document.finishPage(page);
try {
mFile.createNewFile();
OutputStream out = new FileOutputStream(mFile);
document.writeTo(out);
document.close();
out.close();
Log.e(TAG,"Pdf Saved at:"+mFile.getAbsolutePath());
Toast.makeText(mContext,"Pdf Saved at:"+mFile.getAbsolutePath(),Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/*method for generating bitmap from LinearLayout, RelativeLayout etc.*/
public Bitmap getViewScreenShot(View view)
{
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bm = view.getDrawingCache();
return bm;
}
/*method for generating bitmap from ScrollView, NestedScrollView*/
public Bitmap getScrollViewScreenShot(ScrollView nestedScrollView)
{
int totalHeight = nestedScrollView.getChildAt(0).getHeight();
int totalWidth = nestedScrollView.getChildAt(0).getWidth();
return getBitmapFromView(nestedScrollView,totalHeight,totalWidth);
}
public Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {
Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth,totalHeight , Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
}
Edit
Please follow below xml code snippet for layout designing:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:gravity="center"
tools:context=".views.activities.LayoutToPdfActivity">
<androidx.core.widget.NestedScrollView
android:id="#+id/nestedLayoutToPdf"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/btnGeneratePdf">
<LinearLayout
android:id="#+id/llLayoutToPdfMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TableLayout>
<TableLayout
android:id="#+id/tableLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TableLayout>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
<Button
android:id="#+id/btnGeneratePdf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Generate Pdf"
android:layout_margin="20dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
-> Change in convertToPdf() method
private void convertToPdf() {
PdfGenerator pdfGenerator = new PdfGenerator(LayoutToPdfActivity.this);
Bitmap bitmap = pdfGenerator.getScrollViewScreenShot(nestedLayoutToPdf);
pdfGenerator.saveImageToPDF(llLayoutToPdfMain, bitmap);
}
Note - Please change layout according to your requirement and Change param type to NestedScrollView in getScrollViewScreenShot() method under PdfGenerator Class.
For dynamically adding rows in tableview, check this link

Android Studio, Capture FrameLayout View, While Camera is StopPreview()

This is my CameraView.java (I got it from http://blog.rhesoft.com/)
public class CameraView extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraView(Context context, Camera camera){
super(context);
mCamera = camera;
mCamera.setDisplayOrientation(90);
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try{
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceCreated " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
if(mHolder.getSurface() == null)
return;
try{
mCamera.stopPreview();
} catch (Exception e){
}
try{
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceChanged " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}}
and this is my MainActivity.java.
public class MainActivity extends AppCompatActivity {
private Camera mCamera = null;
private CameraView mCameraView = null;
private FrameLayout camera_view;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
mCamera = Camera.open();
//you can use open(int) to use different cameras
} catch (Exception e){
Log.d("ERROR", "Failed to get camera: " + e.getMessage());
}
if(mCamera != null) {
mCameraView = new CameraView(this, mCamera);//create a SurfaceView to show camera data
camera_view = (FrameLayout)findViewById(R.id.camera_view);
camera_view.addView(mCameraView);//add the SurfaceView to the layout
}
//btn to close the application
final ImageButton imgClose = (ImageButton)findViewById(R.id.imgClose);
final ImageButton capImg = (ImageButton) findViewById(R.id.imgCapture);
imgClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imgClose.setVisibility(View.INVISIBLE);
capImg.setVisibility(View.VISIBLE);
mCamera.startPreview();
}
});
capImg.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
mCamera.stopPreview();
imgClose.setVisibility(View.VISIBLE);
capImg.setVisibility(View.INVISIBLE);
}
});
}
#Override
public void onBackPressed(){
System.exit(0);
}}
and this my activity_main.xml.
<FrameLayout
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">
<FrameLayout
android:id="#+id/camera_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgClose"
android:layout_gravity="right|top"
android:background="#android:drawable/ic_menu_close_clear_cancel"
android:padding="20dp"
android:visibility="invisible" />
<ImageButton
android:layout_width="98dp"
android:layout_height="98dp"
android:id="#+id/imgCapture"
android:layout_gravity="center_horizontal|bottom"
android:background="#android:drawable/ic_menu_camera"
android:padding="20dp"/>
Can I capture this FrameLayout preview as image or do some programing with that preview like delete red color? Can you give me some clue?
So if I understand correctly, you wish to get the image data that is shown when you stop the preview? If you so you can mCamera.takePicture() method. It takes 3 parameters, all of which are useful callbacks. Here is something I recently did to show you.
btn_Capture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCamera == null)
return;
mCamera.takePicture(null, null, mPicture);
}
});
This is my button click listener which is a floating image button (any button will work just fine). The third parameter is a callback that returns an array of pixels that you can convert into a bitmap.
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
mCamera.stopPreview();
Bitmap bMap = BitmapFactory.decodeByteArray(data, 0, data.length);
preview.removeView(mPreview);
img_Captured.setImageBitmap(bMap);
}
};
This is the callback which I passed in the takePicture() method. byte[] data is the image that you are trying to get. As you can see I converted it into a bitmap and displayed it to an ImageView after removing the surfaceview (which holds the camera preview). Just a note, the takePicture() method stops the preview automatically so don't stop the preview before taking the photo. You can do it how I did it in the callback. Also, if you want to take another photo, you can start the preview again.
I hope this helps!! Let me know if I left anything out! By the way, it is all documented on the Android Developer site.
http://developer.android.com/training/camera/cameradirect.html#TaskTakePicture

save last Selected or Captured image in imageView

how can save last Selected or Captured image in imageView? so when user close program and come back again not need to set or take image again?
xml fle:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="5dp" >
<Button
android:id="#+id/btnSelectPhoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Photo" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<ImageView
android:id="#+id/viewImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/camera" />
</LinearLayout>
</LinearLayout>
java file :
public class MainActivity extends Activity {
ImageView viewImage;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button)findViewById(R.id.btnSelectPhoto);
viewImage=(ImageView)findViewById(R.id.viewImage);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds options to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........", picturePath+"");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
this code coped from :
http://www.c-sharpcorner.com/UploadFile/e14021/capture-image-from-camera-and-selecting-image-from-gallery-o/
Thank you very mach
You could save the image(path) as a preference in the OnPause() and load it again in OnResume(). With that path, you can set the image in ImageView again. So it's 2 steps.
More info on the lifecylce of an Android application: http://developer.android.com/training/basics/activity-lifecycle/pausing.html

How to Show Different Layouts inside Fragments

I am working with two fragments in Android Honeycomb (Tab). In the left is a ListView and in the right is a preview of the item selected from the list. When one of the buttons is clicked, I want to show different layouts on the left. How is it possible?
Thanks in advance.
You can do this, I made the same thing with use of these links, here is my code which I am sharing with you in the hope that it will be helpful for you... You will first have to create 4 layouts. 2 of which will be for landscape mode, one for portrait mode and another for tablets. You have to create a couple more folders for layouts and their name should be like layout-xlarge and layout-xlarge-port, this way you can create fragments for both mobile devices and tablets.
MasterFragment Activity:
public class MasterFragment extends ListFragment {
Boolean isDualPane;
int position;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<String> parkNames = new ArrayList<String>();
for (Park park : Resort.PARKS) {
parkNames.add(park.getName());
}
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, parkNames));
View detailFrame = getActivity().findViewById(R.id.detail);
isDualPane = detailFrame != null && detailFrame.getVisibility() == View.VISIBLE;
if (savedInstanceState != null) {
position = savedInstanceState.getInt("position", 0);
}
if (isDualPane) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
showDetail(position);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("position", position);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetail(position);
}
void showDetail(int position) {
this.position = position;
if (isDualPane) {
getListView().setItemChecked(position, true);
DetailFragment detailFragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detail);
if (detailFragment == null || detailFragment.getIndex() != position) {
detailFragment = new DetailFragment(position);
FragmentTransaction ft = getFragmentManager()
.beginTransaction();
ft.replace(R.id.detail, detailFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
Intent intent = new Intent();
intent.setClass(getActivity(), DetailActivity.class);
intent.putExtra("position", position);
startActivity(intent);
}
}
}
Second Activity - DetailFragment Activity:
public class DetailActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_act);
Bundle bundle = getIntent().getExtras();
int position = bundle.getInt("position");
System.out.println("RR : position is : " + position);
Integer[] images = { R.drawable.pic1, R.drawable.pic2, R.drawable.pic3,
R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
R.drawable.pic7, R.drawable.pic8, R.drawable.pic9,
R.drawable.pic10, R.drawable.pic11, R.drawable.pic12,
R.drawable.pic13 };
final ImageView imgview = (ImageView) findViewById(R.id.imageView1);
imgview.setImageResource(images[position]);
// DetailFragment detailFragment = new DetailFragment(position);
// FragmentManager fm = getSupportFragmentManager();
// FragmentTransaction ft =fm.beginTransaction();
// ft.add(android.R.id.content, detailFragment).commit();
}
}
Now you have to create a third activity, MasterGridActivity for my images which I am using for showing in fragment in GridView.
public class MasterGridActivity extends Fragment {
Boolean isDualPane;
GridView gridView;
ListView listView;
int position;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.gridview, container, false);
gridView = (GridView) view.findViewById(R.id.gridViewImage);
gridView.setAdapter(new MyAdapter(view.getContext()));
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
View detailFrame = getActivity().findViewById(R.id.detail);
isDualPane = detailFrame != null && detailFrame.getVisibility() == View.VISIBLE;
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
if (!isDualPane) {
Intent intent = new Intent();
intent.setClass(getActivity(), DetailActivity.class);
intent.putExtra("position", pos);
startActivity(intent);
} else {
DetailFragment detailFragment = (DetailFragment) getFragmentManager().findFragmentById(R.id.detail);
if (detailFragment == null || detailFragment.getIndex() != pos) {
detailFragment = new DetailFragment(pos);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.detail, detailFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
}
}
});
super.onActivityCreated(savedInstanceState);
}
}
Now here is my image adapter - MyAdapter - for my images which extends a BaseAdapter.
public class MyAdapter extends BaseAdapter {
private Context mContext;
public MyAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
static Integer[] mThumbIds = { R.drawable.pic1, R.drawable.pic2,
R.drawable.pic3, R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
R.drawable.pic7, R.drawable.pic8, R.drawable.pic9,
R.drawable.pic10, R.drawable.pic11, R.drawable.pic12,
R.drawable.pic13,
};
}
Now I am sharing the XML files for these fragments.
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:id="#+id/master"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="org.fragment.MasterGridActivity" />
</LinearLayout>
gridview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridViewImage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:columnWidth="90dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth" />
</LinearLayout>
detail_fragment.xml: This XML is for showing the detail in another fragment.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="8dp" />
</LinearLayout>
</ScrollView>
detail_act.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
Make the same XML for landscape mode and for tablets. It's working fine for me. Hope it will helpful for you.
You need to define an event callback to the activity activity callback. That is, your left fragment must first notify the container activity that an event occurred (i.e. one of the list items were selected). The container activity will then pass this information to the right fragment, which will then update its UI accordingly.
I could explain this in more detail, but there are several tutorials on the internet that teach just that. I suggest you read through some of them, as the concept will make a lot more sense once you do.

Resources