Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Wednesday, June 16, 2021

Android 10: Enable the built-in screen recorder


 

Note: This may NOT be supported by all phones.

 

1. Turn on the Developer Options on the phone. (Google it to see how to...)

2. Connection the phone to the computer.

3. On the computer, install the "adb" application.

4. On the computer, open a terminal, run command "adb devices" to verify that the phone is connected correctly.

5. On the computer, run command "adb shell settings put global settings_screenrecord_long_press true" to enable the screen recorder on the phone.

6. On the phone, long press the power butter to bring up the menu: Power off/Restart/Screenshot

7. Long press the "Screenshot" item in the above menu. A "Start Recording" dialog is popped up.

8. Click on the "Start Recording" button to start.


Monday, January 27, 2020

Speakout and Android Oreo


When inserting the Speakout SIM into an Android Oreo phone, the APN settings are pushed from the Rogers Network as "ltemobile.apn".

As Speakout does not support LTE, that APN setting does not work. And APN settings are locked for Speakout SIM. The "Add APN" button is not there and the only available APN is grayed out that we cannot change it.

The workaround is to use an unrestricted SIM to generate an APN profile.

Steps:

1. With Speakout SIM in, change the Network Operator to "Speakout 3G" (Settings / Network&Internet / Mobile network / Network operators) (However, I am not sure if this step is necessary. But in my case, it didn't work when on Speakout 4G.)

2. Power off the phone. Remove Speakout SIM.

3. Insert an unlocked/unrestricted SIM, e.g. Roam Mobility. Power on.

4. Go to APN settings (Settings / Network&Internet / Mobile network / Access point names). Now we can add a new APN.

5. Tap the "+" icon on the top right. Add an new profile with this values:
      APN: speakout
      APN: rogers-core-appl1.apn
      APN type: default,supl
      APN Protocol: IPv4/IPv6
      APN Roaming Protocol: IPV4
      MVNO type: None

    Don't touch the MCC and MNC fields which are set as the US codes.

6. Tap the Save button to save it. Check that speakout is generated.

7. Power off the phone. Remove Roam Mobility SIM.

8. Insert Speakout SIM. Power on.

9. Go to APN settings. Tap to select the newly created "speakout" profile. If you look into it, you can find that MCC and MNC are automatically updated to what Speakout uses:
      MCC: 302
      MNC: 720
      MVNO type: GID
      MVNO value: D4

10. Switch back the Network Operator to "Speakout 4G" (refer to step 1).

11. Reboot if necessary.


Tuesday, May 21, 2019

Where is the Print menu of Google Chrome on Android


On Android phones and tablets, the Print button is not shown in the drop-down menu of the Google Chrome. You can get to it through the Share... button.

On the drop-down menu of Google Chrome, find the Share... button and click on it.

The Share via dialogue emerges where you can find the Print icon.

Monday, May 6, 2019

Android programming: Banner Ads for minSdkVersion 16


1. In app/build.gradle, add the following in the dependencies (Note: for Google Mobile Ads SDK version 17.0.0, more steps will be needed.):
implementation 'com.google.android.gms:play-services-ads:16.0.0'

2. Create an AdsBanner class:
import android.content.Context;
import android.view.ViewGroup.LayoutParams;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;

public class AdsBanner {
    private static final String AD_ID = "ca-app-pub-3940256099942544/6300978111";   // Banner Test Admob ID

    private AdView mAdView;

    public AdsBanner(Context context) {
        mAdView = new AdView(context);
        mAdView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        mAdView.setAdSize(AdSize.SMART_BANNER);
        mAdView.setAdUnitId(AD_ID);
    }

    public AdView getAdView() {
        return mAdView;
    }

    public void load() {
        if (mAdView != null) {
            AdRequest adRequest = new AdRequest.Builder()
                    //.addTestDevice(TEST_DEV_HASH)
                    .build();

            mAdView.loadAd(adRequest);
        }
    }
}


3. Add a layout widget as the banner ads container to the Activity:
    <LinearLayout
        android:id="@+id/adLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    </LinearLayout>



4. Add the following code in the onCreate() method of the Activity to show the banner ads:
        // create AdsBanner unit and append it to the layout.
        AdsBanner adsBanner = new AdsBanner(this);

        LinearLayout llayout = findViewById(R.id.adLayout);
        llayout.addView(adsBanner.getAdView());

        adsBanner.load();




Saturday, May 4, 2019

Android: how to prevent soft keyboard from showing up on activity startup


If the first widget of the activity is an EditText, it will get focus when the activity starts and the soft keyboard will automatically show up. This behavior, however, is not desired sometimes. To hide the soft keyboard in this situation, we can add this code in the onCreate() method of the activity or the onCreateView().

    protected void onCreate(Bundle savedInstanceState) {
... ...      getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

... ...
}

or

    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
... ...        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
... ...

}



