Archive for January 2019

This is one of my favorites features, it helps you keep track of what is what on your activity, by displaying a popup on you device, this of it as alert on javascript.





1. import the Toast class

import android.widget.Toast;


2. display any message, anywhere within your code to show on device.

Toast.makeText(MainActivity.this, "Hello AppSpaza", Toast.LENGTH_LONG).show();

Note: MainActivity is the name of the class we currently on.















How to create a tip popup (Toast)

It is sometimes useful to have your own custom list, here we are going to create a custom layout with a switch, button and an image.


1. first, we need to create the xml file of our layout res/layout/sliding_item.xml

<?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:gravity="center"    android:background="@drawable/head_light_banner"    android:orientation="vertical"    android:id="@+id/car_light_banner">


    <ImageView        android:id="@+id/car_light"        android:layout_width="100dp"        android:layout_height="100dp"/>

    <TextView        android:id="@+id/car_light_title"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:background="@null"        android:textColor="#fff"        android:textSize="20dp"        android:text="Car Lights" />

    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="50dp"        android:gravity="center"        android:background="@null"        android:orientation="horizontal">

        <Switch            android:id="@+id/switch_plug"            android:layout_width="wrap_content"            android:layout_margin="10dp"            android:layout_height="wrap_content"            android:textSize="10dp"            android:trackTint="#fff"            android:checked="false"            android:colorForeground="#fff"/>

        <Button            android:id="@+id/detail_button"            android:layout_width="wrap_content"            android:layout_height="40dp"            android:textSize="10dp"            android:text="Detail" />

    </LinearLayout>

</LinearLayout>


2. in you res/layout/activity_main.xml

<android.support.v4.view.ViewPager    android:id="@+id/slider_view"    android:layout_width="match_parent"    android:layout_height="223dp"    android:layout_weight="1"    android:gravity="center" />


Notice that the name of our id is viewPager

3. now we will create our SlidingItem class

package com.designspaza.carcontroller;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.Toast;

    public class SlidingItem extends PagerAdapter {
        Context context;
        int car_light[];
        int car_light_banner[];
        int car_set_banner = -1;
        String car_light_title[];
        LayoutInflater layoutInflater;


        public CarLights(Context context, int car_light[],int car_light_banner[], String car_light_title[]) {
            this.context = context;
            this.car_light    = car_light;
            this.car_light_banner = car_light_banner;
            this.car_light_title = car_light_title;
            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override        public int getCount() {
            return car_light.length;
        }

        @Override        public boolean isViewFromObject(View view, Object object) {
            return view == ((LinearLayout) object);
        }

        @Override        public Object instantiateItem(ViewGroup container, final int position) {
            View CarLightView = layoutInflater.inflate(R.layout.car_lights, container, false);

            final ImageView CarLight = (ImageView) CarLightView.findViewById(R.id.car_light);
            CarLight.setImageResource(car_light[position]);

            final LinearLayout CarLightBanner = (LinearLayout) CarLightView.findViewById(R.id.car_light_banner);
            CarLightBanner.setBackgroundResource(car_light_banner[position]);

            TextView CarLightTitle = (TextView) CarLightView.findViewById(R.id.car_light_title);
            CarLightTitle.setText(car_light_title[position]);

            Switch SwitchPlug = (Switch) CarLightView.findViewById(R.id.switch_plug);

            Button DetailButton = (Button) CarLightView.findViewById(R.id.detail_button);

            container.addView(CarLightView);

            //listening to image click            CarLight.setOnClickListener(new View.OnClickListener() {
                @Override                public void onClick(View v) {
                    if( car_set_banner != car_light[position]) {
                        CarLightBanner.setBackgroundResource(car_light[position]);
                        car_set_banner = car_light[position];
                    }
                    else {
                        CarLightBanner.setBackgroundResource(car_light_banner[position]);
                        car_set_banner = car_light_banner[position];
                    }
                    Toast.makeText(context, "you clicked image " + (position + 1), Toast.LENGTH_LONG).show();
                }
            });


            //listening to switch flip            //SwitchPlug.setChecked(false);            SwitchPlug.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override                public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
                    if (bChecked) {
                        CarLight.setBackgroundColor(Color.rgb(255,255,255));
                        CarLight.setPadding(3,3,3,3);
                        Toast.makeText(context, "turn on " + (position + 1), Toast.LENGTH_LONG).show();
                    } else {
                        CarLight.setBackgroundColor(Color.rgb(0,0,0));
                        CarLight.setPadding(0,0,0,0);
                        Toast.makeText(context, "turn off " + (position + 1), Toast.LENGTH_LONG).show();
                    }

                }
            });

            //details direction for popup            DetailButton.setOnClickListener(new View.OnClickListener(){
                @Override                public void onClick(View v) {
                    //car lights intent                    Intent i = new Intent(context.getApplicationContext(), PopActivity.class);

                    i.putExtra("car_light_title", car_light_title[position]);
                    i.putExtra("car_light", car_light[position]);
                    context.startActivity(i);
                }
            });

            return CarLightView;
        }

        @Override        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((LinearLayout) object);
        }
    }

