--> android source code full | Deskripsi Singkat Blog di Sini

Find The Complete Source Code Android


Sunday, February 18, 2018

Autofit Recyclerview

Autofit Recyclerview

Autofit Recyclerview  is used to show number of column which can be auto adjust with screen size. you can see it in this tutorial.





Steps to use Autofit Recyclerview in your project.

  1. Crate a project(Autofit Recyclerview Demo) in android studio.

  2. Create a Activity AutoFitGridRecyclerView.Java and update it-

    package com.pankaj.autofitrecyclerviewdemo;
    import android.content.Context;
    import android.content.res.TypedArray;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.util.AttributeSet;
    import android.view.MotionEvent;
    /**
    * Created by gsolc on 5/2/18.
    */
    public class AutoFitGridRecyclerView extends RecyclerView {
    private GridLayoutManager manager;
    private int columnWidth = -1;

    public AutoFitGridRecyclerView(Context context) {
    super(context);
    initialization(context, null);
    }

    public AutoFitGridRecyclerView(Context context, AttributeSet attrs) {
    super(context, attrs);
    initialization(context, attrs);
    }

    public AutoFitGridRecyclerView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    initialization(context, attrs);
    }

    private void initialization(Context context, AttributeSet attrs) {
    if (attrs != null) {
    // list the attributes we want to fetch
    int[] attrsArray = {
    android.R.attr.columnWidth
    };
    TypedArray array = context.obtainStyledAttributes(attrs, attrsArray);
    //retrieve the value of the 0 index, which is columnWidth
    columnWidth = array.getDimensionPixelSize(0, -1);
    array.recycle();
    }
    manager = new GridLayoutManager(context, 1);
    setLayoutManager(manager);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
    return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {
    super.onMeasure(widthSpec, heightSpec);
    if (columnWidth > 0) {
    //The spanCount will always be at least 1
    int spanCount = Math.max(1, getMeasuredWidth() / columnWidth);
    manager.setSpanCount(spanCount);
    }
    }
    }
     
  3. Create a class Data.java to hold data and update it-

    package com.pankaj.autofitrecyclerviewdemo;
    /**
    * Created by gsolc on 5/2/18.
    *
    * data model to hold data
    */

    public class Data {
    private String name;
    private String contact;
    public Data(String name, String contact) {
    this.name = name;
    this.contact = contact;
    }

    public Data() {
    }

    public String getName() {
    return name;
    }

    public String getContact() {
    return contact;
    }
    }
     
  4. Create a class MyAdapter.Java and update it-

    package com.pankaj.autofitrecyclerviewdemo;
    import android.content.Context;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    import java.util.List;
    /**
    * Created by gsolc on 5/2/18.
    */

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private List<Data> data;
    private Context context;
    public MyAdapter(List<Data> data, Context context) {
    this.data = data;
    this.context = context;
    }

    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    View view1 = inflater.inflate(R.layout.item, parent, false);
    ViewHolder viewHolder = new ViewHolder(view1);
    return viewHolder;
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
    holder.tvName.setText(data.get(position).getName());
    holder.tvContact.setText(data.get(position).getContact());
    }

    @Override
    public int getItemCount() {
    return data.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
    TextView tvName, tvContact;
    public ViewHolder(View itemView) {
    super(itemView);
    tvContact = itemView.findViewById(R.id.tvContact);
    tvName = itemView.findViewById(R.id.tvName);
    }
    }
    }
     
  5. Create a activity MainActivity.Java and update it-

    package com.pankaj.autofitrecyclerviewdemo;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.RecyclerView;
    import java.util.ArrayList;
    import java.util.List;

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //create and initialize recycler view object
    RecyclerView recyclerView = findViewById(R.id.recyclerView);

    //create dummy data to show in list
    List<Data> data = new ArrayList<>();
    for (int i = 10; i <= 100; i++)
    data.add(new Data("Name " + i, "9876543" + i));

    //create object of adapter and initialize it
    MyAdapter adapter = new MyAdapter(data, this);

    //if you want to use autofitgridview then no need to add layout manager
    //But for the simple verticle/horizontal list its required
    //LinearLayoutManager manager = new LinearLayoutManager(this);
    //LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
    //GridLayoutManager manager = new GridLayoutManager(this, 2);
    //recyclerView.setLayoutManager(manager);
    //set adapter

    recyclerView.setAdapter(adapter);
    }
    }
     

  6. Create a xml activity_main.xml and update it-

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 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="com.pankaj.autofitrecyclerviewdemo.MainActivity">

    <!--only one parameter is required to show autofit column is columnWidth -->
    <com.pankaj.autofitrecyclerviewdemo.AutoFitGridRecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="100dp" />
    </android.support.constraint.ConstraintLayout>

     
  7. Create a xml item.xml for adapter row and update it-

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

    <TextView
    android:id="@+id/tvName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:transitionName="@string/app_name" />

    <TextView
    android:id="@+id/tvContact"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:transitionName="@string/app_name" />
    </LinearLayout>

     
  8. All the application development process with Auto fit Recycler View has completed, Now run the app and look the screen.
    Note :
    Now change your device mode to portrait.


  9. Now change your device mode to landscape





  10. Good bye, Thanks to read this blog.

