Android Fragment Activity Communication

ChangeColorFragment.java

public class ChangeColorFragment extends Fragment {

    private OnChangeColorFragmentInteractionListener mListener;
    RadioGroup radioGroupColors;

    public ChangeColorFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.fragment_change_color, container, false);

        radioGroupColors= (RadioGroup) view.findViewById(R.id.radioGroupColors);

        radioGroupColors.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                onColorChanged(checkedId);
            }
        });

        return view;
    }

    public void onColorChanged(int id) {
        if (mListener != null) {
            mListener.onChangeColorFragmentInteraction(id);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnChangeColorFragmentInteractionListener) {
            mListener = (OnChangeColorFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnChangeColorFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnChangeColorFragmentInteractionListener {
        void onChangeColorFragmentInteraction(int id);
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity implements ChangeColorFragment.OnChangeColorFragmentInteractionListener{

    RelativeLayout layout;

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

        layout= (RelativeLayout) findViewById(R.id.activity_main);

        FragmentTransaction transaction= getSupportFragmentManager().beginTransaction();

        ChangeColorFragment changeColorFragment=new ChangeColorFragment();
        transaction.add(R.id.relativeLayoutFragmentContainer,changeColorFragment);

        transaction.commit();
    }

    @Override
    public void onChangeColorFragmentInteraction(int id) {
        switch (id)
        {
            case R.id.radioButtonRed:
                layout.setBackgroundColor(getResources().getColor(R.color.red));
                break;
            case R.id.radioButtonBlue:
                layout.setBackgroundColor(getResources().getColor(R.color.blue));
                break;
        }
    }
}

References
https://github.com/mhdr/AndroidSamples/tree/master/031

Android Working with RadioGroup

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="iterator.ir.a030.MainActivity">

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RadioButton
            android:text="Red"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radioButtonRed" />

        <RadioButton
            android:text="Blue"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radioButtonBlue" />
    </RadioGroup>
</RelativeLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {


    RadioGroup radioGroup;
    RelativeLayout layout;

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

        layout= (RelativeLayout) findViewById(R.id.activity_main);
        radioGroup= (RadioGroup) findViewById(R.id.radioGroup);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId)
                {
                    case R.id.radioButtonRed:
                        layout.setBackgroundColor(getResources().getColor(R.color.red));
                        break;
                    case R.id.radioButtonBlue:
                        layout.setBackgroundColor(getResources().getColor(R.color.blue));
                        break;
                }
            }
        });
    }
}

References
https://github.com/mhdr/AndroidSamples/tree/master/030

Android Add a Fragment to an Activity at Runtime

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="iterator.ir.a029.MainActivity">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="22dp"
        android:id="@+id/textView"
        android:text="@string/fragment_demo"
        android:textAppearance="@style/TextAppearance.AppCompat.Large" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:layout_marginTop="30dp"
        android:id="@+id/relativeLayoutFragment">

    </RelativeLayout>

    <Button
        android:text="First"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="36dp"
        android:layout_marginStart="36dp"
        android:layout_marginBottom="23dp"
        android:id="@+id/buttonFirstFragment" />

    <Button
        android:text="Second"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/buttonFirstFragment"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginRight="39dp"
        android:layout_marginEnd="39dp"
        android:id="@+id/buttonSecondFragment" />
</RelativeLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    Button buttonFirst;
    Button buttonSecond;

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

        final FragmentManager fragmentManager=getSupportFragmentManager();

        final FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();

        FirstFragment firstFragment=new FirstFragment();

        fragmentTransaction.add(R.id.relativeLayoutFragment,firstFragment);

        fragmentTransaction.commit();

        buttonFirst= (Button) findViewById(R.id.buttonFirstFragment);
        buttonSecond= (Button) findViewById(R.id.buttonSecondFragment);

        buttonFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final FragmentManager fragmentManager=getSupportFragmentManager();

                final FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();

                FirstFragment firstFragment=new FirstFragment();

                fragmentTransaction.replace(R.id.relativeLayoutFragment,firstFragment);

                fragmentTransaction.commit();
            }
        });

        buttonSecond.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final FragmentManager fragmentManager=getSupportFragmentManager();

                final FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();

                SecondFragment secondFragment=new SecondFragment();

                fragmentTransaction.replace(R.id.relativeLayoutFragment,secondFragment);

                fragmentTransaction.commit();
            }
        });
    }
}

References
https://github.com/mhdr/AndroidSamples/tree/master/029

