• Tidak ada hasil yang ditemukan

Buku Android Notes For Professionals

N/A
N/A
gurmel singh

Academic year: 2024

Membagikan "Buku Android Notes For Professionals"

Copied!
1329
0
0

Teks penuh

1093 Section 230.3: This code I implemented in my application to push image, message and link.

About

Getting started with Android

Creating a New Project

This is one of the signals that the Google Play Store uses to determine which devices an app can be installed on. Introduction to configuring the build.gradle and the DSL methods to run the application.

Setting up Android Studio

Android programming without an IDE

You can replace steps 11 and 12 with a single call to Jack if you want; it can compile directly from the Java source (.java → .dex). If they are also not required for your app, you can streamline the build somewhat by omitting step 10 and removing the reference to the res/ directory from step 13.

Application Fundamentals

Yet another example, You are in a restaurant and sit on a table, each table has a server, when ever you want to order food items, you ask the server to do it. The attendant then places your order and your food items are served to your table.

Setting up an AVD (Android Virtual Device)

  • Click this button to bring up the AVD Manager
  • You should see a dialog like this
  • Here, enter a name for your emulator, initial orientation, and whether you want to display a frame around it
  • Now you got a new AVD ready for launching your apps on it

Now think of this hotel as an Android app, yourself as an activity, and the room service agent is your context, giving you access to the hotel resources such as room service, food items, etc. Also in this example, the restaurant is an Android app, the tables or the customers are app components, the food items are your app resources and the companion is your context, allowing you to access the resources such as food items.

Android Studio

Setup Android Studio

View And Add Shortcuts in Android Studio

Android Studio useful shortcuts

Refactor This (menu/selector for all relevant . refactor actions of the current item) Mac CTRL + T - Win/Linux CTRL + ALT + T.

Android Studio Improve performance tip

Gradle build project takes forever

Enable/Disable blank line copy

Custom colors of logcat message based on message importancemessage importance

Filter logs from UI

Create filters configuration

Create assets folder

Instant Run in Android Studio

Enabling or disabling Instant Run

Types of code Swaps in Instant Run

WARM SWAP is triggered when an existing resource is changed or removed (anything in the res folder) COLD SWAP when there is a structural code change in your app's code, e.g. HOT SWAP changes are visible immediately - as soon as the next call to the method whose implementation has changed is made.

Unsupported code changes when using Instant RunRun

TextView

Spannable TextView

However, for the above code to work, the CustomTypefaceSpan class must be derived from the TypefaceSpan class.

Strikethrough TextView

4, // End of span (exclusive) . Spanned.SPAN_EXCLUSIVE_EXCLUSIVE // Text changes are not reflected in the alert change.

TextView with image

Make RelativeSizeSpan align to top

Pinchzoom on TextView

Textview with dierent Textsize

Theme and Style customization

TextView customization

Single TextView with two dierent colors

AutoCompleteTextView

Simple, hard-coded AutoCompleteTextView

Autosizing TextViews

Granularity

Preset Sizes

ListView

Custom ArrayAdapter

By default, the ArrayAdapter creates a view for each array element by calling toString() on each element and placing the contents in a TextView. ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, myStringArray);. To use something other than TextViews for the array view, for example ImageViews, or to get some of the data in addition to toString() results, populate the views, override getView(int, View, ViewGroup) to return that type of view , you wish.

Filtering with CursorAdapter

Suppose your query runs every time the user types an EditText: EditText queryText = (EditText) findViewById(R.id.textQuery);.

Layouts

LayoutParams

Other attributes of a View are directly View-related and are processed by the View itself. Because the LayoutParams object is directly related to the enclosing ViewGroup, this method returns a non-null value only when View is linked to the ViewGroup. Please note that this item may not always be present.

You may need to use functions that are specific to a particular ViewGroup (eg you may want to change the RelativeLayout rules programmatically). This can get a bit confusing when you get a LayoutParams object for a child view that is actually another ViewGroup. IMPORTANT: The LayoutParams object type is directly related to the ENCLOSING ViewGroup type.

Gravity and layout gravity

CoordinatorLayout Scrolling Behavior

Percent Layouts

This allows you to set just one dimension, such as just the width, and the height will automatically be determined based on the aspect ratio you've specified, whether it's 4:3 or 16:9 or even a 1:1 square relationship.

View Weight

Even if the device size is larger, the EditText will occupy 2/4 of the screen space. If widgets are to be aligned vertically, layout_height will be set to 0dp. This is done to increase the efficiency of the code because at runtime the system will not try to calculate the width or height, as this is handled by the weight.

If you used wrap_content instead, the system would try to calculate the width/height first before applying the weight attribute, causing a new calculation cycle.

Creating LinearLayout programmatically

LinearLayout

RelativeLayout

FrameLayout

GridLayout

CoordinatorLayout

Notice how the FloatingActionButton is anchored to the CoordinatorLayout with app:layout_anchor="@id/coord_layout".

ConstraintLayout

Adding ConstraintLayout to your project

Chains

TextInputLayout

Basic usage

Password Visibility Toggles

Adding Character Counting

Handling Errors

TextInputEditText

The CoordinatorLayout is a super powerful FrameLayout and the purpose of this ViewGroup is to coordinate the views contained within it. The main appeal of the CoordinatorLayout is its ability to coordinate the animations and transitions of the views within the XML file itself.

Creating a simple Behavior

