Showing posts with label Android. Show all posts

Sunday, September 23, 2018

thumbnail

Create Android spinner (drop down list) example


In this posted we show you how to do the following this:

1-Render a Spinner in XML, and load the selection items via XML file also.
2-Render another Spinner in XML, and load the selection items via code dynamically.
3-Attach a listener on Spinner, fire when user select a value in Spinner.
4-Render and attach a listener on a normal button, fire when user click on it, and it will display selected value of Spinner.
1. First we need to create list of items in spinner
 Open folder " res/values/strings.xml" file, and we need to definde the list of items
 
strings.xml file



<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">MyAndroidApp</string>
    <string name="country_prompt">Choose a country</string>

    <string-array name="country_arrays">
        <item>Thai</item>
        <item>United States</item>
        <item>Indonesia</item>
        <item>France</item>
        <item>Italy</item>
        <item>Singapore</item>
        <item>New Zealand</item>
        <item>India</item>
    </string-array>

</resources>
2 . Spinner (DropDown List)

Open folder "res/layout/main_activity.xml" and add spinner and button
1. "spinner1”, the “android:entries” represents the selection items in spinner.
2. “spinner2”, the selection items will be defined in code later.

  Open folder "res/layout/main_activity.xml" add the code below :

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

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/country_arrays"
        android:prompt="@string/country_prompt" />

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit" />

</LinearLayout>


3. In MainActivity.java

package com.spinner.example.android;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {

  private Spinner spinner1, spinner2;
  private Button btnSubmit;

  @Override
  public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);

 addItemsOnSpinner2();
 addListenerOnButton();
 addListenerOnSpinnerItemSelection();
  }

  // add items into spinner dynamically
  public void addItemsOnSpinner2() {

 spinner2 = (Spinner) findViewById(R.id.spinner2);
 List<String> list = new ArrayList<String>();
 list.add("list 1");
 list.add("list 2");
 list.add("list 3");
 ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
  android.R.layout.simple_spinner_item, list);
 dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 spinner2.setAdapter(dataAdapter);
  }

  public void addListenerOnSpinnerItemSelection() {
 spinner1 = (Spinner) findViewById(R.id.spinner1);
 spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
  }

  // get the selected dropdown list value
  public void addListenerOnButton() {

 spinner1 = (Spinner) findViewById(R.id.spinner1);
 spinner2 = (Spinner) findViewById(R.id.spinner2);
 btnSubmit = (Button) findViewById(R.id.btnSubmit);

 btnSubmit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {

     Toast.makeText(MyAndroidAppActivity.this,
  "OnClickListener : " + 
                "\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) + 
                "\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
   Toast.LENGTH_SHORT).show();
   }

 });
  }
}


Custom Select item


package com.spinner.example.android;

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;

public class CustomOnItemSelectedListener implements OnItemSelectedListener {

  public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
 Toast.makeText(parent.getContext(), 
  "OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
  Toast.LENGTH_SHORT).show();
  }

  @Override
  public void onNothingSelected(AdapterView<?> arg0) {
 // TODO Auto-generated method stub
  }

}

4 Run Our App












Monday, September 17, 2018

thumbnail

How to add Header in Listview Android?

In this posted I will talking about how to customize Header of ListView in android. I really tired to find more examples today I have solution to customize header of listview. let's start

Create new project in android studio.




and here is my code :
1. Create Custom Header layout

<?xml version="1.0" encoding="utf-8"?><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="wrap_content"    android:background="#4333"    android:orientation="vertical">

    <TextView        android:id="@+id/txtheader_excel_item"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_marginLeft="5dp"        android:layout_marginStart="5dp"        android:paddingTop="5dp"        android:paddingBottom="5dp"        android:text="Function for Math"        android:textAllCaps="false"        android:textColor="@android:color/black"        android:textSize="18sp"        android:textStyle="bold"        tools:layout_editor_absoluteX="101dp"        tools:layout_editor_absoluteY="2dp" />
