Tuesday, November 29, 2016

FragmentStatePagerAdapter


activity_main 
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:gravity="center_horizontal" 
 android:orientation="vertical" 
 android:padding="4dip">

    <android.support.v4.view.ViewPager 
 android:id="@+id/pager" 
 android:layout_width="match_parent" 
 android:layout_height="0px" 
 android:layout_weight="1">
</android.support.v4.view.ViewPager>

    <LinearLayout 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" 
 android:layout_weight="0" 
 android:gravity="center" 
 android:measureWithLargestChild="true" 
 android:orientation="horizontal">

        <Button 
 android:id="@+id/goto_first" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:text="first">
</Button>

        <Button 
 android:id="@+id/goto_last" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:text="last"></Button>
    </LinearLayout>
</LinearLayout>
fragment_image
<?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" >

    <TextView 
 android:id="@+id/text" 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" 
 android:gravity="center_vertical|center_horizontal" 
 android:text="hello_world" 
 android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView 
 android:id="@+id/imageView1" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:layout_below="@+id/text" 
 android:layout_centerHorizontal="true" 
 android:layout_marginTop="36dp" 
 android:src="@mipmap/ic_launcher" />

</RelativeLayout>
fragment_pager_list
<?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:background="@android:drawable/gallery_thumb" 
 android:orientation="vertical" >

    <TextView 
 android:id="@+id/text" 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" 
 android:gravity="center_vertical|center_horizontal" 
 android:text="hello_world" 
 android:textAppearance="?android:attr/textAppearanceMedium" />

    <FrameLayout 
 android:layout_width="match_parent" 
 android:layout_height="0dip" 
 android:layout_weight="1" >

        <ListView 
 android:id="@android:id/list" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:drawSelectorOnTop="false" />
    </FrameLayout>

</LinearLayout>
public class MainActivity extends FragmentActivity {
    static final int ITEMS = 5;
    MyAdapter mAdapter;
    ViewPager mPager;

    @Override 
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_pager);
        mAdapter = new MyAdapter(getSupportFragmentManager());
        mPager = (ViewPager) findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);

        Button button = (Button) findViewById(R.id.first);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mPager.setCurrentItem(0);
            }
        });
        button = (Button) findViewById(R.id.last);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mPager.setCurrentItem(ITEMS - 1);
            }
        });
    }

    public static class MyAdapter extends FragmentStatePagerAdapter {
        public MyAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        @Override 
 public int getCount() {
            return ITEMS;
        }

        @Override 
 public Fragment getItem(int position) {
            switch (position) {
                case 0: // Fragment # 0 - This will show image 
 return ImageFragment.init(position);
                case 1: // Fragment # 1 - This will show image 
 return ImageFragment.init(position);
                default:// Fragment # 2-9 - Will show list 
 return ArrayListFragment.init(position);
            }
        }
    }


}
public class ImageFragment extends Fragment {
    int fragVal;

    static ImageFragment init(int val) {
        ImageFragment truitonFrag = new ImageFragment();
        // Supply val input as an argument. 
 Bundle args = new Bundle();
        args.putInt("val", val);
        truitonFrag.setArguments(args);
        return truitonFrag;
    }

    @Override 
 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragVal = getArguments() != null ? getArguments().getInt("val") : 1;
    }

    @Override 
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View layoutView = inflater.inflate(R.layout.fragment_image, container,
                false);
        View tv = layoutView.findViewById(R.id.text);
        ((TextView) tv).setText("Truiton Fragment #" + fragVal);
        return layoutView;
    }
}
public class ArrayListFragment extends ListFragment {
    int fragNum;
    String arr[] = {"1", "2", "2", "3", "4", "5"};

    static ArrayListFragment init(int val) {
        ArrayListFragment truitonList = new ArrayListFragment();

        // Supply val input as an argument. 
 Bundle args = new Bundle();
        args.putInt("val", val);
        truitonList.setArguments(args);

        return truitonList;
    }