4. now lets edit your MainActivity.java class

public class MainActivity extends AppCompatActivity {


    //custom slider
    int car_light[] = {R.drawable.image_1, R.drawable.image_2, R.drawable.image_3};
    int car_light_banner[] = {R.drawable.head_light_banner, R.drawable.rear_light_banner, R.drawable.rear_light_banner};
    String car_light_title[] = {"Head Light","Rear Light","Stop Lights"};
    SlidingItem SlidingItem;


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

        //car lights        ViewPager viewPager = (ViewPager)findViewById(R.id.slider_view);
        SlidingItem = new SlidingItem(MainActivity.this, car_light,car_light_banner,car_light_title);
        viewPager.setAdapter(SlidingItem);



Note: we create our page viewer object and our SlidingItem class object, and pass through our array to our SlidingItem constructor.

I hope this article was clear



How To create custom Horizontal Slider using ViewPager

This is a nice trick to make your app more interactive. In this article i will show you an ImageView that can change its image resource after it has been clicked.





1. first, make sure you have you imageView class imported and you have an imageView in your layout file.

import android.widget.ImageView;

2. now i will show you the code to change your image resource

ImageView my_image = (ImageView) findViewById(R.id.my_image );


my_image.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {
        my_image.setImageResource(R.drawable.my_image_new);
    }
});

This will replace the current image resource of  my_image ImageView.




















How to change image resource of clicked imageView

Vibration adds a nice feel to your device, it makes the user feel part of your app and awaken. I am going to show you how to make your phone vibrate when you long press a button.





1. import the vibrate class

import android.os.Vibrator;

2. next, this will be the code that will listen for a long press, and make your phone vibrate.

button.setOnLongClickListener(new View.OnLongClickListener(){
    

    @Override    public boolean onLongClick(View v) {
        Vibrator vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(100);
        return true;
    }
});


Note: this will make your phone vibrate for 100 milliseconds, hence 1000ms is 1s

enjoy this nice feature.












How to make your device Vibrate onLong Click

This is a useful tool, especial if you have a complex UI. the ability to go back to your previously opened Activity.

1. first you need to import the menuItem class on your opened Second Activity.



import android.view.MenuItem;

2. next add the following code under

public class SecondActivity extends AppCompatActivity {

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

        //add back button        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

3. now paste the follow code.

@Overridepublic boolean onOptionsItemSelected(MenuItem item){
    int id = item.getItemId();

    if(id == android.R.id.home){
          this.finish();
    }

    return super.onOptionsItemSelected(item);
}


Its that simple, i hope this article was helpful.










How to add a Back button on Activity

One of the most coolest things you can add on your activity, is the ability to create a custom popup activity. Follow the steps bellow.

1. We are going to create a layout for our popup activity res/layout/popup_activity.xml the file name does not matter.



<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    tools:context="com.designspaza.carcontroller.PopupActivity"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#555"    android:gravity="center"    android:orientation="vertical"    android:id="@+id/pop_layout">

    <TextView        android:id="@+id/pop_title"        android:layout_width="wrap_content"        android:layout_height="50dp"        android:background="@android:color/transparent"        android:gravity="center_horizontal"        android:text="POP1"        android:textColor="#fff"        android:textSize="20sp" />

    <Button        android:id="@+id/close_btn"        android:layout_width="100dp"        android:layout_height="60dp"        android:text="Close" />
</LinearLayout>


2. next create the PopupActivity class to handle any View present on your popup

public class PopupActivity extends Activity {
@Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.popup_activity);

Note: popup_activity: is the name of our popup layout.

3. we need a theme for our popup, see below.

<style name="AppTheme.PopMe" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowCloseOnTouchOutside">true</item>
</style>

android:windowIsTranslucent: will make the pop up transparent beyond its borders.
android:windowCloseOnTouchOutside: will close the pop up when you click out side its borders.

4. we need to register our class with the manifest file manifests/AndroidManifest.xml

<activity    android:name=".PopupActivity"    android:theme="@style/AppTheme.PopMe" />


5. here i will show you how to actually display the popup after a click event.

    //details direction for popup    button.setOnClickListener(new View.OnClickListener(){
        @Override        public void onClick(View v) {
            Intent i = new Intent(context.getApplicationContext(), PopupActivity.class);
            context.startActivity(i);
        }
    });

Note: PopupActivity: is the name of our class.


I hope this was very helpful. Also read how to pass values to your popup activity.












How To create a pop up Activity on your current Activity

Add a splash screen, is a great way to open you app, especially if its graphics heavy like a game.

first create a xml file under the drawable folder (drawable/splash_screen.xml)




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

    <item android:drawable="@color/colorPrimary"/>

    <!-- Set the Background Image-->    <item android:gravity="center" android:width="500dp" android:height="500dp">
        <bitmap            android:gravity="fill_horizontal|fill_vertical"            android:src="@drawable/splash_screen_image"/>
    </item>
