Android Beginner Lessons

because i'm beginner

.

Senin, 16 November 2015

Android: ImageView on Cardview

5 komentar
INTRODUCTION
Setelah memahami Recyclerview/Cardview dan Toolbar di posting kemarin, selanjutnya kita akan memasukan gambar ke Cardview.
Tutor ini lanjutan dari Cardview with Toolbar, jadi ikuti dulu tutorialnya dari awal di postingan sebelumnya.
Untuk memasukan gambar ke item cardview perlu menambah beberapa code ke xml dan adapter.
ok, langsung saja..

EXAMPLE CARDVIEW WITH IMAGE
  1. Download bahan untuk iconnya disini, extract, masukkan ke folder res/drawable-hdpi
  2. Buka item_recycle.xml, perhatikan tambahan codenya atau ganti saja semua isinya dengan ini:
  3. <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:id="@+id/cardlist_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="4dp"
        card_view:cardElevation="@dimen/cardview_default_elevation"
        android:foreground="?android:attr/selectableItemBackground"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp">
    
        <RelativeLayout
            android:layout_height="wrap_content"
            android:layout_width="wrap_content">
    
            <ImageView
                android:id="@+id/icon_item"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:padding="4dp"
                android:scaleType="centerCrop"
                android:src="@mipmap/ic_launcher" />
    
            <LinearLayout
                android:layout_width="match_parent"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="8dp"
                android:paddingBottom="8dp"
                android:gravity="center_vertical"
                android:layout_height="?attr/listPreferredItemHeight"
                android:orientation="vertical"
                android:layout_toEndOf="@id/icon_item">
    
                <TextView
                    android:id="@+id/listitem_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Android version name"
                    android:textColor="@color/primary_text_default_material_light"
                    android:textSize="@dimen/abc_text_size_subhead_material" />
    
                <TextView
                    android:id="@+id/listitem_subname"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Test"
                    android:paddingTop="3dp"
                    android:textColor="@color/secondary_text_default_material_light"
                    android:textSize="@dimen/abc_text_size_caption_material" />
            </LinearLayout>
    
        </RelativeLayout>
    
    </android.support.v7.widget.CardView>
  4. Buka arrays.xml, tambahkan ini di bagian bawah sebelum code </resources> 
  5.     <string-array name="list_icon">
            <item>a</item>
            <item>b</item>
            <item>c</item>
            <item>d</item>
            <item>e</item>
            <item>f</item>
            <item>g</item>
            <item>h</item>
            <item>i</item>
            <item>j</item>
            <item>k</item>
            <item>l</item>
            <item>m</item>
        </string-array>
  6. Buka ItemController.java, perhatikan tambahan codenya :
  7. import android.support.v7.widget.CardView;
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;
    
    /**
     * Created by AbangAzmi on 11/14/2015.
     */
    public class ItemController extends RecyclerView.ViewHolder implements View.OnClickListener {
    
        //Variable
        CardView cardItemLayout;
        ImageView icon; // Picture
        TextView title;
        TextView subTitle;
    
        public ItemController(View itemView) {
            super(itemView);
    
            //Set id
            cardItemLayout = (CardView) itemView.findViewById(R.id.cardlist_item);
            
            //Tambahan untuk id Picture
            icon = (ImageView)itemView.findViewById(R.id.icon_item);
            
            //id Text
            title = (TextView) itemView.findViewById(R.id.listitem_name);
            subTitle = (TextView) itemView.findViewById(R.id.listitem_subname);
    
            //onClick
            itemView.setOnClickListener(this);
    
        }
    
        @Override
        public void onClick(View v) {
            //tampilkan toas ketika click
            Toast.makeText(v.getContext(),
                    String.format("Position %d", getAdapterPosition()),
                    Toast.LENGTH_SHORT).show();
        }
    
    }
  8. Buka MyRecyclerAdapter.java, perhatikan juga tambahannya:
  9. import android.content.Context;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Created by AbangAzmi on 11/14/2015.
     */
    public class MyRecyclerAdapter extends RecyclerView.Adapter<ItemController> {
    
        Context context;
        List<String> versionModels;
    
        //Array tambahan untuk picture
        public static List<String> ic = new ArrayList<String>();
    
        //Text
        public static List<String> titleOs = new ArrayList<String>();
        public static List<String> osSubList = new ArrayList<String>();
    
        //Set List Items
        public void setCardList(Context context) {
            
            //Ambil nama picture dari array list_icon
            String[] icon = context.getResources().getStringArray(R.array.list_icon);
            
            //text
            String[] listArray = context.getResources().getStringArray(R.array.os_version);
            String[] subTitleArray = context.getResources().getStringArray(R.array.os_sub_version);
            for (int i = 0; i < listArray.length; ++i) {
                ic.add(icon[i]);
                titleOs.add(listArray[i]);
                osSubList.add(subTitleArray[i]);
            }
        }
    
        public MyRecyclerAdapter(Context context) {
            this.context = context;
            setCardList(context);
        }
    
        public MyRecyclerAdapter(List<String> versionModels) {
            this.versionModels = versionModels;
    
        }
    
        @Override
        public ItemController onCreateViewHolder(ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_recycle, viewGroup, false);
            ItemController viewHolder = new ItemController(view);
            return viewHolder;
        }
    
        @Override
        public void onBindViewHolder(ItemController versionViewHolder, int i) {
            
            //Cari Picture di drawable sesuai nama dari array
            //lalu menyusunnya sesuai urutan dari atas ke bawah
            int listIcon = context.getResources().getIdentifier(String.valueOf(ic.get(i)),
                    "drawable", context.getPackageName());
            versionViewHolder.icon.setImageResource(listIcon);
    
            versionViewHolder.title.setText(titleOs.get(i));
            versionViewHolder.subTitle.setText(osSubList.get(i));
        }
    
        @Override
        public int getItemCount() {
    
            return titleOs == null ? 0 : titleOs.size();
        }
    }
  10. Hasilnya: 
  11. Selesai.. 