Thursday, May 2, 2019

Android programming: use Google's Material Icons in the App


  1. Visit Google Material Icons site: https://material.io/tools/icons/?style=baseline
  2. Select the theme option on the left side.
  3. Find the icon suitable for the app.
  4. Click on the wanted icon.
  5. On the bottom left, a new link Selected Icon appears.  Click on it.
  6. Select the size of the icon. For Android app, select Android.
  7. Click to download the SVG format of the icon.
  8. Open the project in Android Studio.
  9. Click on menu File|New|Image Asset.
  10. Select Action Bar and Tab Icons for Icon Type.
  11. Create a name for the icon.
  12. Select Image for Asset Type.
  13. Enter the path to the downloaded file.
  14. Choose a Theme according to that is used in the app.
  15. Click on the Next button.
  16. Click on the Finish button.
  17. The icon is then added into res/drawable. e.g. res/drawable/myicon.
  18. Use the icon as "@drawable/myicon".

Remove the firmware upgrade notification on Android phone


It may be different for various brands of the phones, however this is one kind of tricks you may try.

First try to change the upgrade option to Download Update Manually, usually from the Settings|System Updates option.

If after that the notification still shows up, we can clear the data and cache of the Update App to remove the notification from the notification bar. To do that:
  1. Go to Settings
  2. Select Apps & notifications
  3. Select App info
  4. Click on the menu and choose Show system
  5. Find the update app (e.g. FOTAService)
  6. Click on the Storage item of the app
  7. Clear both data and cache
  8. The notification is gone from the notification bar

Monday, April 29, 2019

Android: ListView doesn't respect layout_constraintBottom


When a ListView is put inside a ConstraintLayout:

<?xml version="1.0" encoding="utf-8"?>
<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">

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginEnd="@dimen/activity_horizontal_margin"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:maxLength="32"
        android:inputType="text"
        />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/editText1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginEnd="@dimen/activity_horizontal_margin"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:maxLength="32"
        android:inputType="text"
        />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/editText2"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:text="Button1"
        />

     <ListView
        android:id="@+id/setKeyListview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/button1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        />

</android.support.constraint.ConstraintLayout>


The ListView is shifted above when there are more items than the view can display. It seems that the option app:layout_constraintTop_toBottomOf="@id/button1" does not take effect.