</LinearLayout>

and next I create One Class call ExcelFragment extends from Fragment
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import android.widget.Filter;

public class ExcelFragment extends Fragment {

    ListView listView;
    TwoTextArrayAdapter adapter;
    @Override    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        items = new ArrayList <>();
        items.add(new Header("រូបមន្ត គណិតវិត្យា",getContext()));
        items.add(new ListItem("០១- ", "រូបមន្ត កូស៊ីនីស",getActivity()));
        items.add(new ListItem("០២-", "រូបមន្ត កូតង់សង់",getActivity()));
        items.add(new ListItem("០៣-", "រូបមន្ត ស៊ីនីស",getActivity()));
        items.add(new ListItem("០៤-", "រូបមន្ត ត្រីកោណមាត្រ",getActivity()));
        items.add(new Header("រូបមន្ត ស្វីតនព្ធន្ត",getContext()));
        items.add(new ListItem("Text 5", "Rabble rabble",getActivity()));
        items.add(new ListItem("Text 6", "Rabble rabble",getActivity()));
        items.add(new ListItem("Text 7", "Rabble rabble",getActivity()));
        items.add(new ListItem("Text 8", "Rabble rabble",getActivity()));
        items.add(new Header("Header 3",getContext()));
        items.add(new ListItem("Text 9", "Rabble rabble",getActivity()));
        items.add(new ListItem("Text 10", "Rabble rabble",getActivity()));
        items.add(new ListItem("Text 11", "Rabble rabble",getActivity()));
        items.add(new ListItem("Text 12", "Rabble rabble",getActivity()));




    }
//Required Constructor    public ExcelFragment(){}

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

        View v = inflater.inflate(R.layout.fragment_excel,container,false);
      //  excelList = new ArrayList <HashMap<String, String>>();        listView =(ListView)v.findViewById(R.id.list_excel_lesson);

        //Set Adapter for list        adapter = new TwoTextArrayAdapter(getActivity(), items);

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override            public void onItemClick(AdapterView <?> adapterView, View view, int position, long l) {
                Intent intent = new Intent(getContext(),SearchResultsActivity.class);
                startActivity(intent);
            }
        });
        return v;
    }


  
    }


Fragment Excel Layout  fragment_excel.xml

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

    <ListView        android:id="@+id/list_excel_lesson"        android:layout_width="match_parent"        android:layout_height="match_parent"        />
</LinearLayout>


Interface Item

import android.view.LayoutInflater;
import android.view.View;

public interface Item {
    public int getViewType();
    public View getView(LayoutInflater inflater, View convertView);
}



Class TwoTextArrayAdapter.java

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

import java.util.List;

public class TwoTextArrayAdapter extends ArrayAdapter<Item> {
    private static final int TYPE_ITEM = 0;
    private static final int TYPE_SEPARATOR = 1;
    private LayoutInflater mlaInflater;
    public enum RowType{
        LIST_ITEM,HEADER_ITEM    }
    public TwoTextArrayAdapter(@NonNull Context context, @NonNull List<Item> objects) {
        super(context, 0, objects);
        mlaInflater = LayoutInflater.from(context);
    }

    @Override    public int getViewTypeCount() {
        return RowType.values().length;

    }

    @Override    public int getItemViewType(int position) {
        return getItem(position).getViewType();
    }

    @Override    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;
        int rowType = getItemViewType(position);
        View View;
        if (convertView == null) {
            holder = new ViewHolder();
            switch (rowType) {
                case TYPE_ITEM:
                    convertView = mlaInflater.inflate(R.layout.list_ex_item, null);
                    holder.View=getItem(position).getView(mlaInflater, convertView);
                    break;
                case TYPE_SEPARATOR:
                    convertView = mlaInflater.inflate(R.layout.header_excel_item, null);
                    holder.View=getItem(position).getView(mlaInflater, convertView);
                    break;
            }
            convertView.setTag(holder);
        }
        else        {
            holder = (ViewHolder) convertView.getTag();
        }
        return convertView;
        //return getItem(position).getView(mlaInflater, convertView);    }