Semoga bermanfaat...

Minggu, 15 November 2015

Android: RecyclerView with Toolbar

6 komentar
INTRODUCTION
Pada posting kali ini kita akan bahas tentang Cardview dan Toolbar

RecyclerView
RecyclerView hampir sama dengan Listview dalam hal penggunaan adapter tapi dengan tampilan yang lebih baru dan dukungan yang lebih luas.

Toolbar
Toolbar adalah pengembangan Actionbar, di api-level 21 kebawah jika ingin menggunakan Toolbar maka harus memakai library appcompat-v7, tapi untuk api-level 23 keatas maka Toolbar sudah tersedia di framework tanpa perlu menggunakan library appcompat-v7.

REQUIREMENTS
Untuk menggunakan Cardview dan Toolbar diperlukan:
  • Android Studio atau Eclipse
  • SDK terbaru

EXAMPLE TOOLBAR & RECYCLERVIEW
  1. Buat project baru
  2. Pilih"Blank Activity" di jendela pemilihan template
  3. Setelah Android Studio menampilkan area kerja, buka file styles.xml di folder res/values, lalu ganti stylenya jadi NoActionBar, seperti ini :
  4. <resources>
    
        <!-- Base application theme. -->
        <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
            <!-- Customize your theme here. -->
        </style>
    
    </resources>

    Atau :
    <resources>
    
        <!-- Base application theme. -->
        <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
            <!-- Customize your theme here. -->
        </style>
    
    </resources>
  5. Bikin array string untuk membuat list. Caranya klik kanan di folder values pilih New >> Values resouce file, beri nama arrays
  6. Isikan ini kedaam file arrays.xml yang baru saja dibuat :
  7. <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string-array name="os_version">
            <item>Alpha</item>
            <item>Beta</item>
            <item>Cupcake</item>
            <item>Donut</item>
            <item>Eclair</item>
            <item>Frozen yogurt</item>
            <item>Ginger Bread</item>
            <item>Honeycomb</item>
            <item>Ice Cream Sandwich</item>
            <item>Jelly Bean</item>
            <item>Kitkat</item>
            <item>Lollipop</item>
            <item>Marshmallow</item>
        </string-array>
    
        <string-array name="os_sub_version">
            <item>Api Level 1.0</item>
            <item>Api Level 1.3</item>
            <item>Api Level 1.5</item>
            <item>Api Level 1.6</item>
            <item>Api Level 2.0</item>
            <item>Api Level 2.2</item>
            <item>Api Level 3.0 - 3.3</item>
            <item>Api Level 3.4</item>
            <item>Api Level 4.0.x</item>
            <item>Api Level 4.1.x - 4.2.x</item>
            <item>Api Level 4.4.x</item>
            <item>Api Level 5.x</item>
            <item>Api Level 6.0</item>
        </string-array>
    
    </resources>
  8. Bikin colors.xml di folder values, caranya sama dengan bikin arrays.
  9. Isikan ini :
  10. <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <!--Indigo 500-->
        <color name="primary_500">#3F51B5</color>
        <!--Indigo 700-->
        <color name="primary_700">#303F9F</color>
        <!--Pink 500-->
        <color name="accent_500">#E91E63</color>
        <!--Pink 700-->
        <color name="accent_700">#C2185B</color>
        <color name="black_trans80">#14000000</color>
    
    
        <color name="blue_grey">#455A64</color>
        <color name="red">#F44336</color>
        <color name="pink">#E91E63</color>
        <color name="purple">#9C27B0</color>
        <color name="deep_purple">#673AB7</color>
        <color name="indigo">#3F51B5</color>
        <color name="blue">#2196F3</color>
        <color name="light_blue">#03A9F4</color>
        <color name="cyan">#00BCD4</color>
        <color name="teal">#009688</color>
        <color name="green">#4CAF50</color>
        <color name="light_green">#8BC34A</color>
        <color name="lime">#CDDC39</color>
        <color name="yellow">#FFEB3B</color>
        <color name="amber">#FFC107</color>
        <color name="orange">#FF9800</color>
        <color name="deep_orange">#FF5722</color>
    </resources> 
  11. Tahap selanjutnya memasukkan library yang dibutuhkan yaitu:
    • appcompat-v7
    • cardview-v7
    • recyclerview-v7
    Caranya, klik kanan di folder project, pilih Open module settings, selanjutnya ikuti langkah di gambar berikut ini :


  12. Lakukan langkah diatas untuk memasukkan semua library.
    Atau memasukkan library bisa juga dengan cara manual asal kita mengetahui versi SDK yang kita pakai, misal versi 23.1.0, maka caranya buka file build.gradle di folder app, dibagian dependencies isikan ini :
  13.     compile fileTree(include: ['*.jar'], dir: 'libs')
        compile 'com.android.support:appcompat-v7:23.1.0'
        compile 'com.android.support:cardview-v7:23.1.0'
        compile 'com.android.support:recyclerview-v7:23.1.0'
     

    Sehingga menjadi
    
    apply plugin: 'com.android.application'
    
    android {
        compileSdkVersion 23
        buildToolsVersion "23.0.1"
    
        defaultConfig {
            applicationId "net.zam.samplecard"
            minSdkVersion 14
            targetSdkVersion 23
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }
    
    dependencies {
        compile fileTree(include: ['*.jar'], dir: 'libs')
        compile 'com.android.support:appcompat-v7:23.1.0'
        compile 'com.android.support:cardview-v7:23.1.0'
        compile 'com.android.support:recyclerview-v7:23.1.0'
    } 

  14. Setelah proses diatas, lakukan sinkronisasi gradle dengan mengklik ikon Sync Project with Gradle Files
  15. Bikin file shadow.xml di folder res/drawable, ini untuk menambah efek bayangan toolbar

  16. shadow.xml
    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <gradient
            android:angle="90"
            android:endColor="#80000000"
            android:startColor="@android:color/transparent" />
    </shape>

  17. Tahap selanjutnya membuat Layout, ada tiga layout yang akan kita buat yaitu

    • activity_main.xml
    • item_recycle.xml
    • toolbar.xml
    • jika sudah ada file activiy_main.xml ganti saja isinya.
       
       
      activity_main.xml
      <RelativeLayout 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:fitsSystemWindows="true"
          tools:context="net.zam.design.MainActivity">
      
          <FrameLayout
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:layout_marginTop="?attr/actionBarSize">
      
              <android.support.v7.widget.RecyclerView
                  android:id="@+id/home_recyclerview"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:clipToPadding="false" />
      
          </FrameLayout>
      
          <include layout="@layout/toolbar" />
      
      </RelativeLayout>

         
        item_recycle.xml
        <?xml version="1.0" encoding="utf-8"?>
        <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            android:orientation="vertical"
            android:id="@+id/cardlist_item"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            card_view:cardCornerRadius="4dp"
            card_view:cardElevation="@dimen/cardview_default_elevation"
            android:foreground="?android:attr/selectableItemBackground"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp">
        
            <LinearLayout
                android:layout_width="match_parent"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="8dp"
                android:paddingBottom="8dp"
                android:gravity="center_vertical"
                android:layout_height="?attr/listPreferredItemHeight"
                android:orientation="vertical">
        
                <TextView
                    android:id="@+id/listitem_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Android version name"
                    android:textColor="@color/primary_text_default_material_light"
                    android:textSize="@dimen/abc_text_size_subhead_material" />
        
                <TextView
                    android:id="@+id/listitem_subname"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Test"
                    android:paddingTop="3dp"
                    android:textColor="@color/secondary_text_default_material_light"
                    android:textSize="@dimen/abc_text_size_caption_material" />
            </LinearLayout>
        
        </android.support.v7.widget.CardView>

         
        toolbar.xml
        <?xml version="1.0" encoding="utf-8"?>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
        
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar_elevated"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/red"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
        
            <!-- Menambah effect shadow di toolbar -->
            <View
                android:layout_width="match_parent"
                android:layout_height="4dp"
                android:background="@drawable/shadow" />
        
        
        </LinearLayout>
        

    • Langkah selanjutnya membuat file java. Ada tiga yang akan kita buat :
      • MainActivity.java 
      • ItemController.java
      • MyRecyclerAdapter.java 


      MainActivity.java
      import android.content.Context;
      import android.os.Bundle;
      import android.support.v7.app.AppCompatActivity;
      import android.support.v7.widget.CardView;
      import android.support.v7.widget.DefaultItemAnimator;
      import android.support.v7.widget.LinearLayoutManager;
      import android.support.v7.widget.RecyclerView;
      import android.support.v7.widget.Toolbar;
      import android.view.Menu;
      import android.view.MenuItem;
      
      
      public class MainActivity extends AppCompatActivity {
      
          //Variable
          Toolbar toolbar;
          RecyclerView rv;
          MyRecyclerAdapter adapter;
          CardView cv;
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
      
              //Layout
              setContentView(R.layout.activity_main);
      
              //Toolbar
              toolbar = (Toolbar) findViewById(R.id.toolbar_elevated);
              if (toolbar != null) {
                  setSupportActionBar(toolbar);
              }
      
              toolbar.setTitle("");
      
              //Cardview
              cv = (CardView) findViewById(R.id.cardlist_item);
              rv = (RecyclerView) findViewById(R.id.home_recyclerview);
      
              rv.setHasFixedSize(true);
              rv.setLayoutManager(new LinearLayoutManager(this));
              rv.setItemAnimator(new DefaultItemAnimator());
      
              //Adapter
              if (adapter == null) {
                  adapter = new MyRecyclerAdapter(this);
                  rv.setAdapter(adapter);
              }
      
              final Context context = this;
          }
      
          //Menu
          @Override
          public boolean onCreateOptionsMenu(Menu menu) {
              // Inflate the menu; this adds items to the action bar if it is present.
              getMenuInflater().inflate(R.menu.menu_main, menu);
              return true;
          }
      
          @Override
          public boolean onOptionsItemSelected(MenuItem item) {
              // Handle action bar item clicks here. The action bar will
              // automatically handle clicks on the Home/Up button, so long
              // as you specify a parent activity in AndroidManifest.xml.
              int id = item.getItemId();
      
              //noinspection SimplifiableIfStatement
              if (id == R.id.action_settings) {
                  return true;
              }
      
              return super.onOptionsItemSelected(item);
          }
      
      }


      ItemController.java
      import android.support.v7.widget.CardView;
      import android.support.v7.widget.RecyclerView;
      import android.view.View;
      import android.widget.TextView;
      import android.widget.Toast;
      
      /**
       * Created by AbangAzmi on 11/14/2015.
       */
      public class ItemController extends RecyclerView.ViewHolder implements View.OnClickListener {
      
          //Variable
          CardView cardItemLayout;
          TextView title;
          TextView subTitle;
      
          public ItemController(View itemView) {
              super(itemView);
      
              //set id
              cardItemLayout = (CardView) itemView.findViewById(R.id.cardlist_item);
              title = (TextView) itemView.findViewById(R.id.listitem_name);
              subTitle = (TextView) itemView.findViewById(R.id.listitem_subname);
      
              //onClick
              itemView.setOnClickListener(this);
      
          }
      
          @Override
          public void onClick(View v) {
              //tampilkan toas ketika click
              Toast.makeText(v.getContext(),
                      String.format("Position %d", getAdapterPosition()),
                      Toast.LENGTH_SHORT).show();
          }
      }
      

      MyRecyclerAdapter.java
      import android.content.Context;
      import android.support.v7.widget.RecyclerView;
      import android.view.LayoutInflater;
      import android.view.View;
      import android.view.ViewGroup;
      
      import java.util.ArrayList;
      import java.util.List;
      
      /**
       * Created by AbangAzmi on 11/14/2015.
       */
      public class MyRecyclerAdapter extends RecyclerView.Adapter {
      
          Context context;
          List versionModels;
      
          public static List titleOs = new ArrayList();
          public static List osSubList = new ArrayList();
      
          //set item list
          public void setCardList(Context context) {
              String[] listArray = context.getResources().getStringArray(R.array.os_version);
              String[] subTitleArray = context.getResources().getStringArray(R.array.os_sub_version);
              for (int i = 0; i < listArray.length; ++i) {
                  titleOs.add(listArray[i]);
                  osSubList.add(subTitleArray[i]);
              }
          }
      
          public MyRecyclerAdapter(Context context) {
              this.context = context;
              setCardList(context);
          }
      
      
          public MyRecyclerAdapter(List versionModels) {
              this.versionModels = versionModels;
      
          }
      
          @Override
          public ItemController onCreateViewHolder(ViewGroup viewGroup, int i) {
              View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_recycle, viewGroup, false);
              ItemController viewHolder = new ItemController(view);
              return viewHolder;
          }
      
      
          @Override
          public void onBindViewHolder(ItemController versionViewHolder, int i) {
              versionViewHolder.title.setText(titleOs.get(i));
              versionViewHolder.subTitle.setText(osSubList.get(i));
      
          }
      
          @Override
          public int getItemCount() {
              return titleOs == null ? 0 : titleOs.size();
          }
      
      
      }
      
    • Jika ada error pada code java atau xml coba lakukan Sync Gradle seperti langkah 10.
    • Run project
    • Selesai
    Semoga bermanfaat...