The fix is to change layout_height of ListView to "0dp". According to this link (https://developer.android.com/reference/android/support/constraint/ConstraintLayout#widgets-dimension-constraints), "0dp" means to match the constraints that are set. So setting ListView's layout_height to "0dp" makes it respect the constraints.

The change is highlighted below:

     <ListView
        android:id="@+id/setKeyListview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toBottomOf="@id/button1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        />



Sunday, April 28, 2019

Android: No static method encodeBase64String in org.apache.commons.codec.binary.Base64


When I used org.apache.commons.codec.binary.Base64.encodeBase64String in my Android application, this exception was thrown:

No static method encodeBase64String([B)Ljava/lang/String; in class Lorg/apache/commons/codec/binary/Base64; or its super classes (declaration of 'org.apache.commons.codec.binary.Base64' appears in /system/framework/org.apache.http.legacy.boot.jar

This method is available since version 1.4 of the Apache Commons Codec. If the OS of the phone has only an older version of the Codec package, the method won't be available. Alternatively, we can use a method that exists in older versions.

Instead of:
String encodedString = Base64.encodeBase64String(bytes);

Use:
String encodedString = new String(Base64.encodeBase64(bytes));

And for decoding, instead of:
byte[] bytes = Base64.decodeBase64(encodedString);

Use:
byte[] bytes = Base64.decodeBase64(encodedString.getBytes());


Saturday, March 30, 2019

Java: AES encryption example


Encryption:
byte[] encrypt(byte[] plainText, String keySeed, byte[] iv) {
    if (plainText == null || iv == null)
        return null;

    try {
        SecretKey key = getSecretKey(keySeed);

        IvParameterSpec ivParm = new IvParameterSpec(iv);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, key, ivParm);
        byte[] cipherText = cipher.doFinal(plainText);
        return cipherText;
    } catch (NoSuchAlgorithmException ex) {
    } catch (NoSuchPaddingException ex) {
    } catch (InvalidKeyException ex) {
    } catch (BadPaddingException ex) {
    } catch (IllegalBlockSizeException ex) {
    } catch (InvalidAlgorithmParameterException ex) {
    }

    return null;
}

Decryption:
byte[] decrypt(byte[] cipherText, String keySeed, byte[] iv) {
    if (cipherText == null || iv == null)
        return null;
    
    try {
        SecretKey key = getSecretKey(keySeed);

        IvParameterSpec ivParm = new IvParameterSpec(iv);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, key, ivParm);
        byte[] plaintext = cipher.doFinal(cipherText);
        return plaintext;
    } catch (NoSuchAlgorithmException ex) {
    } catch (NoSuchPaddingException ex) {
    } catch (InvalidKeyException ex) {
    } catch (BadPaddingException ex) {
    } catch (IllegalBlockSizeException ex) {
    } catch (InvalidAlgorithmParameterException ex) {
    }

    return null;
}

Helper methods:
byte[] generateIv() {
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[16];
    random.nextBytes(bytes);

    return bytes;
}
 
SecretKey getSecretKey(String keySeed) throws NoSuchAlgorithmException {
    byte[] keySeedBytes = keySeed.getBytes();

    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(keySeedBytes);
    byte[] dgBytes = md.digest();   // generate a 32 bytes key

    SecretKey key = new SecretKeySpec(dgBytes, 0, dgBytes.length, "AES");
    return key;
}

Test code:
void test() {
    byte[] b = new byte[] { 1, 2, 3, 10, 20, 30, 100};
    String key = "mykey";

    byte[] iv = generateIv();

    byte[] enb = encrypt(b, key, iv);
    byte[] deb = decrypt(enb, key, iv);

    System.out.println(Arrays.equals(b, deb));
}

Output:
true





Saturday, March 23, 2019

Android programming: request permissions in Activity vs Fragment


In Activity:

// check permission first 
if (ContextCompat.checkSelfPermission(this,
        Manifest.permission.WRITE_EXTERNAL_STORAGE)
        != PackageManager.PERMISSION_GRANTED) {

    // request the permission 
    ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
            PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
else {
    // has the permission. 
    saveFile();
}


In Fragment:

// check permission first
if (ContextCompat.checkSelfPermission(getActivity(),
        Manifest.permission.WRITE_EXTERNAL_STORAGE)
        != PackageManager.PERMISSION_GRANTED) {

    // request the permission
    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
            PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
else {
    // has the permission. 
    saveFile();
}


Both Activity and Fragment then override onRequestPermissionsResult() which has little difference as well.

In Activity:


@Override 
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {

    switch (requestCode) {
        case PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
            // If request is cancelled, the result arrays are empty. 
            if (grantResults.length > 0 
                   && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted. 
                saveFile();
            } else {
                // permission denied. 
                // tell the user the action is cancelled 
                AlertDialog alertDialog = new AlertDialog.Builder(this).create();
                alertDialog.setMessage(getString(R.string.cannot_save_image));
                alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.ok),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                alertDialog.show();
            }
            return;
        }
    }
}

In Fragment:

@Override 
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {

    switch (requestCode) {
        case PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
            // If request is cancelled, the result arrays are empty. 
            if (grantResults.length > 0 
                   && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted.
                saveFile();
            } else {
                // permission denied. 
                // tell the user the action is cancelled 
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
                alertDialog.setMessage(getString(R.string.cannot_save_image));
                alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.ok),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                alertDialog.show();
            }
            return;
        }
    }
}