    /**     * Retrieving this instance's number from its arguments.     */ 
 @Override 
 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragNum = getArguments() != null ? getArguments().getInt("val") : 1;
    }

    /**     * The Fragment's UI is a simple text view showing its instance number and 
 * an associated list.     */ 
 @Override 
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View layoutView = inflater.inflate(R.layout.fragment_pager_list,
                container, false);
        View tv = layoutView.findViewById(R.id.text);
        ((TextView) tv).setText("Truiton Fragment #" + fragNum);
        return layoutView;
    }

    @Override 
 public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, arr));
    }

    @Override 
 public void onListItemClick(ListView l, View v, int position, long id) {
        Log.i("Truiton FragmentList", "Item clicked: " + id);
    }
} 
 

Monday, November 21, 2016

Active Notifications in Android 7 Example Code



<?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 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content">
        <Button 
 android:id="@+id/add_notification" 
 android:text="Add a notification" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" />
    </LinearLayout>

    <TextView 
 style="@android:style/TextAppearance.Material.Large" 
 android:id="@+id/number_of_notifications" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" />
 </LinearLayout>
 

public class MainActivity extends AppCompatActivity {
    String TAG = "MainActivity";
    private static final int REQUEST_CODE = 2323;
    private TextView mNumberOfNotifications;
    private PendingIntent mDeletePendingIntent;
    protected static final String ACTION_NOTIFICATION_DELETE 
 = "com.example.android.activenotifications.delete";
    private static final String NOTIFICATION_GROUP =
            "com.example.android.activenotifications.notification_type";
    private NotificationManager mNotificationManager;
    private static final int NOTIFICATION_GROUP_SUMMARY_ID = 1;
    private static int sNotificationId = NOTIFICATION_GROUP_SUMMARY_ID + 1;

    @Override 
 protected void onResume() {
        super.onResume();
        updateNumberOfNotifications();
    }

    @SuppressLint("StringFormatMatches")
    protected void updateNumberOfNotifications() {
        final StatusBarNotification[] activeNotifications = mNotificationManager                .getActiveNotifications();
        final int numberOfNotifications = activeNotifications.length;
        mNumberOfNotifications.setText(getString(R.string.active_notifications,
                numberOfNotifications));
        Log.i(TAG, getString(R.string.active_notifications, numberOfNotifications));
    }

    protected void updateNotificationSummary() {
        final StatusBarNotification[] activeNotifications = mNotificationManager                .getActiveNotifications();

        int numberOfNotifications = activeNotifications.length;
        for (StatusBarNotification notification : activeNotifications) {
            if (notification.getId() == NOTIFICATION_GROUP_SUMMARY_ID) {
                numberOfNotifications--;
                break;
            }
        }

        if (numberOfNotifications > 1) {
            // There are %s ActiveNotifications 
 String notificationContent = getString(R.string.sample_notification_summary_content,
                    "" + numberOfNotifications);
            final NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(getApplicationContext())
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .setSummaryText(notificationContent))
                    .setGroup(NOTIFICATION_GROUP)
                    .setGroupSummary(true);
            final Notification notification = builder.build();
            mNotificationManager.notify(NOTIFICATION_GROUP_SUMMARY_ID, notification);
        } else {
            mNotificationManager.cancel(NOTIFICATION_GROUP_SUMMARY_ID);
        }
    }

    private void addNotificationAndUpdateSummaries() {
        final NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("This is a sample notification")
                .setAutoCancel(true)
                .setDeleteIntent(mDeletePendingIntent)
                .setGroup(NOTIFICATION_GROUP);

        final Notification notification = builder.build();
        mNotificationManager.notify(getNewNotificationId(), notification);
        Log.d(TAG, "Add a notification");

        updateNotificationSummary();
        updateNumberOfNotifications();
    }

    public int getNewNotificationId() {
        int notificationId = sNotificationId++;
        if (notificationId == NOTIFICATION_GROUP_SUMMARY_ID) {
            notificationId = sNotificationId++;
        }
        return notificationId;
    }

    void init() {
        mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(
                Context.NOTIFICATION_SERVICE);
        mNumberOfNotifications = (TextView) findViewById(R.id.number_of_notifications);

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override 
 public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.add_notification: {
                        addNotificationAndUpdateSummaries();
                        break;
                    }
                }
            }
        };
        findViewById(R.id.add_notification).setOnClickListener(onClickListener);
        Intent deleteIntent = new Intent(ACTION_NOTIFICATION_DELETE);
        mDeletePendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
                REQUEST_CODE, deleteIntent, 0);
    }

    @Override 
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        init();
    }

    @Override 
 public void onBackPressed() {
        super.onBackPressed();
    }


}