Using the SwipeDismissBehavior

Create dependencies between Views

TabLayout

ViewPager

ViewPager with a dots indicator

In this case, we can place the TabLayout anywhere, but we need to connect the TabLayout to the ViewPager programmatically. So we create three files: select_dot.xml, default_dot.xml and tab_selector.xml.

Basic ViewPager usage with fragments

Now we just need to add 3 lines of code to TabLayout in our XML layout and you're done. Until recently, using android.support.v4.app.FragmentPagerAdapter prevented the use of a PreferenceFragment as one of the fragments used in the FragmentPagerAdapter. The latest versions of the supporting v7 library now include the PreferenceFragmentCompat class, which works with a ViewPager and the v4 version of FragmentPagerAdapter.

Adding a ViewPager

Setup OnPageChangeListener

Determines whether a page view is associated with a specified key object // as returned by instantiateItem(ViewGroup, int). This method will be called when scrolling the current page, either as part of // programmatically triggered smooth scrolling or user-triggered touch scrolling. Useful for detecting when the user starts // dragging, when the prompter is automatically set to the current page,.

This method synchronizes by creating and removing tabs according to the contents of the adapter attached to your ViewPager each time you call it. It will also set a callback so that every time the user turns the page, the corresponding tab will be selected. Then implement the FragmentPagerAdapter and apply it to the ViewPager: public class MyViewPagerActivity extends AppCompatActivity.

CardView

Getting Started with CardView

Adding Ripple animation

Customizing the CardView

Using Images as Background in CardView (Pre- Lollipop device issues)Lollipop device issues)

3 FIXED Image background card in API 19 with attribute cardView.setPreventCornerOverlap(false) (issue now resolved).

NavigationView

How to add the NavigationView

ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( . this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);. The action bar will // automatically handle Home/Up button clicks as long as // you specify a parent activity in AndroidManifest.xml.

Add underline in menu elements

Add seperators to menu

RecyclerView

Adding a RecyclerView

Smoother loading of items

Here an instance of the special ViewDataBinding class is created using the inflated View object and the DataBindingUtil utility class. By default, the Android Data Binding library generates a ViewDataBinding class based on the name of the layout file. That Binding class would also have a setter method to set the object defined as data in the layout file (ItemModel for this example).

Preglasi public void onBindViewHolder(BindingViewHolder holder, int position) { holder.getBinding().setItemModel(items.get(position));.

Animate data change

This class handles all calls to the 'notify' method on the RecyclerView.Adapter to ensure proper animation and even allows stacking of multiple changes so the animations don't flicker. If this returns false, onBindViewHolder() is called with the holder containing the item and the position of the item. Just update the handler with the object in the sorted list from the given position DataModel model = mSortedList.get(position);.

Popup menu with recyclerView

Sometimes a RecyclerView will need to use multiple view types to be displayed in the list shown in the UI, and each view needs a different layout xml to be inflated. For this issue, you can use different ViewHolders in a single Adapter, using a special method in RecyclerView - getItemViewType(int position).

Drag&Drop and Swipe with RecyclerView

Show default view till items load or when data is not availablenot available

Add header/footer to a RecyclerView

If you have multiple headers and footers, you should return total count // like, headers.size() + data.size() + footers.size(). Now set the default ViewHolder to NormalViewHolder public class ViewHolder extends RecyclerView.ViewHolder { // Define elements of an array here.

Endless Scrolling in Recycleview

First make a one abstract method in Recycleview adapter like below

Now every backend logic is complete now it's time to execute this logic.It's simple you can override load method where you create object of your adapter.this method is automatically call while user reach at end of the

Add divider lines to RecyclerView items

RecyclerView Decorations

Add divider to RecyclerView

Drawing a Separator

Per-item margins with ItemDecoration

Kotlin and RxJava example

RecyclerView Click listener

Another way to implement Item Click Listener

New Example

Item Click Listeners

Adding header view to recyclerview with gridlayout managergridlayout manager

GridLayoutManager with dynamic span count

The recycler will need to determine how many columns will fit in the available space. In your activity/fragment you simply take a reference to the recycler review and set an adapter for it (and any item decorations or animations you want to add). As a final addition, you may want to center the columns in the recycler view (by default they are aligned with layout_start).

Simple list with LinearLayoutManager

When a list item refers to different data types such as text, numbers, images (as in this example with places), it is often a good idea to use a custom object. You must specify an xml layout file that will be used for each list item. In this example, an ImageView is used for the image and a TextView for the name.

The LinearLayout positions the ImageView to the left and the TextView to the right of the image. We obtain the model used by finding it at the given position in the list and then setting its image and name in the views of the ViewHolder.

StaggeredGridLayoutManager

Pagination in RecyclerView

Custom_Volly_Request jsonObjReq = new Custom_Volly_Request(Request.Method.POST, "Your php file link", params, .

ImageView

Set tint

Set alpha

Set Scale Type

The image in the ImageView may not fit the exact size given to the container. In that case, the frame allows you to resize the image in a number of ways. Scales the image uniformly (maintains the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or greater than the corresponding dimension of the view (minus padding).

When the image is wider than the container, it expands to a larger size (in this case the height) and adjusts the width of the image without changing its proportions, causing it to be cropped. Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image are equal to or less than the corresponding dimension of the display (minus padding). It will center the image and resize it to the smaller size. If both container sizes are larger, it will work the same as middle.

Referensi

Dokumen terkait