Monday, December 18, 2017

Base Activity

Base Activity

BaseActivity is used to reuse code on the different place for the same purpose. you can see it in this tutorial.





Steps to use BaseActivity in your project.

  1. Crate a project(BaseActivityDeleteDemo) in android studio.

  2. Create a Activity Activity1.Java and update it-

    package com.pankaj.mmm;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    public class Activity1 extends BaseActivity {
    private Button btnGetSelectedTag1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity1);
    super.onCreate(savedInstanceState);
    //initialization
    btnGetSelectedTag1 = findViewById(R.id.btnGetSelectedTag1);
    //Add Listeners
    btnGetSelectedTag1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    String message = "";
    for (String data : getSelectedTagList()) {
    if (!data.isEmpty())
    message += data + "\n";
    }
    message.trim();
    Toast.makeText(Activity1.this, message, Toast.LENGTH_SHORT).show();
    }
    });
    }
    public void openSecondActivity(View view) {
    Intent intent = new Intent(this, Activity2.class);
    startActivity(intent);
    }
    }


     
  3. Create a xml activity1.xml and update it-

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 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="com.pankaj.mmm.BaseActivity">

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/tag_layout" />

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
    android:id="@+id/btnGetSelectedTag1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:imeOptions="actionNone"
    android:text="Show entered Data" />

    <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:imeOptions="actionNone"
    android:onClick="openSecondActivity"
    android:text="Open Second Screen" />

    </LinearLayout>
    </LinearLayout>
    </android.support.constraint.ConstraintLayout>


     
  4. Create a activity Activity2.Java and update it-

    package com.pankaj.mmm;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    public class Activity2 extends BaseActivity {
    private Button btnGetSelectedTag2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity2);
    super.onCreate(savedInstanceState);
    //initialization
    btnGetSelectedTag2 = findViewById(R.id.btnGetSelectedTag2);
    //Add Listeners
    btnGetSelectedTag2.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    String message = "";
    for (String data : getSelectedTagList()) {
    if (!data.isEmpty())
    message += data + "\n";
    }
    message.trim();
    Toast.makeText(Activity2.this, message, Toast.LENGTH_SHORT).show();
    }
    });
    }
    }


     
  5. Create a interface CallBack.Java and update it-

    package com.pankaj.mmm;
    /**
    * Created by pankaj on 7/12/17.
    */

    public interface CallBacks {

    //to get event on select item
    void onSelected(String s);

    //to get event on delete item
    void onDeleted(int rowPosition);

    //to get event on done/enter click
    void onDone(String s);
    }


     
    Create a xml activity2.xml and update it-
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 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="com.pankaj.mmm.BaseActivity">

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <include layout="@layout/tag_layout" />

    <Button
    android:id="@+id/btnGetSelectedTag2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:imeOptions="actionNone"
    android:text="Show entered Data" />

    </LinearLayout>
    </android.support.constraint.ConstraintLayout>


     


  6. Create a activity BaseActivity.Java and update it-

    package com.pankaj.mmm;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    import android.widget.Toast;
    import java.util.ArrayList;
    import java.util.List;

    public class BaseActivity extends AppCompatActivity implements CallBacks {

    //create objects
    private RecyclerView rvTagList;
    private List<String> dataSelected = new ArrayList<>();
    private List<String> dataOptions = new ArrayList<>();
    private TagAdapter tagAdapter;

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

    public void initialization(){

    //Initialize list view
    rvTagList = findViewById(R.id.rvTagList);

    //Create layout manager
    LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

    //Set layout manager
    rvTagList.setLayoutManager(manager);

    //Add data to show entry point
    dataSelected.add("");

    //Create suggestions
    for (int i = 0; i < 500; i++) {
    dataOptions.add("data" + i);
    }

    //Initialize adapter
    tagAdapter = new TagAdapter(BaseActivity.this, dataSelected, dataOptions);

    //Set callbacks
    tagAdapter.setCallBacks(this);

    //Set adapter
    rvTagList.setAdapter(tagAdapter);
    }

    @Override
    public void onSelected(String selected) {

    //Check size and put data into selecteddata list
    if (dataSelected.size() > 1) {
    dataSelected.add(dataSelected.size() - 1, selected);
    } else {
    dataSelected.add(0, selected);
    }
    scrollToLastPosition(false);
    }

    @Override
    public void onDeleted(int rowPosition) {
    //Delete selected item
    dataSelected.remove(rowPosition);
    scrollToLastPosition(true);
    }

    @Override
    public void onDone(String selected) {

    //Check size and put data into selecteddata list
    if (dataSelected.size() > 1) {
    dataSelected.add(dataSelected.size() - 1, selected);
    } else {
    dataSelected.add(0, selected);
    }
    scrollToLastPosition(true);
    }

    private void scrollToLastPosition(boolean goToLast) {

    //notify adapter to refresh data in it
    tagAdapter.notifyDataSetChanged();
    // if (goToLast) rvTagList.scrollToPosition(dataSelected.size() - 1);
    }

    //function to show selected data
    public void selectedData(View view) {
    String message = "";
    for (String data : dataSelected) {
    if (!data.isEmpty())
    message += data + "\n";
    }
    message.trim();
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    public List<String> getSelectedTagList() {
    return dataSelected;
    }
    }


     
  7. Create a class TagAdapter.Java and update it-

    package com.pankaj.mmm;
    import android.app.Activity;
    import android.support.v7.widget.RecyclerView;
    import android.util.Log;
    import android.view.KeyEvent;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.AutoCompleteTextView;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    import java.util.List;
    /**
    * Created by pankaj on 7/12/17.
    */

    public class TagAdapter extends RecyclerView.Adapter<TagAdapter.MyViewHolder> {
    //Objects
    private String TAG = "TagAdapter";
    private List<String> dataOptions;
    private List<String> dataSelected;
    private Activity activity;
    private CallBacks callBacks;

    /**
    * View holder class
    */
    public class MyViewHolder extends RecyclerView.ViewHolder {
    private TextView tvText;
    private ImageView ivDelete;
    private AutoCompleteTextView tvAutocomplete;
    private LinearLayout llSelected;
    public MyViewHolder(View view) {
    super(view);
    tvAutocomplete = (AutoCompleteTextView) view.findViewById(R.id.tvAutocomplete);
    tvText = (TextView) view.findViewById(R.id.tvText);
    ivDelete = (ImageView) view.findViewById(R.id.ivDelete);
    llSelected = view.findViewById(R.id.llSelected);
    }
    }

    //Constructor
    public TagAdapter(Activity activity, List<String> dataSelected, List<String> dataOptions) {
    this.dataSelected = dataSelected;
    this.dataOptions = dataOptions;
    this.activity = activity;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int rowPosition) {
    if (rowPosition != dataSelected.size() - 1) {

    //Set null to listeners
    holder.tvAutocomplete.setOnItemClickListener(null);
    holder.tvAutocomplete.setOnEditorActionListener(null);

    //selected data
    holder.llSelected.setVisibility(View.VISIBLE);
    holder.tvAutocomplete.setVisibility(View.GONE);

    //Set data in cells
    holder.tvText.setText(dataSelected.get(rowPosition));

    //Add listener to delete cells
    holder.ivDelete.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
    //send event to delete selected cell
    callBacks.onDeleted(rowPosition);
    }
    });
    } else {

    //options in autocomplete
    //Hide cells
    holder.llSelected.setVisibility(View.GONE);
    holder.tvAutocomplete.setVisibility(View.VISIBLE);

    //Create adapter to show suggestion
    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, android.R.layout.simple_dropdown_item_1line, dataOptions);

    //Add adapter to show suggestion
    holder.tvAutocomplete.setAdapter(adapter);

    //reset entry point for new entry
    holder.tvAutocomplete.setText("");

    //Add listener to select item from suggestion
    holder.tvAutocomplete.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Log.e(TAG, holder.tvAutocomplete.getText() + " Position : " + position);

    //send event to add selected suggestion in cells
    callBacks.onSelected(holder.tvAutocomplete.getText().toString());
    }
    });

    //Add listener to create cell of entered data
    holder.tvAutocomplete.setOnEditorActionListener(new TextView.OnEditorActionListener() {

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

    Log.e(TAG, "" + actionId);

    //check if pressed on Ok/Done button
    if (actionId == 6) {
    if (holder.tvAutocomplete.getText().toString().trim().length() > 0) {

    //send event to add entered text in cells
    callBacks.onDone(holder.tvAutocomplete.getText().toString().trim());

    //reset entry point for new entry
    holder.tvAutocomplete.setText("");
    }
    }
    return false;
    }
    });
    }
    }

    @Override
    public int getItemCount() {
    return dataSelected.size();
    }

    //Initialize callbacks interface
    public void setCallBacks(CallBacks callBacks) {
    this.callBacks = callBacks;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
    .inflate(R.layout.row, parent, false);
    return new MyViewHolder(v);
    }
    }


     
  8. Create a xml row.xml to show individual selected item and update it-


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

    <LinearLayout
    android:id="@+id/llSelected"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="3dp"
    android:layout_marginLeft="3dp"
    android:layout_marginTop="3dp"
    android:background="@drawable/bg_button_with_corner_orange"
    android:gravity="center_vertical"
    android:padding="3dp">

    <TextView
    android:id="@+id/tvText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:editable="false"
    android:singleLine="true"
    android:text="@string/app_name" />

    <ImageView
    android:id="@+id/ivDelete"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:src="@android:drawable/ic_delete" />

    </LinearLayout>

    <AutoCompleteTextView
    android:id="@+id/tvAutocomplete"
    android:layout_width="200dp"
    android:layout_height="match_parent"
    android:imeOptions="actionDone"
    android:layout_marginLeft="5dp"
    android:background="@android:color/transparent"
    android:hint="@string/app_name"
    android:singleLine="true"
    android:textSize="12sp" />

    </LinearLayout>


     
  9. Create a xml tag_layout.Java and update it-


    <?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="wrap_content">

    <android.support.v7.widget.RecyclerView
    android:id="@+id/rvTagList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
    </LinearLayout>


     


  10. All the application development process with Base Activity has completed, Now run the app and look the screen. 














  11. Good bye, Thanks to read this blog.