Friday, December 28, 2018

ProgressBar not shown due to animation disabled on phone | Android Programming


I noticed the ProgressBar used in my app suddenly stopped working.

<ProgressBar
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/progressBar"
    android:progressDrawable="@drawable/circular_progress_bar"/>



res/drawable/circular_progress_bar.xml:

<?xml version="1.0" encoding="utf-8"?>
<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="90"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="360">

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="7.0">

        <gradient
            android:centerColor="#2277DD"
            android:endColor="#2277DD"
            android:startColor="#2277DD"
            android:angle="0"
            android:type="sweep"
            android:useLevel="false" />
    </shape>

</rotate>

I played with the code for an hour or so but cannot find out why. It turned out the reason is that I had turned off animation on my phone. To turn it back on, go to Settings/Developer options, find all the "animation scale" options and set the scales to a value other than "Animation off". Restart the app on the phone and the ProgressBar will come back.

Wednesday, December 26, 2018

Stop showing soft keyboard on Activity start | Android programming


If the first element in the Activity is an EditText, it will get focus when the Activity starts, and the soft keyboard will show up.

There are many ways to solve this issue if you don't want the soft keyboard pop up. Here is a simple and interesting trick that only makes small updates on the layout XML files.

Add the attributes to the parent element of the first EditText. The EditText will not get focus at the start up and thus the soft keyboard will not show. The code to be added is highlighted below:

<LinearLayout
    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"
    android:orientation="vertical"
    android:focusable="true"
    android:focusableInTouchMode="true">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/some_iput"/>

   ...

Monday, February 6, 2017

Android programming: Banner Ads


I managed to set up the banner ad in my little app. Here is the summary of the changes:
  • Set minSdkVersion to 9 or higher.
  • To use Firebase, add these dependencies and plugin to the app/build.gradle file:
dependencies {
...
    compile 'com.google.android.gms:play-services:10.0.1'
    compile 'com.google.firebase:firebase-ads:10.0.1'
    compile 'com.google.android.gms:play-services-ads:10.0.1'
}

apply plugin: 'com.google.gms.google-services'

  • Add this dependency to the project's build.gradle file:
dependencies {
        classpath 'com.google.gms:google-services:3.0.0'
        classpath 'com.android.tools.build:gradle:2.2.3'
}
  • Add permission to use INTERNET in app/src/main/AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
  • Add the Ad unit ID and app ID to the strings.xml file. The following shows the test IDs used in Google's example. To get the IDs for my real app, I went to the Admob web site and registered my app. Admob then generated the Ad unit ID and the app ID, and offered to send the IDs and setup instruction to my Email.
<string name="banner_ad_unit_id">ca-app-pub-3940256099942544/6300978111</string>
<string name="banner_ad_app_id">ca-app-pub-3940256099942544~3347511713</string>

  •  Now the real stuff, add the AdView widget to the app:
...
          xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"

          xmlns:ads="http://schemas.android.com/apk/res-auto"
...
<com.google.android.gms.ads.AdView
           android:id="@+id/adView"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_centerHorizontal="true"
           android:layout_alignParentBottom="true"
           ads:adSize="BANNER"
           ads:adUnitId="@string/banner_ad_unit_id" />

  • In the onCreate() method of the Activity, or the onCreateView() method of the Fragment, add the code to fetch the Ad:
MobileAds.initialize(getActivity().getApplicationContext(), 
                     getString(R.string.banner_ad_app_id));