Multi Screen in Android 7 Example Code

Tuesday, November 15, 2016

Fragment in Android

public class MainActivity extends AppCompatActivity {
    String TAG = "MainActivity";

    @Override 
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.v(TAG, "<<screen>>");


        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        FragmentMain fragmentMain = new FragmentMain();
        transaction.addToBackStack("fragmentMain");
        transaction.replace(R.id.container, fragmentMain);
        transaction.commit();

    }


    public boolean handleBackStack() {
        int count = getFragmentManager().getBackStackEntryCount();
        Log.v(TAG, String.valueOf(count));
        if (count == 1) {
            finish();
        } else {
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            getFragmentManager().popBackStackImmediate();
            transaction.commit();
        }
        return true;
    }


    //handle the hardware back press 
 @Override 
 public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            handleBackStack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
public class FragmentMain extends Fragment {


    public FragmentMain() {
        // Required empty public constructor    }

    @Override 
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_main, container, false);
        final Button mButtonFragmentMain=(Button)view.findViewById(R.id.button__fragment_main);

        Log.v("<< main fragment>>","<<screen>>");

        mButtonFragmentMain.setOnClickListener(new View.OnClickListener() {
            @Override 
 public void onClick(View view) {
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                FragmentChild fragmentChild = new FragmentChild();
                transaction.addToBackStack("fragmentChild");
                transaction.replace(R.id.container, fragmentChild);
                transaction.commit();

            }
        });


        return view;
    }
}
public class FragmentChild extends Fragment {


    public FragmentChild() {
        // Required empty public constructor    }


    @Override 
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

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



        return view;
    }
}
activity_main
<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:id="@+id/container" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:orientation="vertical">

</FrameLayout>
 
fragment_main
 
<RelativeLayout 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:paddingBottom="@dimen/activity_vertical_margin" 
 android:paddingLeft="@dimen/activity_horizontal_margin" 
 android:paddingRight="@dimen/activity_horizontal_margin" 
 android:paddingTop="@dimen/activity_vertical_margin">

    <TextView 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:layout_centerHorizontal="true" 
 android:layout_marginTop="20dp" 
 android:text="Main Fragment Screen" 
 android:textSize="26sp" 
 android:textStyle="bold" />

    <Button 
 android:id="@+id/button__fragment_main" 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" 
 android:layout_centerInParent="true" 
 android:paddingBottom="15dp" 
 android:paddingTop="15dp" 
 android:text="Open Child Fragment" 
 android:textSize="20sp" />
</RelativeLayout>
 
fragment_child
<RelativeLayout  
xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:paddingBottom="@dimen/activity_vertical_margin" 
 android:paddingLeft="@dimen/activity_horizontal_margin" 
 android:paddingRight="@dimen/activity_horizontal_margin" 
 android:paddingTop="@dimen/activity_vertical_margin">

    <TextView 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:layout_centerInParent="true" 
 android:text="Child Fragment Screen" 
 android:textSize="26sp" 
 android:textStyle="bold" />
</RelativeLayout>

   

Android Expand RecyclerView

 
import libs 
compile 'com.bignerdranch.android:expandablerecyclerview:2.1.1' 
 
activity_expand
 
<?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">

  <android.support.v7.widget.RecyclerView 
 android:id="@+id/recycler_view" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" />
</LinearLayout>
 
item_subcategory_fragment_elv_group
 
<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="match_parent" 
 android:orientation="vertical" 
 android:layout_height="48dp">
<TextView     
android:id="@+id/lblListHeader" 
 android:text="abc" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" />
</LinearLayout>
 
item_subcategory_fragment_elv_child
 