    public static class ViewHolder {
        public  View View; }

}

In MainActivity.java I create one method to add fragment


private void loadFragment(Fragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.mycontianer, fragment);
    transaction.addToBackStack(null);
    transaction.commit();
}

In onCreate method I add loadFragment to load item by default 

       loadFragment(new ExcelFragment());


activity_main.xml

<FrameLayout    android:id="@+id/mycontianer"    android:layout_width="match_parent"    android:layout_height="0dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"    app:layout_constraintBottom_toTopOf="@+id/bottomNavigation"    app:layout_constraintEnd_toEndOf="parent"    app:layout_constraintStart_toStartOf="parent"    app:layout_constraintTop_toBottomOf="@+id/TopNavigation"    tools:ignore="MissingConstraints">


</FrameLayout>




Let's run

Sunday, August 5, 2018

thumbnail

Integrating Google Admob Banner and Interstitial ads With Eclipse ADT

In this post we will talking about how to integrate AdMob in Android application with banner using Eclipse. with our example we will add admob banner on the top of our application by using ads test unite id, we will complete run this example so now let's start with eclipse IDE and following step by step :

Before we create project in eclipse we need to sign in your Admob account and create unite ads as banner. (ca-app-pub-6593689845821813/9312087245)

Get Google-Play-Service library 

make sure your Android SDK(System Development Kite) has been installed google play service in android manage. Open your eclipse tool and go to
1-  Windows  > Android SDK Manage


2- After completed install the project will download in to C:\Users\<User Name>\android-sdks\extras\google\google_play_services\libproject for Windows OS.

3- Import File>Import browse to  google play-service in extra folder  to your project work space follow with this :



Click Next it will popup like :


it will show google-play-service project folder in your current project work space. and next step we need to add google-play-service to our library follow this step: 

4- Right click on your Project go to Property of your project 


By Click Add button it will show 



Then click OK>Apply>OK

Now we go to our project in activity main.xml I create ads and assign id call @+id/adsview1

<com.google.android.gms.ads.AdView
   android:id="@+id/adsview1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerHorizontal="true"
   android:layout_alignParentBottom="true"
   ads:adSize="SMART_BANNER"
   ads:adUnitId="@string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView> 


AdMob provides test ad unit id for application development mode. After development we need to use actual ad unit id for your application.
Now we add banner UnitId in strings.xml


<string name="banner_ad_unit_id">ca-app-pub-3940256099942544/6300978111</string>
    
Android Manifest.xml add permissions meta data tag and Activity

Add Permissions 


<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
    
Add meta data 

<meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" /> 
Add Activity Class


<activity android:name="com.google.android.gms.ads.AdActivity"
   android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
   android:theme="@android:style/Theme.Translucent" /> 
Full Android Manufest.xml



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.grouprttcadmob"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
        <activity android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            android:theme="@android:style/Theme.Translucent" />
    </application>

</manifest>

Now we back to our activity_main.xml in this code it very important to add the code like below in our layout

xmlns:ads="http://schemas.android.com/apk/res-auto
So you can put ads on you activity

<com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ads:adSize="BANNER"
        ads:adUnitId="@string/ads_banner_unitId" />

In MainActivity class


public class MainActivity extends Activity {
    Utility utility;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  setBodyText();
  utility = new Utility(this);
  utility.setLayoutForSmartBanner();
  //Display smart banner ads
                AdView mAdView = (AdView) findViewById(R.id.adView);
                AdRequest adRequest = new AdRequest.Builder().build();
                mAdView.loadAd(adRequest);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
           getMenuInflater().inflate(R.menu.menu_main, menu);
           return true;
    }
}























MYMEMO. Powered by Blogger.