Android Working with SeekBar

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="iterator.ir.a028.MainActivity">

    <SeekBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="21dp"
        android:id="@+id/seekBar"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/seekBar"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="42dp"
        android:id="@+id/textView" />
</RelativeLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    SeekBar seekBar;
    TextView textView;

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

        textView= (TextView) findViewById(R.id.textView);
        seekBar= (SeekBar) findViewById(R.id.seekBar);

        textView.setText(0 + " / " + seekBar.getMax());

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                textView.setText(progress + " / " + seekBar.getMax());
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }
}

References
https://github.com/mhdr/AndroidSamples/tree/master/028

Android Menu with Radio Button

/res/menu/menu_radio_button.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item android:id="@+id/itemWifi"
            android:title="@string/wifi" />
        <item android:id="@+id/itemBluetooth"
            android:title="@string/bluetooth" />
        <item android:id="@+id/itemData"
            android:title="@string/data" />
    </group>
</menu>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    Button buttonSelectNetwork;
    int previousSelectedNetwork =0;

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

        buttonSelectNetwork= (Button) findViewById(R.id.buttonSelectNetwork);

        buttonSelectNetwork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                registerForContextMenu(v);
                openContextMenu(v);
            }
        });
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);

        getMenuInflater().inflate(R.menu.menu_radio_button,menu);

        MenuItem itemWifi=menu.findItem(R.id.itemWifi);
        MenuItem itemBluetooth=menu.findItem(R.id.itemBluetooth);
        MenuItem itemData=menu.findItem(R.id.itemData);

        if (previousSelectedNetwork==1)
        {
            itemWifi.setChecked(true);
        }
        else if (previousSelectedNetwork==2)
        {
            itemBluetooth.setChecked(true);
        }
        else if (previousSelectedNetwork==3)
        {
            itemData.setChecked(true);
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        if (item.getItemId()==R.id.itemWifi)
        {
            previousSelectedNetwork =1;
            Toast.makeText(getBaseContext(),"Wifi",Toast.LENGTH_LONG).show();
        }
        else if (item.getItemId()==R.id.itemBluetooth)
        {
            previousSelectedNetwork =2;
            Toast.makeText(getBaseContext(),"Bluetooth",Toast.LENGTH_LONG).show();
        }
        else if (item.getItemId()==R.id.itemData)
        {
            previousSelectedNetwork =3;
            Toast.makeText(getBaseContext(),"Data",Toast.LENGTH_LONG).show();
        }

        return super.onContextItemSelected(item);
    }
}

References
https://github.com/mhdr/AndroidSamples/tree/master/027

Android Working with Popup Menu

/res/menu/popup_login.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/itemLoginAdmin"
        android:title="@string/login_admin" />
    <item android:id="@+id/itemLoginUser"
        android:title="@string/login_user" />
</menu>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    Button button;

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

        button= (Button) findViewById(R.id.buttonLogin);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popupMenu=new PopupMenu(getBaseContext(),v);
                popupMenu.getMenuInflater().inflate(R.menu.popup_login,popupMenu.getMenu());
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        if (item.getItemId()==R.id.itemLoginAdmin)
                        {
                            Toast.makeText(getBaseContext(),"Admin",Toast.LENGTH_LONG).show();
                            return true;
                        }
                        else if (item.getItemId()==R.id.itemLoginUser)
                        {
                            Toast.makeText(getBaseContext(),"User",Toast.LENGTH_LONG).show();
                            return true;
                        }

                        return false;
                    }
                });

                popupMenu.show();
            }
        });
    }
}

References
https://github.com/mhdr/AndroidSamples/tree/master/026

Android ListView with Contextual Action Mode

/res/menu/custom_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/itemShare"
        android:title="@string/share"
        android:icon="@drawable/ic_share_white_24dp" />
    <item android:id="@+id/itemDelete"
        android:title="@string/delete"
        android:icon="@drawable/ic_delete_white_24dp" />