</layer-list>

You can add a new theme under your res/values/styles.xml file

<style name="SplashScreenTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name ="android:windowBackground"> @drawable/splash_screen</item>
</style>

NOTE: splash screen will only work if you use the parent theme.AppCompat and your MainActivity class needs to extend the AppCompatActivity class. see below

public class MainActivity extends AppCompatActivity {

Now all you have to do is change some lines in you manifests/AdroidManifest.xml file

<activity    android:name=".SplashActivity"    android:theme="@style/SplashScreenTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name=".MainActivity" />


As you can see, we are telling our app to use the SplashScreenTheme theme when it LAUNCHER. And the SplashScreenTheme reference drable/splash_screen as its windowBackground.

I hope this article has been helpful.































How to add a Splash Screen to your Android App

This will be one of the features you will use the most, so its best you get the handle of it now.

create a file under res/menu/app_menu_bar.xml and paste the code below.



<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    >
    <item        android:id="@+id/harzard_menu"        android:title="Harzard"        android:icon="@mipmap/harzard_sign"        app:showAsAction="ifRoom"    />

    <item        android:id="@+id/indicator_left"        android:title="Indicator Left"        android:icon="@mipmap/indicator_left_on"        app:showAsAction="ifRoom"        />

    <item        android:id="@+id/indicator_right"        android:title="Indicator right"        android:icon="@mipmap/indicator_left_on"        app:showAsAction="never"        />

</menu>


looking at the above code
ifRoom: menu icon will only if the is room on the menu bar.

Never: menu item will only show if you click on the ... vertical icon.

@mipmap/: This is where the compiler will look for the item's icon. res/mipmap

now open you MainActivity.java and paste the following code under the MainActivity class.


@Overridepublic boolean onCreateOptionsMenu(Menu menu){
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.app_bar_menu, menu);

    return true;
}

@Overridepublic boolean onOptionsItemSelected(MenuItem item){
    int id = item.getItemId();

    if(id == R.id.harzard_menu){
        //your code here
    }
    else if(id == R.id.indicator_left){
        //your code here
    }
    else{
        //your code here
    }

    return false;

}



We have two functions on the above code, first we override the onCreateOptionsMenu 
function and inflate our app_bar_menu.xml layout.

New we override the onOptionsItemSelected function to help us identify which menu item has
been clicked. 

READ >> How to make a clickable items to a new Activity











































How To create Menu Bar with clickable item


This is a very useful piece of code, playing simple sound effect on your app.

first open, res/raw/ and save your sound file inside the raw folder.

next you need to import the media class in your MainActivity.

import android.media.MediaPlayer;

now you can load your sound effect into your activity.

car_alarm = MediaPlayer.create(this, R.raw.car_alarm);

you may set loop, to have your effect play end to end.

car_alarm.setLooping(true);

finally you can have your sound played by the media class.

car_alarm.isPlaying();

use stop and then release once you no longer need it.

car_alarm.stop(); 
car_alarm.release();

It is said to be good practice to destroy your object, for memory reasons, this is how you do so.

@Overrideprotected void onDestroy()
{
    // stop the sounds    if(car_alarm.isPlaying()) car_alarm.stop(); car_alarm.release();
    super.onDestroy();
}

place above code inside your MainActivity class.














How To play sound on your Android app


Sometimes you may need to have a click and a long click (press) on the same View, here is how you can avoid triggering both event.





//button view 
button.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {
       //your code here
   }
});


button.setOnLongClickListener(new View.OnLongClickListener() {
@Override public boolean onLongClick(View v) { //your code here return true; } });


By setting onLongClick return to true, you are telling the compiler that you have handled onLongClick event, no need to trigger the onClick event.


How To separate a LongClick from a Click event


It is very useful to have an app that is able to access different Activities and pass values (Intent) that can be used by the new Activity.






In file /MainActivity.java import the intent class.

import android.content.Intent;



Now paste the following code inside MainActivity class

Intent i = new Intent(MainActivity.this.getApplicationContext(), NewActivity.class);


NewActivity: This is the name of the class of the activity you wish to load on your app.

Now use PushExtra to pass values into the NewActivity.

i.putExtra("title", "Any Text");
i.putExtra("image", R.drawable.harzard_sign);


looking above, line_1 shows how to pass a String valuable, and line_2 show how to pass
a drawable.

Once you done, you may start new activity.

startActivity(i);


Now lets access your /New_Activity.java file, first import the intent class

import android.content.Intent;


Now use the below code to access the values you just pass.

//get valuables
Intent intent = getIntent();
String menu_title = intent.getExtras().getString("title_text");
int menu_icon = intent.getExtras().getInt("image_view");


I hope this helps you will your android development journey.

How To click to a new Activity and pass values

- Copyright © Mdunge Apps - Blogger Templates - Powered by Blogger - Designed by Johanes Djogan -