AdView mAdView = (AdView) v.findViewById(R.id.adView);
AdRequest.Builder builder = new AdRequest.Builder();
AdRequest adRequest = builder.build();
mAdView.loadAd(adRequest);

  •  Note: I have tried to use builder.addKeyword() to retrieve targeting Ads. Unfortunately, this feature is not supported by Admob yet. And using builder.addKeyword() makes Ads rendering much slower.

Wednesday, February 1, 2017

Admob + Firebase: google-services.json is missing


After adding Firebase Admob into my Android app project, Gradle build failed with this error:

Error:Execution failed for task ':app:processDebugGoogleServices'.
> File google-services.json is missing. The Google Services Plugin cannot function without it.
   Searched Location:
  ...\app\src\debug\google-services.json
  ...\app\google-services.json

Where can I get the google-services.json?

I encountered this problem because I hadn't set up my project in Firebase yet.

I went to https://console.firebase.google.com/ and signed in. Followed the Create New Project step by step to set up the project in Firebase. After the project was successfully set up, it prompted me to download the google-services.json file. Then I copied the file to my project's app/ directory.

Then I re-synchronized Gradle and this time, no errors.

Admob + Firebase: Plugin with id 'com.google.gms.google-services' not found.


I was following the instruction in https://firebase.google.com/docs/admob/android/quick-start to add Admob into my Android App.

It sounded as simple as adding two lines into the app level's build.gradle:
...
    dependencies {
            compile fileTree(dir: 'libs', include: ['*.jar'])
            compile 'com.android.support:appcompat-v7:xx.x.x'
            compile 'com.google.firebase:firebase-ads:10.0.1'
        }
...

apply plugin: 'com.google.gms.google-services'
 However, after doing the Sync as the IDE required, this error was encountered:

   Gradle sync failed: Plugin with id 'com.google.gms.google-services' not found.

It seems the tutorial has left out some details. After I added the following two lines, this problem was solved.

In the Project level build.gradle, add dependency: classpath 'com.google.gms:google-services:3.0.0':

dependencies { 
     classpath 'com.google.gms:google-services:3.0.0'
     classpath 'com.android.tools.build:gradle:2.2.3'...
}

In the app level build.gradle, add dependency: compile 'com.google.android.gms:play-services:10.0.1'

dependencies { 
... 
    compile 'com.google.android.gms:play-services:10.0.1' 
    compile 'com.google.firebase:firebase-ads:10.0.1'
}

After that, click on the Sync link on the top right corner to synchronize Gradle.


Wednesday, March 9, 2016

Android programming: UI Fragment hosted in Activity


AndroidManifest.xml:

<manifest package="com.solezero.android.learning"
           xmlns:android="http://schemas.android.com/apk/res/android">

    <application
         android:allowBackup="true"
         android:icon="@mipmap/ic_launcher" 
         android:label="@string/app_name" 
         android:supportsRtl="true" 
         android:theme="@style/AppTheme">
        <activity
             android:name=".MyActivity"
             android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>


MyActivity.java:

package com.solezero.android.learning;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;

public class MyActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_my);

        FragmentManager fragmentManager = getSupportFragmentManager();

        Fragment fragment = fragmentManager.findFragmentById(R.id.fragmentContainer);

        if (fragment == null) {
            fragment = createFragment();

           fragmentManager.beginTransaction().add(R.id.fragmentContainer, fragment).commit();        }
    }

    protected Fragment createFragment() {

        MyFragment myFragment = new MyFragment();

        return myFragment;
    }

}


layout/activity_my.xml:

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/fragmentContainer"
              android:layout_width="match_parent"
              android:layout_height="match_parent" />


MyFragment.java:

package com.solezero.android.learning;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MyFragment extends Fragment {
    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_my, container, false);

        return view;
    }
}

To access the Activity from the Fragment, use getActivity().


layout/fragment_my.xml:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
               android:orientation="vertical" 
               android:layout_width="match_parent"
               android:layout_height="match_parent">

</LinearLayout>


 
Get This <