</menu>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    ListView listViewCountries;
    ArrayList<String> countries=new ArrayList<>();
    ArrayList<String> selections=new ArrayList<>();

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

        String[] temp1=getResources().getStringArray(R.array.countries);

        for (String c:temp1)
        {
            countries.add(c);
        }

        listViewCountries= (ListView) findViewById(R.id.listViewCountries);
        final ArrayAdapter arrayAdapter=new ArrayAdapter(getBaseContext(),android.R.layout.simple_list_item_1,countries);
        listViewCountries.setAdapter(arrayAdapter);

        listViewCountries.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);

        listViewCountries.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
            @Override
            public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
                if (checked)
                {
                    selections.add(countries.get(position));
                }
                else {
                    selections.remove(countries.get(position));
                }

                mode.setTitle(selections.size() + " Selected");
            }

            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                getMenuInflater().inflate(R.menu.custom_menu,menu);
                return true;
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {

                if (item.getItemId()==R.id.itemDelete)
                {

                    for (String i:selections)
                    {
                        countries.remove(i);
                    }

                    arrayAdapter.notifyDataSetChanged();
                    mode.finish();

                    return true;
                }

                return false;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {
                selections.clear();
            }
        });


    }
}

References
https://github.com/mhdr/AndroidSamples/tree/master/025

Android Working with Contextual Action Mode

/res/menu/custom_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/itemDelete"
        android:title="@string/delete"
        android:icon="@drawable/ic_delete_black_24dp" />
    <item android:id="@+id/itemShare"
        android:title="@string/share"
        android:icon="@drawable/ic_share_black_24dp" />
</menu>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    ImageView imageView;
    ActionMode actionMode;

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

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

        imageView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                if (actionMode==null)
                {
                    actionMode=startActionMode(new android.view.ActionMode.Callback() {
                        @Override
                        public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {

                            getMenuInflater().inflate(R.menu.custom_menu,menu);

                            return true;
                        }

                        @Override
                        public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
                            mode.setTitle("Item Selected");
                            return true;
                        }

                        @Override
                        public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {

                            if (item.getItemId()==R.id.itemShare)
                            {
                                Toast.makeText(getApplicationContext(),"Share",Toast.LENGTH_LONG).show();
                                return true;
                            }
                            else if (item.getItemId()==R.id.itemDelete)
                            {
                                Toast.makeText(getApplicationContext(),"Delete",Toast.LENGTH_LONG).show();
                                return true;
                            }

                            return false;
                        }

                        @Override
                        public void onDestroyActionMode(android.view.ActionMode mode) {
                            actionMode=null;
                        }
                    });

                    return true;
                }

                return false;
            }
        });
    }
}

References
https://github.com/mhdr/AndroidSamples/tree/master/024

Configure Let’s Encrypt for Apache on Ubuntu

sudo apt-get install python-letsencrypt-apache 
letsencrypt --apache
nano /etc/apache2/apache2.conf
<VirtualHost *:443>
	SSLEngine on
	SSLCertificateKeyFile /etc/letsencrypt/live/dl.mhdr.ir/privkey.pem
	SSLCertificateFile /etc/letsencrypt/live/dl.mhdr.ir/cert.pem
	SSLCertificateChainFile /etc/letsencrypt/live/dl.mhdr.ir/chain.pem
    DocumentRoot "/var/www/html/dl"
    ServerName dl.mhdr.ir
</VirtualHost>
service apache2 restart

PPA

$ sudo add-apt-repository ppa:certbot/certbot
$ sudo apt-get update
$ sudo apt-get install python-certbot-apache

note : only the last VitualHost will be detected by letsencrypt
References
https://certbot.eff.org/#ubuntuxenial-apache
https://www.digitalocean.com/community/tutorials/how-to-use-apache-http-server-as-reverse-proxy-using-mod_proxy-extension
https://letsencrypt.org/

Android Handling Click Events of Floating Context Menu

MainActivity.java

public class MainActivity extends AppCompatActivity {

    ListView listViewCities;
    ArrayList<String> cities=new ArrayList<>();
    ArrayAdapter<String> arrayAdapter;

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

        listViewCities= (ListView) findViewById(R.id.listViewCities);

        String[] temp=getResources().getStringArray(R.array.cities);
        for (String city:temp)
        {
            cities.add(city);
        }

        arrayAdapter=new ArrayAdapter<String>(getBaseContext(), R.layout.custom_listview_layout,R.id.textViewCity,cities);

        listViewCities.setAdapter(arrayAdapter);

        registerForContextMenu(listViewCities);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);

        getMenuInflater().inflate(R.menu.contextual_menu,menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo contextMenuInfo= (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

        if (item.getItemId()==R.id.itemDelete)
        {
            cities.remove(contextMenuInfo.position);
            arrayAdapter.notifyDataSetChanged();
        }

        return super.onContextItemSelected(item);
    }
}

References
https://github.com/mhdr/AndroidSamples/tree/master/023