<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout  
xmlns:android="http://schemas.android.com/apk/res/android"     
android:layout_width="match_parent" 
 android:orientation="vertical" 
 android:layout_height="48dp">
<TextView 
 android:layout_width="wrap_content" 
 android:id="@+id/lblListItem" 
 android:layout_marginLeft="70dp" 
 android:layout_height="wrap_content" />
</LinearLayout>
    
public class MainActivity extends AppCompatActivity {
    String TAG = "MainActivity";
    RecyclerView recycler_view;

    @Override 
 protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_expand);
        List<ParentListItem> parentListItems = new ArrayList<>();
        List<SubcategoryParentListItem> listItems = new ArrayList<>();

        for (int i = 0; i < 50; i++) {
            SubcategoryParentListItem ob = new SubcategoryParentListItem();
            listItems.add(ob);
        }


        for (int i = 0; i < 100; i++) {
            SubcategoryParentListItem ob = new SubcategoryParentListItem();
            ob.setChildItemList(listItems);
            parentListItems.add(ob);
        }

        recycler_view = (RecyclerView) findViewById(R.id.recycler_view);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recycler_view.setLayoutManager(mLayoutManager);
        recycler_view.setAdapter(new SubCategoryExpandableRecyclerAdapter(this, parentListItems));

    }
}
public class SubCategoryExpandableRecyclerAdapter extends ExpandableRecyclerAdapter<SubCategoryExpandableRecyclerAdapter.MyParentViewHolder, SubCategoryExpandableRecyclerAdapter.MyChildViewHolder> {
    private LayoutInflater mInflater;

    public SubCategoryExpandableRecyclerAdapter(Context context, List<ParentListItem> itemList) {
        super(itemList);
        mInflater = LayoutInflater.from(context);
    }

    @Override     
public MyParentViewHolder onCreateParentViewHolder(ViewGroup viewGroup) {
        View view = mInflater.inflate(R.layout.item_subcategory_fragment_elv_group, viewGroup, false);
        return new MyParentViewHolder(view);
    }

    @Override 
 public MyChildViewHolder onCreateChildViewHolder(ViewGroup viewGroup) {
        View view = mInflater.inflate(R.layout.item_subcategory_fragment_elv_child, viewGroup, false);
        return new MyChildViewHolder(view);
    }

    @Override 
 public void onBindParentViewHolder(MyParentViewHolder parentViewHolder, int position, ParentListItem parentListItem) {
        SubcategoryParentListItem subcategoryParentListItem = (SubcategoryParentListItem) parentListItem;
        // handler for row parent 
 parentViewHolder.lblListHeader.setText(subcategoryParentListItem.mTitle);

    }

    @Override 
 public void onBindChildViewHolder(MyChildViewHolder childViewHolder, int position, Object childListItem) {
        SubcategoryParentListItem subcategoryChildListItem = (SubcategoryParentListItem) childListItem;
        // handler for row child 
 childViewHolder.txtListChild.setText(subcategoryChildListItem.mTitle);

    }

    public class MyParentViewHolder extends ParentViewHolder {

        public TextView lblListHeader;

        public MyParentViewHolder(View itemView) {
            super(itemView);
            // init view parent 
 lblListHeader = (TextView) itemView.findViewById(R.id.lblListHeader);
        }
    }


    public class MyChildViewHolder extends ChildViewHolder {

        public TextView txtListChild;

        public MyChildViewHolder(View itemView) {
            super(itemView);
            // init view child list 
 txtListChild = (TextView) itemView.findViewById(R.id.lblListItem);
        }
    }
}
public class SubcategoryParentListItem implements ParentListItem {
    // object    public String mTitle;
    public List<SubcategoryParentListItem> mChildItemList;

    public SubcategoryParentListItem() {
        mTitle = "SubcategoryParentListItem";
    }

    @Override 
 public List<SubcategoryParentListItem> getChildItemList() {
        return mChildItemList;
    }

    public void setChildItemList(List<SubcategoryParentListItem> list) {
        mChildItemList = list;
    }

    @Override    public boolean isInitiallyExpanded() {
        return false;
    }
}