battle programminga forum for elite programmerswith extreme will powerto sharpen theire skills
 
HomeCalendarFAQSearchMemberlistUsergroupsRegisterLog in
Share | 
 

 android mobile app dev APK

Go down 
Go to page : 1, 2, 3  Next
AuthorMessage
Admin
Admin
avatar

Posts : 120
Join date : 2011-08-01

PostSubject: android mobile app dev APK   Tue May 01, 2018 10:23 pm



1 android studio
2 JDK
3A in android studio - virtual mobile machine :
tool strip, tools, AVD manager, in the now appeared window : +create device, select devices with
the google play store symbol, next, select version : oreo (download), wait... wait, wait some more

3B tool strip, tools, SDK manager, SDK platforms tab : those are the SDKs your app will support
choose : 4.3 and above: corresponding to API lvl : 15,18,25,27 those are the criticle ones.

3c choose the SDK tools tab, check the : sdk build tools, android emulator, android sdk platform tools,
android sdk tools, google play servicesgoogle play APK, google play licencing library, instant apps deployment SDK
intel x86 emulator

3d : click apply, wait.
4 alternative to VM : GenyMotion
it simulates physical devices as if they are actually connected to your machine.
so when you run the app it will show on connected devices.
https://www.genymotion.com/download/
choose the installation with VirtualBox
5 install Vysor to cast your android screen on to the computer
7 enable developer mode & USB debugging mode on your phone :
open your mobil device for developing search the walkthrough for your phone.
mostly it is : all apps, settings, build number, click build number 7 times, rego to
settings, developer options, enable debugging and usb debugging.

on android studio, tool strip, file, settings, appearance (for IDE visual customization)

8 enable virtual devices :
windows key + R
type msinfo32
search the field with hyper v virtualization, this must be enabled Fix VT-x is disabled in BIOS :

press and hold shift key and restart your computer
choose trouble shoot, advanced options, UEFI firmware options, restart.
choose bios settings, go to advanced tab, enable virtualization technology, exit with save changes.

9 with android studio some of the files it downloads need to be installed externally.
install : intelhaxm-android from : "C:\Users\Lenovo\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager"
Lenovo = comuter name
(HAXM). now the emulator should work.

drunken

_________________
kurayami no kagi  _____    
Back to top Go down
View user profile http://yotamarker.forumotion.com
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android studio hello world   Tue May 08, 2018 8:15 pm


if you leave the project name as the default exercise it will not be uploadable to the google play store.

in the solution explorer window :
app :
java : where your activity code
res : layout : the activities xml files (how the app windows look (widgets))


the xml can be manipulated by drag droping in the design tab or with the text tab :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:onClick="TestHelloWorld"
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginStart="63dp"
        android:text="Button" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="16dp"
        android:layout_marginTop="81dp"
        android:ems="10"
        android:inputType="textPersonName" />

</RelativeLayout>
notice you need to change the 2nd line to RelativeLayout as you see above and
it automatically changes the corresponding closing tag.
also notive I added a btn and a textbox.

when you add in the btn the line :
android:onClick="TestHelloWorld"
it offers you to generate onClick event code in the X activity (main activity here)
in the java folder, 1st folder main activity make the code :
Code:
package com.example.lenovo.myapplication1;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText t1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(getApplicationContext(), "moti", Toast.LENGTH_LONG).show();
        t1 = findViewById(R.id.editText); // links var to textbox
    }
// btn click event :
    public void TestHelloWorld(View view) {
        String str1 = t1.getText().toString();
        Toast.makeText(this,"moti rulz " + str1,Toast.LENGTH_LONG).show();
    }
}
run the code.

in the next code I harness the button and make its text display it's click count :
Code:
package com.example.lenovo.myapplication1;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText t1;
    Button btn1;
    int c =0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(getApplicationContext(), "moti", Toast.LENGTH_LONG).show();
        t1 = findViewById(R.id.editText);
        btn1 = findViewById(R.id.button); // btn name id = button
    }

    public void TestHelloWorld(View view) {
        String str1 = t1.getText().toString();
        Toast.makeText(this,"moti rulz " + str1,Toast.LENGTH_LONG).show();
        c++;
        String sTemp = c + "";
        btn1.setText(sTemp);
    }
}
sometimes the IDE will mark some code with red as an error cause it needs to import stuff or what ever
so press alt + enter to fix it.

to create classes right click the solution explorer window, new, java class
press alt + insert to add setters getters and constructores geek

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: changing android studio theme   Tue May 08, 2018 9:56 pm


_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: controllers (activeX)   Sun May 13, 2018 6:27 pm

the following app builds a toast message using radio group buttons +
pile of check boxes.
the cassier will select his problem (radio)
the cassier will select person to summon (check box)
a message is built accordingly
the controllers (radio group, check boxes are reset)

xml design (solution explorer, res folder, layout):
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtName"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <!-- this is a comment -->
    <!-- android:layout_below = set controller location -->
    <!--android:id = controller name-->
    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/radioGroup"
        android:layout_below="@id/txtName">

        <RadioButton
            android:id="@+id/rbChange"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="need change" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="permission to return product"
            android:id="@+id/rbReturn"/>

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="else"
            android:id="@+id/rbElse"/>
    </RadioGroup>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="send to vice"
        android:id="@+id/chkVice"
        android:layout_below="@id/radioGroup"/>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="send to manager"
        android:id="@+id/chkManager"
        android:layout_below="@id/chkVice"/>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="send to supervisor"
        android:id="@+id/chkSupervisor"
        android:layout_below="@id/chkManager"/>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="send to coWorker"
        android:id="@+id/chkTall"
        android:layout_below="@id/chkSupervisor"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="summon"
        android:id="@+id/btnOrder"
        android:textAllCaps="false"
        android:layout_below="@id/chkTall"
        android:layout_centerHorizontal="true"
        android:onClick="summon"
        />
</RelativeLayout>
main activity (fire up when the app starts) :
(solution explorer, java folder, 1st sub folder):


Code:
package com.example.lenovo.cassiersummoner;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    Button btnCbOrder;
    RadioGroup radioCbGroup;

    TextView txtCbName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnCbOrder = findViewById(R.id.btnOrder);
        radioCbGroup = findViewById(R.id.radioGroup);
        txtCbName = findViewById(R.id.txtName);
    }
    public void summon(View view) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("Hello, " + "\n");
        buffer.append(((CheckBox)(findViewById(R.id.chkManager))).isChecked() ? "\nmanager" : "");
        buffer.append(((CheckBox)(findViewById(R.id.chkVice))).isChecked() ? "\nvice" : "");
        buffer.append(((CheckBox)(findViewById(R.id.chkSupervisor))).isChecked() ? "\nsupervisor" : "");
        buffer.append(((CheckBox)(findViewById(R.id.chkTall))).isChecked() ? "\nworker" : "");
        buffer.append(" " + getSummon());
        Toast.makeText(this,buffer.toString() ,Toast.LENGTH_LONG).show();
        resetForm();
    }
    public void resetForm(){
        ((CheckBox)(findViewById(R.id.chkManager))).setChecked(false);
        ((CheckBox)(findViewById(R.id.chkSupervisor))).setChecked(false);
        ((CheckBox)(findViewById(R.id.chkTall))).setChecked(false);
        ((CheckBox)(findViewById(R.id.chkVice))).setChecked(false);
        radioCbGroup.clearCheck();
        txtCbName.setText("");
    }

    public String getSummon(){
        switch (radioCbGroup.getCheckedRadioButtonId()){
            case R.id.rbChange:
                return "change needed";
            case R.id.rbReturn:
                return "customer wants to return a product";
            case R.id.rbElse:
                return "need you at the register";
            default:
                return "test message";
        }
    }
}

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: spinner controller   Sun May 13, 2018 8:13 pm



spinner controller (see comments for Xplnation)

xml design :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:id="@+id/spnNames"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnAdd"
        android:text="Add"
        android:textAllCaps="false"
        android:layout_below="@id/spnNames"
        android:layout_alignParentRight="true"
        android:onClick="newName"
        />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtName"
        android:layout_below="@id/spnNames"
        android:hint="Enter Name..."
        android:layout_toLeftOf="@id/btnAdd"
        android:textAlignment="center"/>

</RelativeLayout>

main activity :
Code:
package com.example.lenovo.spinner;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    // shadow clone the controllers declaration
    Spinner spnCbNames;
    EditText txtCbName;
    List<String> lstNames;
    ArrayAdapter<String> arrayAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lstNames = new ArrayList<>();
        initControllers(); // connect shallow clones to controllers
        arrayAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_dropdown_item,
                lstNames); // link spinner to its components :
        spnCbNames.setAdapter(arrayAdapter);
        // get the selected item
        http://spnCbNames.getSelectedItem();
        // listener - to perform an action when item is selected
        spnCbNames.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this,
                        lstNames.get(position), Toast.LENGTH_SHORT).show();
                // lstNames.get(position) returns the item itself not a position
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void initControllers(){
        spnCbNames = findViewById(R.id.spnNames);
        txtCbName = findViewById(R.id.txtName);
    }

    public void newName(View view) {
        // btn on click event summoned from the xml file of the activity
        lstNames.add(txtCbName.getText().toString());
        txtCbName.setText("");
        arrayAdapter.notifyDataSetChanged(); // updates the spinner organs
    }
}

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: change the apps background picture using code   Mon May 14, 2018 7:08 am



xml design code (activity_main.xml):
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:id="@+id/mainActivityLayout"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</RelativeLayout>

notice in the above code I named the layout :
android:id="@+id/mainActivityLayout"
and the 1st line was changed to : <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

main activity code (mainActivity.java):
Code:
package com.example.lenovo.screenbg;

import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    RelativeLayout r1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        r1 = findViewById(R.id.mainActivityLayout);
        r1.setBackgroundDrawable(ContextCompat.getDrawable(this,R.drawable.aoitori));
    }
}

finally the aoitori.jpg picture was added to the res, drawable in the solution explorer window

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: simple list view rapid walkthrough   Tue May 15, 2018 7:38 pm

simple list view :

xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtItem"
        android:textAlignment="center"
        android:hint="enter Item"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="save"
        android:textAllCaps="false"
        android:id="@+id/btnSave"
        android:layout_below="@id/txtItem"
        android:layout_centerHorizontal="true"
        android:onClick="newItem"
        />
    <!--Divider code in ListView-->
    <ListView
        android:id="@+id/simpleListView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#f00"
        android:dividerHeight="1dp"
        android:layout_below="@id/btnSave"
        />

</RelativeLayout>
activity code :
Code:
package com.example.lenovo.mylistview2;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List<String> words;
    private ListView lv1;
    private EditText txtItem;
    private ArrayAdapter<String> arrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        words = new ArrayList<>();
        lv1 = findViewById(R.id.simpleListView);
        txtItem = findViewById(R.id.txtItem);
        arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_activated_1,words);
        lv1.setAdapter(arrayAdapter);
    }


    public void newItem(View view) {
// btn xml onClick event
        words.add(txtItem.getText().toString());
        txtItem.setText("");
// update list view (lv1) with the words in the list words
        arrayAdapter.notifyDataSetChanged();
    }
}



_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android studio custom list view walkthrough   Thu May 17, 2018 6:22 am



polimarization !!!







exmple : contact list
each contact has : image name phone number

main activity xml :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtName"
        android:textAlignment="center"
        android:hint="Enter Item"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtPhone"
        android:textAlignment="center"
        android:layout_below="@id/txtName"
        android:hint="Enter Item"/>
    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/radioGroupImg"
        android:layout_below="@id/txtPhone"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal">
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="work"
            android:id="@+id/rbWork"
            android:checked="true"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="cell"
            android:id="@+id/rbCell"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Home"
            android:id="@+id/rbHome"/>

    </RadioGroup>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"
        android:textAllCaps="false"
        android:id="@+id/btnSave"
        android:layout_below="@id/radioGroupImg"
        android:layout_centerHorizontal="true"
        android:onClick="newContact"/>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lstItems"
        android:divider="#f00"
        android:dividerHeight="1dp"
        android:layout_below="@id/btnSave"/>

</RelativeLayout>

partinias xml = custom list view element inflation appearans:

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

    <ImageView
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:id="@+id/imgContact"
        android:src="@mipmap/ic_launcher"
        android:layout_margin="5dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/lblName"
        android:layout_toRightOf="@id/imgContact"
        android:layout_toEndOf="@id/imgContact"
        android:text="Contact Name"
        android:textSize="16dp"
        android:layout_centerVertical="true"
        android:layout_marginLeft="8dp"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtContactName"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@id/imgContact"
        android:layout_toEndOf="@id/imgContact"
        android:visibility="invisible"
        android:layout_toLeftOf="@id/btnEdit"
        android:layout_toStartOf="@id/btnEdit" />

    <ImageButton
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:id="@+id/btnEdit"
        android:src="@drawable/edit"
        android:layout_toLeftOf="@id/btnDel"
        android:layout_centerVertical="true"
        android:visibility="invisible"
        />
    <ImageButton
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:id="@+id/btnDel"
        android:src="@drawable/del"
        android:layout_toLeftOf="@id/btnDone"
        android:layout_centerVertical="true"
        android:visibility="invisible"
        />
    <ImageButton
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:id="@+id/btnDone"
        android:src="@drawable/save"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:visibility="invisible"
        />


</RelativeLayout>

contact java class :

Code:
package com.justforum.yotamarker.contacts;

import android.support.annotation.DrawableRes;

public class Contact {

    private String name;
    private String phone;
    // Will limit the image variable to get only R.drawable.something as int value
    private @DrawableRes int image;

    public Contact(String name, int image, String phone) {
        this.name = name;
        this.image = image;
        this.phone = phone;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public @DrawableRes int getImage() {
        return image;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public void setImage(@DrawableRes int image) {
        this.image = image;
    }
}

regex java class

Code:
package com.justforum.yotamarker.contacts;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class regexifier {
    public static String regexChecker(String theRegex, String str2Check) {
        // You define your regular expression (REGEX) using Pattern
        Pattern checkRegex = Pattern.compile(theRegex);
        // Creates a Matcher object that searches the String for
        // anything that matches the REGEX
        Matcher regexMatcher = checkRegex.matcher(str2Check);
        // Cycle through the positive matches and print them to screen
        // Make sure string isn't empty and trim off any whitespace
        while (regexMatcher.find()) {
            if (regexMatcher.group().length() != 0) {
                return regexMatcher.group().trim();
//                System.out.println(regexMatcher.group().trim());
//                // You can get the starting and ending indexs
//                System.out.println("Start Index: " + regexMatcher.start());
//                System.out.println("Start Index: " + regexMatcher.end());
            }
        }
        return "err";
    }
}

example partinias java class (adjusted for the contact class):
fuses main xml's listview with partinias xml

Code:
package com.justforum.yotamarker.contacts;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

public class partinias extends ArrayAdapter {

    private ArrayList<Contact> arrayList;
    private Activity mActivity;
    public partinias(@NonNull Activity context, int resource, ArrayList<Contact> arrayList) {
        super(context, resource);
        this.arrayList = arrayList;
        this.mActivity = context;
    }

    // will help the ListView to know how many items need to be created
    @Override
    public int getCount() {
        return arrayList.size();
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View view, @NonNull ViewGroup parent) {

        LayoutInflater inflater = mActivity.getLayoutInflater();
        // attachToRoot - if the layout is inside the root layout, or in a different layout
        view = inflater.inflate(R.layout.partinias, parent, false);

        TextView lblCbName = view.findViewById(R.id.lblName);
        ImageView imgCbContact = view.findViewById(R.id.imgContact);

        Contact contact = arrayList.get(position);

        lblCbName.setText(contact.getName() + " " + contact.getPhone());
        imgCbContact.setImageDrawable(ContextCompat.getDrawable(mActivity, contact.getImage()));

        return view;
    }
}

main activity :

Code:
package com.justforum.yotamarker.contacts;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {
    // Class Variables, will live through the Class life cycle.
    EditText txtCbName;
    EditText txtPhone;
    RadioGroup radioGroupCbImg;
    ListView lstCbContacts;
    ArrayList<Contact> contactsList;
    partinias adapter;
    int lastPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Point to all ID's in XML, using variables
        initControllers();
        contactsList = new ArrayList<>();
        adapter = new partinias(this,
                R.layout.partinias, contactsList);
        lstCbContacts.setAdapter(adapter);
        setListViewListener();
    }



    public void initControllers(){
        // Assign the variables to the object using findViewById to find the object with ID
        txtCbName = findViewById(R.id.txtName);
        txtPhone = findViewById(R.id.txtPhone);
        radioGroupCbImg = findViewById(R.id.radioGroupImg);
        lstCbContacts = findViewById(R.id.lstItems);
    }


    public void setListViewListener(){
        lstCbContacts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                // Will clear the last clicked item and return it back to normal;
                clearLastCheckedItem();
                ImageButton btnCbDel = view.findViewById(R.id.btnDel);
                ImageButton btnCbEdit = view.findViewById(R.id.btnEdit);
                ImageButton btnCbDone = view.findViewById(R.id.btnDone);
                btnCbDel.setVisibility(View.VISIBLE);
                btnCbEdit.setVisibility(View.VISIBLE);
                btnCbDone.setVisibility(View.VISIBLE);
                final EditText txtCbContactName = view.findViewById(R.id.txtContactName);
                final TextView lblCbName = view.findViewById(R.id.lblName);
                btnCbDel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        contactsList.remove(position);
                        adapter.notifyDataSetChanged();
                    }
                });
                btnCbEdit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        txtCbContactName.setText(lblCbName.getText().toString());
                        txtCbContactName.setVisibility(View.VISIBLE);
                        lblCbName.setVisibility(View.INVISIBLE);
                    }
                });
                btnCbDone.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String value = txtCbContactName.getText().toString();
                        String newphone = regexifier.regexChecker("([0][0-9]{9})",value);
                        value = value.substring(0,value.indexOf(" "));

                        if(!value.isEmpty()){
                            contactsList.get(position).setName(value);
                            contactsList.get(position).setPhone(newphone);
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
                lastPosition = position;
            }
        });
    }

    // Check which Radio Button checked by the user
    public int chosenImage(){
        switch (radioGroupCbImg.getCheckedRadioButtonId()){
            case R.id.rbHome:
                return R.drawable.home;
            case R.id.rbCell:
                return R.drawable.phone;
            case R.id.rbWork:
                return R.drawable.work;
            default:
                return R.mipmap.ic_launcher;
        }
    }
    public void newContact(View view) {
        String phoneNumInput = regexifier.regexChecker("([0][0-9]{9})", txtPhone.getText().toString());
        if(phoneNumInput=="err"){
            Toast.makeText(this,"phone number must be 10 digits and start with 0", Toast.LENGTH_LONG).show();
            txtPhone.setText("");
        }else{
            contactsList.add(new Contact(txtCbName.getText().toString(), chosenImage(), phoneNumInput));
            txtCbName.setText("");
            txtPhone.setText("");
            adapter.notifyDataSetChanged();
        }
    }

    public void clearLastCheckedItem(){
        try{
            View lastChild = lstCbContacts.getChildAt(lastPosition);
            lastChild.findViewById(R.id.btnDel).setVisibility(View.INVISIBLE);
            lastChild.findViewById(R.id.btnEdit).setVisibility(View.INVISIBLE);
            lastChild.findViewById(R.id.btnDone).setVisibility(View.INVISIBLE);
            lastChild.findViewById(R.id.txtContactName).setVisibility(View.INVISIBLE);
            lastChild.findViewById(R.id.lblName).setVisibility(View.VISIBLE);

        }
        catch (NullPointerException e){
            e.printStackTrace();
        }

    }
}

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android studio xml techniques and matrix style linear layout with green text color   Mon May 21, 2018 3:48 am

xml beefup :

linear layouts :

Code:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!1"
        android:id="@+id/lbl1"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!2"
        android:id="@+id/lbl2"
        android:layout_gravity="left"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!3"
        android:id="@+id/lbl3"
        android:layout_gravity="right"
        />

</LinearLayout>

LinearLayout : makes the controllers align in theire declaired sequence.
android:gravity="center" sets the controller on the middle

android:layout_gravity="right" declared in the controller effects only that controller

wrapping a controller group in a layout :

Code:
<?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:orientation="vertical"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!1"
        android:id="@+id/lbl1"
        android:layout_gravity="center"
        />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="horizontal">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="btn1"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="btn2"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="btn3"/>

    </LinearLayout>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="btn4"
        android:layout_gravity="right"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:orientation="vertical">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="btn5"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="btn6"/>

    </LinearLayout>


</LinearLayout>

Relative Layouts :

Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!1"
        android:id="@+id/lbl1"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!2"
        android:id="@+id/lbl2"
        android:layout_centerInParent="true"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!3"
        android:id="@+id/lbl3"
        android:layout_toRightOf="@id/lbl2"
        android:layout_toEndOf="@id/lbl2" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!5"
        android:id="@+id/lbl5"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!6"
        android:id="@+id/lbl6"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:textColor="#a5000000"
        />

</RelativeLayout>


android:layout_centerInParent="true" sets controller in the middle

android:layout_toRightOf="@id/lbl2"
       android:layout_toEndOf="@id/lbl2"
sets controller as said

android:layout_alignParentLeft="true"
       android:layout_centerVertical="true"
sets controller to the left and vrtically in the middle (height)

android:layout_alignParentRight="true"
       android:layout_centerVertical="true"
like the previous but to the right

setting Linear layout image + text color to matrix style
add the matrix3 background to the drawable folder in the res folder

xml :

Code:
<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:id="@+id/mainActivityLayout"
    >

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textColor="#037117"
        android:hint="matrix style"
        />


</LinearLayout>

main activity :

Code:
package com.justforum.yotamarker.myapplication;

import android.annotation.SuppressLint;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import static com.justforum.yotamarker.myapplication.R.id.mainActivityLayout;

public class MainActivity extends AppCompatActivity {
    LinearLayout r1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        r1 = findViewById(R.id.mainActivityLayout);
        r1.setBackgroundDrawable(ContextCompat.getDrawable(this,R.drawable.matrix3));
        // alt + enter was clicked
    }
}



if any red text errors in code click on them + alt + enter

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: creating and summoning activities   Mon May 21, 2018 4:54 am

create two activities with buttons

in solution explorer window right click layout folder in res folder, new, activity, empty activity

main activity xml:

Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="First Activity"
        android:id="@+id/lblFirst"
        android:layout_centerHorizontal="true"
        android:textSize="25dp"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtFirstContent"
        android:hint="Enter First Content"
        android:layout_centerInParent="true"
        android:textAlignment="center"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnFirstIntent"
        android:text="First To Second"
        android:textAllCaps="false"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/txtFirstContent"
        android:onClick="intentFirstToSecond"/>

</RelativeLayout>

change the 2nd activity (I named it activityx) xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activityX"
    android:background="#344955">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Second Activity"
        android:id="@+id/lblSecond"
        android:layout_centerHorizontal="true"
        android:textColor="#d0d0d0"
        android:textSize="25dp"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtSecondContent"
        android:hint="Enter First Content"
        android:layout_centerInParent="true"
        android:textColor="#d0d0d0"
        android:textColorHint="#d0d0d0"
        android:textAlignment="center"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnSecondIntent"
        android:text="Second To First"
        android:textAllCaps="false"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/txtSecondContent"
        android:onClick="intentSecondToFirst"/>

</RelativeLayout>

main activity c0de :

Code:
package com.justforum.yotamarker.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

        txtCbFirstContent = findViewById(R.id.txtFirstContent);
        lblCbFirst = findViewById(R.id.lblFirst);
        Bundle bundle = getIntent().getExtras();

        if(bundle != null){
            lblCbFirst.setText(bundle.getString("secondContent", "No Content Found"));
        }
    }


    public void intentFirstToSecond(View view) {
        Intent intent = new Intent(MainActivity.this, activityX.class);
        intent.putExtra("firstContent", txtCbFirstContent.getText().toString());

        startActivity(intent);

        finish();
    }
}

2nd activity code :

Code:
package com.justforum.yotamarker.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class activityX extends AppCompatActivity {

    EditText txtCbSecondContent;
    TextView lblCbSecond;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_x);
        txtCbSecondContent = findViewById(R.id.txtSecondContent);
        lblCbSecond = findViewById(R.id.lblSecond);
        Bundle bundle = getIntent().getExtras();

        lblCbSecond.setText(bundle.getString("firstContent", "No Content Found"));

    }

    public void intentSecondToFirst(View view) {
        Intent intent = new Intent(activityX.this, MainActivity.class);
        intent.putExtra("secondContent", txtCbSecondContent.getText().toString());

        startActivity(intent);

    }
}

Intent intent = new Intent(MainActivity.this, activityX.class);
intent.putExtra("firstContent", txtCbFirstContent.getText().toString());

puts data from this activity in a bundle which is summonable from the summoned activity at :
startActivity(intent);

finish(); kills the activity.

Bundle bundle = getIntent().getExtras();

lblCbSecond.setText(bundle.getString("firstContent", "No Content Found"));

gets the data from the summoning activity (it is a dictionary : data key = "firstContent", value = txtCbFirstContent.getText().toString())
if no data is found the default data would be : "No Content Found"

now add a button to link to the summoning of a different activity from each activity.



_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: custom grid view jutsu   Wed May 23, 2018 10:40 pm

custom grid view jutsu :

png images allow to see the background behind the character in said image
I added miku1.png - miku8.png to the drawable folder.


main xml

Code:
<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"

        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/gridview1"
        android:numColumns="3"
        android:stretchMode="columnWidth"
        ></GridView>

</LinearLayout>

gridView partinias (image + label):

Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/icons"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:src="@drawable/miku1"

        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="partinias label"
        android:id="@+id/pix"
        android:layout_below="@+id/icons"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="40dp"

        />
</RelativeLayout>

grid adapter java class with images and texts array as in the above partinias:

Code:
package com.justforum.yotamarker.mygridview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class GridAdapter extends BaseAdapter{

    private  int icons[];
    private  String pix[];
    private Context context;
    private LayoutInflater inflater;

    public  GridAdapter(Context context,int icons[], String pix[]){
        this.context = context;
        this.icons = icons;
        this.pix = pix;

    }

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

    @Override
    public Object getItem(int position) {
        return pix[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View gridView = convertView;
        if(convertView == null){

            inflater = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
            gridView = inflater.inflate(R.layout.grid_partinias,null);

        }
        ImageView icon = (ImageView)gridView.findViewById(R.id.icons);
        TextView pix = gridView.findViewById(R.id.pix);
        icon.setImageResource(icons[position]);
        pix.setText(this.pix[position]);



        return gridView;
    }
}

main java :

Code:
package com.justforum.yotamarker.mygridview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    GridView gridView;
    String txts[]={"miku1","miku2","miku3","miku4","miku5","miku6","miku7","miku8"};
    int pictu[] = {R.drawable.miku1,R.drawable.miku2,R.drawable.miku3,R.drawable.miku4,R.drawable.miku5,R.drawable.miku6,R.drawable.miku7,R.drawable.miku8};

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

        gridView = findViewById(R.id.gridview1);
        GridAdapter adapter = new GridAdapter(MainActivity.this,pictu,txts);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "hello " + txts[position], Toast.LENGTH_LONG).show();
            }
        });
    }
}

Cool


_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android studio alert dialogs   Wed May 23, 2018 11:40 pm



the following shows an app with 3 btn each one's click event summons a differt type of alert dialog:
regular, list, custom

main activity xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Open Regular AlertDialog"
            android:textAllCaps="false"
            android:id="@+id/btnRegAD"
            android:onClick="onRegularAlertDialog"
            android:layout_gravity="center"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Open List AlertDialog"
            android:textAllCaps="false"
            android:id="@+id/btnListAD"
            android:onClick="onListAlertDialog"
            android:layout_gravity="center"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Open Custom View AlertDialog"
            android:textAllCaps="false"
            android:id="@+id/btnCustomAD"
            android:onClick="onCustomAlertDialog"
            android:layout_gravity="center"/>
    </LinearLayout>

</RelativeLayout>

custom alert xml design :

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="UserName:"
            android:layout_weight="0.22"/>
        <EditText
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="Enter User Name"
            android:textAlignment="center"
            android:layout_weight="0.7"
            android:id="@+id/txtUser"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Password:"
            android:layout_weight="0.22"/>
        <EditText
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="Enter Password"
            android:textAlignment="center"
            android:layout_weight="0.7"
            android:inputType="textVisiblePassword"
            android:id="@+id/txtPass"/>
    </LinearLayout>


    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show/Hide Password"
        android:id="@+id/chkPassword"
        android:checked="true"/>

</LinearLayout>

main activity code :

Code:
package com.justforum.yotamarker.alert1;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

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);
    }
    public void onRegularAlertDialog(View view) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("My First Alert Dialog");
        builder.setMessage("Hello,\n This is my first alert dialog.\n Please, don't try to click No");
        builder.setCancelable(false);

        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Thank you for listening", Toast.LENGTH_LONG).show();
                dialog.dismiss();
//                dialog.cancel();
//                cancel - using dismiss + fire OnCancelListener event:
//                builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
//                    @Override
//                    public void onCancel(DialogInterface dialog) {
//
//                    }
//                });
            }
        });

        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "shiku shiku", Toast.LENGTH_LONG).show();
                builder.show();
            }
        });

        AlertDialog dialog = builder.create();

        dialog.show();
    }

    public void onListAlertDialog(View view) {
        List<String> lstItems = new ArrayList<String>();
        lstItems.add("Honda");lstItems.add("Suzuki");lstItems.add("Toyota");lstItems.add("Lexus");
        lstItems.add("Hyundai");lstItems.add("Delorian");lstItems.add("Mazda");lstItems.add("Mercedes");

        createListDialog(lstItems).show();
    }
    public AlertDialog createListDialog(List<String> lst){
        final List<String> lstItems = lst;

        ArrayAdapter<String> adapter =
                new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lstItems);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose Car");
        builder.setCancelable(false);
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int index) {
                Toast.makeText(MainActivity.this, lstItems.get(index), Toast.LENGTH_LONG).show();
            }
        });

        return builder.create();
    }

    public void onCustomAlertDialog(View view) {
        LayoutInflater inflater = getLayoutInflater();
        View adView = inflater.inflate(R.layout.alertxml, null, false);
        final EditText txtCbUser = adView.findViewById(R.id.txtUser);
        final EditText txtCbPass = adView.findViewById(R.id.txtPass);
        CheckBox chkCbPass = adView.findViewById(R.id.chkPassword);

        chkCbPass.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    txtCbPass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    return;
                }
                txtCbPass.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("Please Login.");

        builder.setCancelable(false);

        builder.setPositiveButton("Signup", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // todo : or not to do, that's the question
            }
        });

        builder.setNegativeButton("Login", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String cerd = "User: " + txtCbUser.getText().toString() +
                        "Password: " + txtCbPass.getText().toString();
                Toast.makeText(MainActivity.this, cerd, Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }
        });
        // setView(View); - custom xml View
        builder.setView(adView);

        AlertDialog dialog = builder.create();
        dialog.show();
    }
}


_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android studio play mp3.   Thu May 24, 2018 1:38 am





android studio play mp3.

the following app plays pokemon from an online resource and digimon from
a digimon.mp3 (all chars must be lower case) from a file in the app.

on solution explorer window right click res folder, new, android resource directory
and add digimon.mp3.

main activity xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <SeekBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_above="@id/controlsLayout"
        android:layout_marginHorizontal="25dp"
        android:id="@+id/seekBar"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:id="@+id/controlsLayout">
        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnStart"
            android:src="@android:drawable/ic_media_play"
            android:onClick="onStartMedia"/>
        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnPause"
            android:src="@android:drawable/ic_media_pause"
            android:onClick="onPauseMedia"/>
        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnStop"
            android:src="@android:drawable/ic_media_previous"
            android:onClick="onStopMedia"/>
    </LinearLayout>
    <Button
        android:onClick="playDigimon"
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="Button"
        android:layout_below="@id/controlsLayout"
        />


</RelativeLayout>

main activity java code :

Code:
package com.justforum.yotamarker.mp3project;

import android.media.MediaPlayer;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    MediaPlayer mediaPlayer;
    SeekBar seekCbBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        seekCbBar = findViewById(R.id.seekBar);
        // using local file:
//        mediaPlayer = MediaPlayer.create(this, R.raw.pokemon);
        //using HTTP:
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource("https://instrumentalfx.co/wp-content/upload/11/Pokemon-Theme-Song.mp3");
            mediaPlayer.prepare();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        //

        mediaPlayer.setLooping(false);
        seekCbBar.setMax(mediaPlayer.getDuration());

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
            }
        });

        attachSeekBarToMedia();
        setSeekBarListener();
    }

    public void attachSeekBarToMedia(){
        final Handler handler = new Handler();

        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                seekCbBar.setProgress(mediaPlayer.getCurrentPosition());
                handler.postDelayed(this, 1000);
            }
        });
    }

    public void setSeekBarListener(){
        seekCbBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    public void onStartMedia(View view) {
        mediaPlayer.start();
    }

    public void onPauseMedia(View view) {
        mediaPlayer.pause();
    }

    public void onStopMedia(View view) {
        mediaPlayer.pause();
        mediaPlayer.seekTo(0);
    }

    public void playDigimon(View view) {
        mediaPlayer = MediaPlayer.create(this, R.raw.digimon);
        mediaPlayer.setLooping(false);
        mediaPlayer.start();
    }
}

in the manifest folder in the AndroidManifest.xml add :

Code:
<uses-permission android:name="android.permission.INTERNET"/>
under
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="project name">

so it looks about like this :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.justforum.yotamarker.mp3project">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

the above manifest gives the app permission to DL files in this case pokemon mp3.

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android studio video view with landscap and portrait mode   Fri May 25, 2018 9:58 pm




android studio video view with landscap and portrait mode

place nebula.mp4 in raw folder in res folder in solution explorer window

main activity xml :

tongue
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <VideoView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/videoView"
        />

</RelativeLayout>

main activity java :

Code:
package com.justforum.yotamarker.video;

import android.app.ActionBar;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {
    VideoView videoCbView;
    MediaController mediaController;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        videoCbView = findViewById(R.id.videoView);
        mediaController = new MediaController(this);
        videoCbView.setMediaController(mediaController);
        videoCbView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.nebula));
        videoCbView.requestFocus();
        videoCbView.start();

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public void changeOrientation(boolean landscape){
        if(landscape){
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) videoCbView.getLayoutParams();
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            videoCbView.setLayoutParams(params);
            return;
        }
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) videoCbView.getLayoutParams();
        params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        params.removeRule(RelativeLayout.ALIGN_PARENT_TOP);
        params.removeRule(RelativeLayout.ALIGN_PARENT_LEFT);
        params.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        videoCbView.setLayoutParams(params);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        switch (newConfig.orientation){
            case Configuration.ORIENTATION_LANDSCAPE:
                changeOrientation(true);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                changeOrientation(false);
                break;
        }
    }
}

add android:configChanges="orientation to the manifest.xml in the manifest folder
so it looks like :


Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.justforum.yotamarker.video">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity" android:configChanges="orientation">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
 Razz

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android studio browser :   Sun May 27, 2018 8:48 pm

main activity xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter URL..."
        android:maxLines="1"
        android:id="@+id/txtUrl"
        android:layout_toLeftOf="@id/btns"
        android:layout_toStartOf="@id/btns" />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:id="@+id/btns"
        android:layout_alignParentEnd="true">
        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnGo"
            android:src="@android:drawable/ic_media_play"
            android:onClick="onLoadUrl"/>
        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnReload"
            android:src="@android:drawable/ic_popup_sync"
            android:onClick="onReload"/>
    </LinearLayout>

    <ProgressBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/progBar"
        style="@android:style/Widget.Holo.ProgressBar.Horizontal"
        android:layout_below="@id/btns"/>

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webView"
        android:layout_below="@id/progBar"/>

</RelativeLayout>

custom browser class to enable site blocking:

Code:
package com.hackeru.mysimplewebview;

import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class CustomWVClient extends WebViewClient {


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

        return request.getUrl().getHost().contains("ynet.co.il");
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return Uri.parse(url).getHost().contains("ynet.co.il");
    }
}

main activity java :

Code:
package com.hackeru.mysimplewebview;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    EditText txtCbUrl;
    WebView webCbView;
    ProgressBar progCbBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // assign reference to the local data members
        txtCbUrl = findViewById(R.id.txtUrl);
        webCbView = findViewById(R.id.webView);
        progCbBar = findViewById(R.id.progBar);
        progCbBar.setMax(100);
        // get the WebView Settings instance
        WebSettings settings = webCbView.getSettings();
        // Enable JavaScript - to allow sites that depend on JS to load
        // content
        settings.setJavaScriptEnabled(true);

        webCbView.setWebViewClient(new CustomWVClient());
        webCbView.setWebChromeClient(new WebChromeClient());

    }

    public void onLoadUrl(View view) {
        StringBuffer buffer = new StringBuffer(txtCbUrl.getText().toString());
        if(!buffer.toString().startsWith("http://") || !buffer.toString().startsWith("https://")){
            buffer.insert(0, "http://");
        }

        webCbView.loadUrl(buffer.toString());
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 1234);
        updateProgressBar();
    }

    public void onReload(View view) {
        webCbView.reload();
        updateProgressBar();
    }

    public void updateProgressBar(){
        final Handler handler = new Handler();
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progCbBar.setProgress(webCbView.getProgress());
                if(webCbView.getProgress() < 100){
                    handler.postDelayed(this, 100);
                }
            }
        });
    }
}

add to the manifest xml in the manifest folder
<!--Where to declare permission requests:-->
<uses-permission android:name="android.permission.INTERNET"/>

so it looks like :

Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hackeru.mysimplewebview">

    <!--Where to declare permission requests:-->
    <uses-permission android:name="android.permission.INTERNET"/>


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

geek

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android studio using fragments   Sun May 27, 2018 8:53 pm

android studio using fragments.
controlling views on fragments from other fragments.

to create a fragment right click the layout folder in the solution explorer, new, fragment.
this will add the fragment xml and java code.

fragment bg color xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".BgColorFragment">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/xyz"
    android:src="@drawable/ic_launcher_background"
    />

</FrameLayout>

bg color fragment java :

Code:
package com.justforum.yotamarker.fragment;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;


public class BgColorFragment extends Fragment {

    // this is a simple empty fragment without any controlls and attached to its xml file
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_bg_color, container, false);
//        ImageView imageView =  view.findViewById(R.id.xyz);
//        imageView.setImageResource(R.drawable.ogre);
        return view;
    }

}

color list fragment xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".ColorListFragment"
    >

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

</FrameLayout>

color list fragment java :

Code:
package com.justforum.yotamarker.fragment;

import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

// all fragment technigues here
public class ColorListFragment extends Fragment {
    ListView listCbColors;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {

        View view =  inflater.inflate(R.layout.fragment_color_list, container, false);
        // color list declared final because it uses a listener
        final String[] colors = {"Red", "Green", "Blue", "Black", "White", "Gray", "Magenta", "Yellow",
                "Light Gray", "Dark Gray", "Light Grey", "Dark Grey", "Olive",
                "Teal", "Silver", "Purple", "Cyan", "Aqua", "Fuchsia", "Lime", "Maroon", "Navy"};

        // on fragment controller
        listCbColors = view.findViewById(R.id.listColors);
        // list view adapter
        ArrayAdapter<String> adapter =
                new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, colors);
        listCbColors.setAdapter(adapter);
        // list view click event :
        listCbColors.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // link to another fragment :
                BgColorFragment bgColorFragment = (BgColorFragment) getFragmentManager().findFragmentById(R.id.bgColorFragments);
                // set linked fragment bg attribute
                setBgColor(bgColorFragment, colors[position].toLowerCase().replace(" ", ""));
                // code block to add controller to fragment programmatically (text box):
                FrameLayout frameLayout = bgColorFragment.getView().findViewById(R.id.bgColorFragments);
                TextView lblColor = new TextView(bgColorFragment.getContext());
                lblColor.setText(colors[position]);
                lblColor.setTextSize(20);
                // reset fragment to the way it is in its xml

                frameLayout.removeAllViews();
                frameLayout.addView(lblColor);
// manipulate a controller on the other fragment this does not work with the code line frameLayout.removeAllViews(); above
                // which kills the image controller image view and all other views for that matter
                //                ImageView iv1 = (ImageView)bgColorFragment.getView().findViewById(R.id.xyz);
//                iv1.setImageResource(R.drawable.ic_launcher_foreground);





            }
        });


        return view;
    }

    public void setBgColor(Fragment fragment, String color){
        fragment.getView().setBackgroundColor(Color.parseColor(color));
    }

}

main activity xml :

Code:
<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.5"
        android:id="@+id/listColorFragments"
        tools:layout="@layout/fragment_color_list"
        android:name="com.justforum.yotamarker.fragment.ColorListFragment"/>
    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.5"
        android:id="@+id/bgColorFragments"
        tools:layout="@layout/fragment_bg_color"
        android:name="com.justforum.yotamarker.fragment.BgColorFragment"/>

</LinearLayout>

main activity java (default):

Code:
package com.justforum.yotamarker.fragment;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

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

notice the image view on bgcolor fragment is only for showing how to change its image from
the color list fragment

the code is commented out :
// manipulate a controller on the other fragment this does not work with the code line frameLayout.removeAllViews(); above
// which kills the image controller image view and all other views for that matter
// ImageView iv1 = (ImageView)bgColorFragment.getView().findViewById(R.id.xyz);
// iv1.setImageResource(R.drawable.ic_launcher_foreground);

if you comment it comment :
frameLayout.removeAllViews();
or it will glitch


_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android studio pager widget   Mon May 28, 2018 11:00 pm




the android grimoir pager using app :

in gradle scripts, build.gradle(module: app)

add :
// Design Package for TabLayout And ViewPager
implementation 'com.android.support:design:27.1.1'

in dependencies (txt) above testImplementation. than clicked the popped up sync now.

now the project can use pagers

main activity layout :


Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.TabLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffba18"
        android:id="@+id/tabLayout"/>

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/tabLayout"
        android:id="@+id/viewPager"/>

</RelativeLayout>

right click layout folder in res folder in solution explorer : new, resource file.
name: fragment_layout
root element : relative layout

xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webView"/>

</FrameLayout>

in tool strib, build rebuild

right click java folder, new, java class
call it url1fragment :


Code:
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class url1fragment extends Fragment {
    WebView webCbView;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_layout, container, false);
        webCbView = view.findViewById(R.id.webView);
        webCbView.setWebViewClient(new WebViewClient());
        WebSettings settings = webCbView.getSettings();
        settings.setJavaScriptEnabled(true);
        webCbView.loadUrl("https://yotamarker.forumotion.com/t155-android-mobile-app-dev-apk");
        return view;
    }
}


do the same with url2fragment, and url3fragment and change the url address to yout liking

main activity java :

Code:
package com.justforum.yotamarker.androidgrimoire;

import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    ViewPager viewCbPager;
    TabLayout tabCbLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewCbPager = findViewById(R.id.viewPager);
        tabCbLayout = findViewById(R.id.tabLayout);
        tabCbLayout.setupWithViewPager(viewCbPager);
        viewCbPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
    }

    private class ViewPagerAdapter extends FragmentPagerAdapter{
        String[] names = {"android grimoire", "java grimoire", "donate"};
        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (names[position].toLowerCase()){
                case "java grimoire":
                    return new url2fragment();
                case "android grimoire":
                    return new url1fragment();
                case "donate":
                    return new url3fragment();
                default:
                    return null;
            }
        }

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

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return names[position];
        }
    }
}


in manifests folder in the solution explorer in the AndroidManifest.xml
add internet browsing permission :
<uses-permission android:name="android.permission.INTERNET"/>

so the code looks like :


Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.justforum.yotamarker.androidgrimoire">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


you can use in the url#fragment java class :
webCbView.setWebChromeClient(new WebChromeClient());
instead of :
webCbView.setWebViewClient(new WebViewClient());
to enable a variety of features such as using img hyperlinks in the urls used.

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android studio timer event repeated scheduled task   Wed May 30, 2018 6:54 pm



android studio timer event repeated scheduled task

main activity xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:id="@+id/tv1"/>

</android.support.constraint.ConstraintLayout>

main activity java :

Code:
package com.justforum.yotamarker.timer1;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView tv1;
    int count = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1= findViewById(R.id.tv1);
        Thread t=new Thread(){
            @Override
            public void  run(){
                while((!isInterrupted())){
                    try {
                        Thread.sleep(2000);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                count++;
                                tv1.setText(String.valueOf(count));

                            }
                        });
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }


                }
            }
        };
        t.start();
    }
}



_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android studio walkthrough RecyclerView :   Sat Jun 02, 2018 8:42 am

android studio walkthrough RecyclerView :
the same as customlist view but takes longer to set up and can handle heavier amounts
of elements, with x elements active at a given time.

setup support design libraries :
solution explorer, gradle scripts, build.gradle(module.app),
add in dependencies:
implementation 'com.android.support:appcompat-v7:27.1.1'
   implementation 'com.android.support:design:27.1.1'

so it looks like :

Code:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.justforum.yotamarker.rycyclerview1"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support:design:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}


add a recycler view to
activity_main xml :


Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

   <android.support.v7.widget.RecyclerView
       android:id="@+id/recyclerView"
       android:scrollbars="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent"/>

</android.support.constraint.ConstraintLayout>


in res, layout folder : right click, add new layout resource file :
file name: layout_recycler_view
root element : LinearLayout

xml  (padding adds space between the recycle partinias elements) :


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

    <TextView
        android:id="@+id/txtDescription"
        android:text="Description"
        android:textColor="#000"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        />

</LinearLayout>


in values, styles.xml set to :

Code:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

right click main.java, new, java class, kind : interface name : ItemClickListener

Code:
package com.justforum.yotamarker.rycyclerview1;

import android.view.View;

public interface ItemClickListener {
    void onClick(View view, int position, boolean isLongClick);
}

right click main.java, new, java class, RecyclerAdapter class :

package com.justforum.yotamarker.rycyclerview1;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

class RecyclerViewHandler extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnLongClickListener{
    public TextView txt_description;
    private ItemClickListener itemClickListener;


    public RecyclerViewHandler(View itemView) {
        super(itemView);
        txt_description = (TextView)itemView.findViewById(R.id.txtDescription);
        itemView.setOnClickListener(this);
        itemView.setOnLongClickListener(this);
    }
    public void  setItemClickListener(ItemClickListener itemClickListener)
    {
        this.itemClickListener = itemClickListener;

    }
    public void onClick(View v)
    {
        itemClickListener.onClick(v,getAdapterPosition(),false);
    }

    @Override
    public boolean onLongClick(View v) {
        itemClickListener.onClick(v,getAdapterPosition(),true);
        return true;
    }
}
public class RecyclerAdapter extends  RecyclerView.Adapter<RecyclerViewHandler>{
    private List<String> listData = new ArrayList<>();
    private Context context;

    public RecyclerAdapter(List<String> listData, Context context) {
        this.listData = listData;
        this.context = context;
    }

    @NonNull
    @Override
    public RecyclerViewHandler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View itemView = inflater.inflate(R.layout.layout_item_recycler_view,parent,false);

        return new RecyclerViewHandler(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHandler holder, int position) {
        holder.txt_description.setText(listData.get(position));
        holder.setItemClickListener(new ItemClickListener() {
            @Override
            public void onClick(View view, int position, boolean isLongClick) {
                if(isLongClick)
                    Toast.makeText(context, "long clicked " + listData.get(position), Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(context, "short clicked " + listData.get(position), Toast.LENGTH_SHORT).show();

            }
        });

    }

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

main activity code :


Code:
package com.justforum.yotamarker.rycyclerview1;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private List<String> listData = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupList();
        recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        RecyclerAdapter adapter = new RecyclerAdapter(listData,this);
        recyclerView.setAdapter(adapter);


    }

    private void setupList() {
        for(int i=1;i<=50;i++){
            listData.add("click me " + i);
        }
    }
}

adding animation to Recyle view : src https://proandroiddev.com/enter-animation-using-recyclerview-and-layoutanimation-part-1-list-75a874a5d213

add miku1- miku14 without miku named png images to the drawable folder

in res add anim directory, add to it :


item_animation_fall_down.xml :

Code:
<set xmlns:android="http://schemas.android.com/apk/res/android"

    android:duration="2000">



    <translate

        android:fromYDelta="-20%"

        android:toYDelta="0"

        android:interpolator="@android:anim/decelerate_interpolator"

        />



    <alpha

        android:fromAlpha="0"

        android:toAlpha="1"

        android:interpolator="@android:anim/decelerate_interpolator"

        />



    <scale

        android:fromXScale="105%"

        android:fromYScale="105%"

        android:toXScale="100%"

        android:toYScale="100%"

        android:pivotX="50%"

        android:pivotY="50%"

        android:interpolator="@android:anim/decelerate_interpolator"

        />



</set>


android:duration="2000" is how long the animation runs

and layout_animation_fall_down.xml :

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

<layoutAnimation

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:animation="@anim/item_animation_fall_down"

    android:delay="15%"

    android:animationOrder="normal"

    />

add a simple book java class with image int :

Code:
package com.justforum.yotamarker.rycyclerview1;

import android.support.annotation.DrawableRes;

public class books {
    private @DrawableRes
    int picture;
    private String name;

    public books(@DrawableRes int picture, String name) {
        this.picture = picture;
        this.name = name;
    }

    public @DrawableRes int getPicture() {
        return picture;
    }

    public String getName() {
        return name;
    }

    public void setPicture(@DrawableRes int picture) {
        this.picture = picture;
    }

    public void setName(String name) {
        this.name = name;
    }
}

add a button to main activity xml which will rerun the animation :

Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
   <Button
       android:onClick="TestHelloWorld"
       android:id="@+id/button"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"

       android:layout_centerVertical="true"
       android:layout_marginStart="63dp"
       android:text="Button" />
   <android.support.v7.widget.RecyclerView
       android:id="@+id/recyclerView"
       android:scrollbars="vertical"

       android:layout_width="match_parent"
       android:layout_height="match_parent"/>

</android.support.constraint.ConstraintLayout>

change the RecyclerAdapter java class to be compatible with the book class :

Code:
package com.justforum.yotamarker.rycyclerview1;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

class RecyclerViewHandler extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnLongClickListener{
    public TextView txt_description;
    public ImageView pic;
    private ItemClickListener itemClickListener;


    public RecyclerViewHandler(View itemView) {
        super(itemView);
        txt_description = (TextView)itemView.findViewById(R.id.txtDescription);
        pic = (ImageView)itemView.findViewById(R.id.imgContact);
        itemView.setOnClickListener(this);
        itemView.setOnLongClickListener(this);
    }
    public void  setItemClickListener(ItemClickListener itemClickListener)
    {
        this.itemClickListener = itemClickListener;

    }
    public void onClick(View v)
    {
        itemClickListener.onClick(v,getAdapterPosition(),false);
    }

    @Override
    public boolean onLongClick(View v) {
        itemClickListener.onClick(v,getAdapterPosition(),true);
        return true;
    }
}
public class RecyclerAdapter extends  RecyclerView.Adapter<RecyclerViewHandler>{
    private  List<books> bookList = new ArrayList<>();
    private Context context;

    public RecyclerAdapter(List<books> bookList, Context context) {
        this.bookList = bookList;
        this.context = context;
    }

    @NonNull
    @Override
    public RecyclerViewHandler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View itemView = inflater.inflate(R.layout.layout_item_recycler_view,parent,false);

        return new RecyclerViewHandler(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHandler holder, int position) {
        holder.txt_description.setText(bookList.get(position).getName());
        holder.pic.setImageResource(bookList.get(position).getPicture());
        holder.setItemClickListener(new ItemClickListener() {
            @Override
            public void onClick(View view, int position, boolean isLongClick) {
                if(isLongClick)
                    Toast.makeText(context, "long clicked " + bookList.get(position).getName(), Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(context, "short clicked " + bookList.get(position).getName(), Toast.LENGTH_SHORT).show();

            }
        });

    }

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

modify the main activity java code :


Code:
package com.justforum.yotamarker.rycyclerview1;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private  List<books> bookList = new ArrayList<>();
    int resId = R.anim.layout_animation_fall_down;

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

        setContentView(R.layout.activity_main);
        setupList();
        recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        RecyclerAdapter adapter = new RecyclerAdapter(bookList,this);
        recyclerView.setAdapter(adapter);

        LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(this, resId);

        recyclerView.setLayoutAnimation(animation);



    }

    private void setupList() {
        int[] thisIsAnIntrray = {R.drawable.miku1,R.drawable.miku2,R.drawable.miku3,R.drawable.miku4,
                R.drawable.miku5,R.drawable.miku6,R.drawable.miku7,R.drawable.miku8,R.drawable.miku9,
                R.drawable.miku10,R.drawable.miku11,R.drawable.miku13,R.drawable.miku14};
        for(int i=0;i<13;i++){
            bookList.add(new books((thisIsAnIntrray[i]), "book " + i));
        }
    }
    private void runLayoutAnimation(final RecyclerView recyclerView) {
        final Context context = recyclerView.getContext();
        final LayoutAnimationController controller =
                AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_fall_down);

        recyclerView.setLayoutAnimation(controller);
        recyclerView.getAdapter().notifyDataSetChanged();
        recyclerView.scheduleLayoutAnimation();
    }

    public void TestHelloWorld(View view) {
        runLayoutAnimation(recyclerView);
    }
}

also you can bind the animation to the xml recycler widget like this :

Code:
<android.support.v7.widget.RecyclerView

    android:layout_width="match_parent"

    android:layout_height="match_parent"                                        

    android:layoutAnimation="@anim/layout_animation_fall_down"

    />

instead of how it is in the main activity on create.






alternate equivilant faster walkthrough :


add : implementation 'com.android.support:recyclerview-v7:27.1.1'
to build.gradle(module:app)

add miku#.png : # = 1 to 14 without 12

to res layout :
activity_main :

Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
   <Button
       android:onClick="TestHelloWorld"
       android:id="@+id/button"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"

       android:layout_centerVertical="true"
       android:layout_marginStart="63dp"
       android:text="Button" />
   <android.support.v7.widget.RecyclerView
       android:id="@+id/recyclerView"
       android:scrollbars="vertical"

       android:layout_width="match_parent"
       android:layout_height="match_parent"/>

</android.support.constraint.ConstraintLayout>

and layout_item_recycler_view.xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:padding="20dp"
    android:layout_height="wrap_content">
    <ImageView
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:id="@+id/imgContact"
        android:src="@mipmap/ic_launcher"
        android:layout_margin="5dp"/>
    <TextView
        android:id="@+id/txtDescription"
        android:text="Description"
        android:textColor="#000"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        />

</LinearLayout>

creat folder anim in res :
add :
item_animation_fall_down.xml :
Code:

<set xmlns:android="http://schemas.android.com/apk/res/android"

   android:duration="2000">



   <translate

       android:fromYDelta="-20%"

       android:toYDelta="0"

       android:interpolator="@android:anim/decelerate_interpolator"

       />



   <alpha

       android:fromAlpha="0"

       android:toAlpha="1"

       android:interpolator="@android:anim/decelerate_interpolator"

       />



   <scale

       android:fromXScale="105%"

       android:fromYScale="105%"

       android:toXScale="100%"

       android:toYScale="100%"

       android:pivotX="50%"

       android:pivotY="50%"

       android:interpolator="@android:anim/decelerate_interpolator"

       />



</set>

and in that same anime folder add layout_animation_fall_down.xml :

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

<layoutAnimation

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:animation="@anim/item_animation_fall_down"

    android:delay="15%"

    android:animationOrder="normal"

    />

add books.java :

Code:
package com.justforum.yotamarker.rycyclerview1;

import android.support.annotation.DrawableRes;

public class books {
    private @DrawableRes
    int picture;
    private String name;

    public books(@DrawableRes int picture, String name) {
        this.picture = picture;
        this.name = name;
    }

    public @DrawableRes int getPicture() {
        return picture;
    }

    public String getName() {
        return name;
    }

    public void setPicture(@DrawableRes int picture) {
        this.picture = picture;
    }

    public void setName(String name) {
        this.name = name;
    }
}

ItemClickListener (interface)

Code:
package com.justforum.yotamarker.rycyclerview1;

import android.view.View;

public interface ItemClickListener {
    void onClick(View view, int position, boolean isLongClick);
}

RecyclerAdapter java :

Code:
package com.justforum.yotamarker.rycyclerview1;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

class RecyclerViewHandler extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnLongClickListener{
    public TextView txt_description;
    public ImageView pic;
    private ItemClickListener itemClickListener;


    public RecyclerViewHandler(View itemView) {
        super(itemView);
        txt_description = (TextView)itemView.findViewById(R.id.txtDescription);
        pic = (ImageView)itemView.findViewById(R.id.imgContact);
        itemView.setOnClickListener(this);
        itemView.setOnLongClickListener(this);
    }
    public void  setItemClickListener(ItemClickListener itemClickListener)
    {
        this.itemClickListener = itemClickListener;

    }
    public void onClick(View v)
    {
        itemClickListener.onClick(v,getAdapterPosition(),false);
    }

    @Override
    public boolean onLongClick(View v) {
        itemClickListener.onClick(v,getAdapterPosition(),true);
        return true;
    }
}
public class RecyclerAdapter extends  RecyclerView.Adapter<RecyclerViewHandler>{
    private  List<books> bookList = new ArrayList<>();
    private Context context;

    public RecyclerAdapter(List<books> bookList, Context context) {
        this.bookList = bookList;
        this.context = context;
    }

    @NonNull
    @Override
    public RecyclerViewHandler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View itemView = inflater.inflate(R.layout.layout_item_recycler_view,parent,false);

        return new RecyclerViewHandler(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHandler holder, int position) {
        holder.txt_description.setText(bookList.get(position).getName());
        holder.pic.setImageResource(bookList.get(position).getPicture());
        holder.setItemClickListener(new ItemClickListener() {
            @Override
            public void onClick(View view, int position, boolean isLongClick) {
                if(isLongClick)
                    Toast.makeText(context, "long clicked " + bookList.get(position).getName(), Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(context, "short clicked " + bookList.get(position).getName(), Toast.LENGTH_SHORT).show();

            }
        });

    }

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

MainActivity.java :

Code:
package com.justforum.yotamarker.recycler2;

import android.content.Context;
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.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private  List<books> bookList = new ArrayList<>();
    int resId = R.anim.layout_animation_fall_down;

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

        setContentView(R.layout.activity_main);
        setupList();
        recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        RecyclerAdapter adapter = new RecyclerAdapter(bookList,this);
        recyclerView.setAdapter(adapter);

        LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(this, resId);

        recyclerView.setLayoutAnimation(animation);



    }

    private void setupList() {
        int[] thisIsAnIntrray = {R.drawable.miku1,R.drawable.miku2,R.drawable.miku3,R.drawable.miku4,
                R.drawable.miku5,R.drawable.miku6,R.drawable.miku7,R.drawable.miku8,R.drawable.miku9,
                R.drawable.miku10,R.drawable.miku11,R.drawable.miku13,R.drawable.miku14};
        for(int i=0;i<13;i++){
            bookList.add(new books((thisIsAnIntrray[i]), "book " + i));
        }
    }
    private void runLayoutAnimation(final RecyclerView recyclerView) {
        final Context context = recyclerView.getContext();
        final LayoutAnimationController controller =
                AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_fall_down);

        recyclerView.setLayoutAnimation(controller);
        recyclerView.getAdapter().notifyDataSetChanged();
        recyclerView.scheduleLayoutAnimation();
    }

    public void TestHelloWorld(View view) {
        runLayoutAnimation(recyclerView);
    }
}

download the projects folder  to open ready made in android studio (extract zip download, from android studio tool bar, file, open, choose extracted folder):
https://k2s.cc/file/6d5cda369a031/recycler2.rar

_________________
MB over and out _______________________     


Last edited by Moti Barski on Thu Jul 19, 2018 6:19 am; edited 4 times in total
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: onActivityResult jutsu   Tue Jun 05, 2018 9:34 pm

explination in javadoc in code

main activity xml :

Code:
<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context="com.justforum.yotamarker.forresult.MainActivity">

    <EditText
        android:id="@+id/edit_text_number1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Number 1"
        android:inputType="number" />

    <EditText
        android:id="@+id/edit_text_number2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Number 2"
        android:inputType="number" />

    <TextView
        android:id="@+id/text_view_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Result"
        android:textSize="30sp" />

    <Button
        android:id="@+id/button_open_activity2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="open activity 2" />

</LinearLayout>


activity 2 xml:

Code:
<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context="com.justforum.yotamarker.forresult.Activity2">

    <TextView
        android:id="@+id/text_view_numbers"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Numbers: "
        android:textSize="30sp" />

    <Button
        android:id="@+id/button_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="add" />

    <Button
        android:id="@+id/button_subtract"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="subtract" />

</LinearLayout>

main java code :

Code:
package com.justforum.yotamarker.forresult;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private TextView mTextViewResult;
    private EditText mEditTextNumber1;
    private EditText mEditTextNumber2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // ties this java class to activity_main.xml (the design)
        setTitle("shouryuken"); // set activity title
        mTextViewResult = findViewById(R.id.text_view_result);
        mEditTextNumber1 = findViewById(R.id.edit_text_number1);
        mEditTextNumber2 = findViewById(R.id.edit_text_number2);

        Button buttonOpenActivity2 = findViewById(R.id.button_open_activity2);
        buttonOpenActivity2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEditTextNumber1.getText().toString().equals("")
                        || mEditTextNumber2.getText().toString().equals("")) {
                    Toast.makeText(MainActivity.this, "Please insert numbers", Toast.LENGTH_SHORT).show();
                } else {

                    int number1 = Integer.parseInt(mEditTextNumber1.getText().toString());
                    int number2 = Integer.parseInt(mEditTextNumber2.getText().toString());

                    Intent intent = new Intent(MainActivity.this, Activity2.class);
                    intent.putExtra("number1", number1);
                    intent.putExtra("number2", number2);
                    startActivityForResult(intent, 1);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /* async methode runs while result activity runs
        * and comes to this methode when summoned activity dies
        *  so it can summon several result activities while running
        */
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                int result = data.getIntExtra("result", 0);
                mTextViewResult.setText("" + result);
            }
            if (resultCode == RESULT_CANCELED) {
                mTextViewResult.setText("Nothing selected");
            }
        }
    }
}

activity 2 java code

Code:
package com.justforum.yotamarker.forresult;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Activity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_2);
        // set activity title
        setTitle("Activity 2 hadouken");

        Intent intent = getIntent();
        final int number1 = intent.getIntExtra("number1", 0);
        final int number2 = intent.getIntExtra("number2", 0);

        TextView textViewNumbers = findViewById(R.id.text_view_numbers);
        textViewNumbers.setText("Numbers: " + number1 + ", " + number2);

        Button buttonAdd = findViewById(R.id.button_add);
        Button buttonSubtract = findViewById(R.id.button_subtract);

        buttonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int result = number1 + number2;

                Intent resultIntent = new Intent();
                resultIntent.putExtra("result", result);

                setResult(RESULT_OK, resultIntent);
                finish(); // kill this activity
            }
        });

        buttonSubtract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int result = number1 - number2;

                Intent resultIntent = new Intent();
                resultIntent.putExtra("result", result);

                setResult(RESULT_OK, resultIntent);
                finish(); // kill this activity
            }
        });
    }
}

pirat

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android splash screen   Wed Jun 06, 2018 9:27 am



android splash screen, the screen thats loads for x milisec B4 the app loads

.1 solution explor, gradle scripts, build.gradle (modules: app), add line :
implementation 'gr.pantrif:easy-android-splash-screen:0.0.1'

above the line :
testImplementation 'junit:junit:4.12'

in dependencies block.

.2 : java folder, right click MainActivity, new, activity, empty activity
activity name : SplashScreen, uncheck generate layout file.

code :

Code:
package com.justforum.yotamarker.splash;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import gr.net.maroulis.library.EasySplashScreen;

public class SplashScreen extends AppCompatActivity {

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

        EasySplashScreen config = new EasySplashScreen(SplashScreen.this)
                .withFullScreen()
                .withTargetActivity(MainActivity.class)
                .withSplashTimeOut(5000)
                .withBackgroundColor(Color.parseColor("#1a1b29"))
                .withHeaderText("Header")
                .withFooterText("Footer")
                .withBeforeLogoText("Before Logo Text")
                .withAfterLogoText("After Logo Text")
                .withLogo(R.mipmap.ic_launcher_round);
        config.withBackgroundResource(R.drawable.splash);
        config.getHeaderTextView().setTextColor(Color.WHITE);
        config.getFooterTextView().setTextColor(Color.WHITE);
        config.getBeforeLogoTextView().setTextColor(Color.WHITE);
        config.getAfterLogoTextView().setTextColor(Color.WHITE);

        View easySplashScreen = config.create();
        setContentView(easySplashScreen);
    }
}

comment out config.withBackgroundResource(R.drawable.splash); if you dont put a background image in res, drawable
(splash.jpg)

.3 solution explorer window, manifests, AndroidManifest.xml flip between mainactivity and splashscreen so it looks like this :


Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.justforum.yotamarker.splash">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".SplashScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity"></activity>
    </application>

</manifest>

remove the action bar to get full screen splash :
res folder, values, styles.xml
change : <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> to
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

you can paste an action bar on the activity xml


_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: dynamic fragment   Sun Jun 10, 2018 8:33 pm

interfacing a fragement and setting a selected fragment into a layout view on some xml.

main xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<!--custom fragment housing-->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_marginTop="40dp"
        android:id="@+id/mainContainer">

    </RelativeLayout>

    <TextView android:text="Fragment Comm"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lblTitle"
        android:gravity="center"
        android:textColor="#4ada2a"
        android:textAppearance="?android:textAppearanceLarge"
        />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_marginTop="40dp"
        android:id="@+id/frgContainer"
        >

    </RelativeLayout>



</android.support.constraint.ConstraintLayout>

right click somewhere in the res, layout folder, new, fragment, fragment blank, change the xml to :


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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select a color:"
        android:layout_gravity="center"
        />
    <RadioGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginLeft="120dp"
        android:layout_marginTop="130dp"
        android:id="@+id/chkGrpBtns"
        >
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/chkRed"
            android:text="Red"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/chkGreen"
            android:text="Green"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/chkBlue"
            android:text="Blue"/>

    </RadioGroup>


</LinearLayout>

main java :


Code:
package com.justforum.yotamarker.kakerainterface;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
// arm your activity with the fragment interface you made (implement):
public class MainActivity extends AppCompatActivity
        implements ColorFragment.IColorChange{
    RelativeLayout relativeLayoutCbObj;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set xml UI for activity
        setContentView(R.layout.activity_main);
        // connect the layout to house the custom dynamic fragment
        relativeLayoutCbObj = (RelativeLayout)findViewById
                (R.id.mainContainer);
        // use the frag manager to lload a fragement
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction =
                fragmentManager.beginTransaction();

        ColorFragment colorFragmentObj = new ColorFragment();
        fragmentTransaction.add(R.id.frgContainer, colorFragmentObj);
        fragmentTransaction.commit();
        // remove fragment : fragmentTransaction.remove(colorFragmentObj);
        // load different fragment : fragmentTransaction.replace(R.id.frgContainer, colorFragmentObj);
        // then fragmentTransaction.commit();

    }

    @Override
    public void colorChanged(String str) {
        // implement your fragment interface
        if(str.equals("Red"))
        {
            relativeLayoutCbObj.setBackgroundColor(Color.RED);
        }else if(str.equals("Green"))
        {
            relativeLayoutCbObj.setBackgroundColor(Color.GREEN);
        }
        else if(str.equals("Blue"))
        {
            relativeLayoutCbObj.setBackgroundColor(Color.BLUE);
        }

    }
}


exampled fragment java :


Code:
package com.justforum.yotamarker.kakerainterface;

import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;

public class ColorFragment extends Fragment {
    RadioGroup grpCbObj;
    IColorChange iColorChange;

    @Nullable
    @Override

    public View onCreateView(LayoutInflater inflater,
                            ViewGroup container, Bundle
                                    savedInstanceState) {
        // add fragment view listeners here :
        View view = inflater.inflate(R.layout.fragment_color,
                container, false);
        grpCbObj = (RadioGroup)view.findViewById(R.id.chkGrpBtns);

        grpCbObj.setOnCheckedChangeListener
                (new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group,
                                                int checkedId) {
                        switch (checkedId){
                            case R.id.chkRed:
                                iColorChange.colorChanged("Red");
                                break;
                            case R.id.chkGreen:
                                iColorChange.colorChanged("Green");
                                break;
                            case R.id.chkBlue:
                                iColorChange.colorChanged("Blue");
                                break;
                        }
                    }
                });
        return view;
    }

    @Override
    public void onAttach(Context context) {
        // on attach fragement event :
        super.onAttach(context);
        try
        {
            iColorChange = (IColorChange)context;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
// create the custom jutsu for the fragement using an interface
    public interface IColorChange
    {
        void colorChanged(String str);
    }
}

What a Face

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android storing data lv1   Wed Jun 13, 2018 8:23 pm




android storing data lv1 :

shared preferences not deprecated (works on new APIs).

use a shared preferences screen to save simple values into the phone's cache memory such as simple
settings and strings :

add array.xml to res, values :
this is for simple dictionary data the preference screen will use among other widgets.

Code:
<resources>
    <string-array name="listArray">
        <item>Ace</item>
        <item>Club</item>
    </string-array>

    <string-array name="listValues">
        <item>Ace</item>
        <item>Club</item>
    </string-array>
</resources>


add xml dir to res, in it put preferences.xml (right click folder, new, xml resource file) :

Code:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <EditTextPreference android:title="Your Name"
        android:key="username"
        android:summary="Please provide your username"></EditTextPreference>
    <CheckBoxPreference android:title="Application Updates"
        android:defaultValue="false"
        android:summary="This option if selected will allow the application to check for latest versions."
        android:key="applicationUpdates" />
    <ListPreference    android:title="Download Details"
        android:summary="Select the kind of data that you would like to download"
        android:key="downloadType"
        android:defaultValue="Ace"
        android:entries="@array/listArray"
        android:entryValues="@array/listValues" />
</PreferenceScreen>

add empty activity : AppPreferenceActivity to java,com.projectdomain by right click new on the mainactivity :

Code:
package com.justforum.yotamarker.pref2;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.widget.Toast;

public class AppPreferenceActivity extends PreferenceActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();

        checkValues();
    }

    public static class MyPreferenceFragment extends PreferenceFragment
    {
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
        }
    }

    private void checkValues()
    {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        String strUserName = sharedPrefs.getString("username", "NA");
        boolean bAppUpdates = sharedPrefs.getBoolean("applicationUpdates",false);
        String downloadType = sharedPrefs.getString("downloadType","1");

        String msg = "Cur Values: ";
        msg += "\n userName = " + strUserName;
        msg += "\n bAppUpdates = " + bAppUpdates;
        msg += "\n downloadType = " + downloadType;
        // display vars from the shared pref widgets represented by the var msg :
        Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();
    }
}

main activity with a btn to summon the preference screen as an activity :



Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:onClick="TestHelloWorld"
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginStart="63dp"
        android:text="Button" />

</android.support.constraint.ConstraintLayout>

main java :


Code:
package com.justforum.yotamarker.pref2;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

    }

    public void test(View view) {
        Intent intent = new Intent(MainActivity.this, AppPreferenceActivity.class);
        startActivity(intent);
    }

    public void TestHelloWorld(View view) {
        Intent intent = new Intent(MainActivity.this, AppPreferenceActivity.class);
        startActivity(intent);
    }
}

lv1.

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: Re: android mobile app dev APK   Wed Jun 13, 2018 9:54 pm



save and read to phone cache as dictionary values for primitive vars (strings) :

main xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <!--focus on view-->
    <EditText
        android:id="@+id/txtText1"
        android:layout_width="278dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="37dp"
        android:layout_toEndOf="@+id/btnSave"
        android:ems="10">

        <requestFocus />

    </EditText>

    <EditText
        android:id="@+id/txtText2"
        android:layout_width="276dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignStart="@+id/txtText1"
        android:layout_marginTop="122dp" />

    <TextView
        android:id="@+id/lblFileName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignTop="@+id/txtText1"
        android:text="File name: " />

    <TextView
        android:id="@+id/lblData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignTop="@+id/txtText2"
        android:text="Data: " />

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/btnRead"
        android:text="Save" />

    <Button
        android:id="@+id/btnRead"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="105dp"
        android:layout_marginTop="188dp"
        android:text="Read" />



</RelativeLayout>


main java :


Code:
package com.justforum.yotamarker.iternalstorage;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;

public class MainActivity extends AppCompatActivity {

    EditText editTextCb1, editTextCb2;
    Button buttonCbSave, buttonCbRead;

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

        editTextCb1 = (EditText)findViewById(R.id.txtText1);
        editTextCb2 = (EditText)findViewById(R.id.txtText2);
        buttonCbSave = (Button)findViewById(R.id.btnSave);
        buttonCbRead = (Button)findViewById(R.id.btnRead);

        buttonCbSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String fileName = editTextCb1.getText().toString();
                String data = editTextCb2.getText().toString();

                // calling FileOutputStream
                FileOutputStream fos;
                try
                {
                    fos = openFileOutput(fileName, Context.MODE_PRIVATE);
                    // Context.MODE_PRIVATE IS DEFAULT
                    fos.write(data.getBytes());
                    fos.close();
                    editTextCb2.setText("");
                    Toast.makeText(getApplicationContext(), fileName + "Saved " ,
                            Toast.LENGTH_SHORT).show();
                }
                catch (FileNotFoundException e)
                {
                    e.printStackTrace();
                }
                catch (IOException e){
                    e.printStackTrace();
                }

            }
        });

        // Preform read FileInputStream
        buttonCbRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String fileName = editTextCb1.getText().toString();
                StringBuffer stringBuffer = new StringBuffer();
                try
                {
                    BufferedReader inputReader =
                            new BufferedReader(new
                                    InputStreamReader(openFileInput(fileName)));
                    String inputString;
                    while((inputString = inputReader.readLine())!= null) {
                        stringBuffer.append(inputString);
                    }
                }
                catch (IOException e){
                    e.printStackTrace();
                }
                Toast.makeText(getApplicationContext(), stringBuffer.toString(),
                        Toast.LENGTH_SHORT).show();
            }
        });

    }
}

_________________
MB over and out _______________________     
Back to top Go down
View user profile
Moti Barski

avatar

Posts : 197
Join date : 2011-08-02

PostSubject: android read write to external SD card walkthrough   Sun Jun 17, 2018 11:58 pm



I twicked the code in here : https://www.journaldev.com/9400/android-external-storage-read-write-save-file
so that the data is stored as a dictionary :
key (String): myInputText2 (lower one on the UI)
value (String): myInputText (upper one)

activity main XML :

Code:

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

   <TextView android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="Reading and Writing to External Storage"
       android:textSize="24sp"/>

   <EditText android:id="@+id/myInputText"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:ems="10" android:lines="5"
       android:minLines="3" android:gravity="top|left"
       android:inputType="textMultiLine">

       <requestFocus />
   </EditText>

   <EditText android:id="@+id/myInputText2"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:ems="10" android:lines="5"
       android:minLines="3" android:gravity="top|left"
       android:inputType="textMultiLine"></EditText>

   <LinearLayout
       android:layout_width="match_parent" android:layout_height="wrap_content"
       android:orientation="horizontal"
       android:weightSum="1.0"
       android:layout_marginTop="20dp">

       <Button android:id="@+id/saveExternalStorage"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:text="SAVE"
           android:layout_weight="0.5"/>

       <Button android:id="@+id/getExternalStorage"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_weight="0.5"
           android:text="READ" />

   </LinearLayout>

   <TextView android:id="@+id/response"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content" android:padding="5dp"
       android:text=""
       android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

main java :

Code:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends Activity {
    EditText inputText, path;
    TextView response;
    Button saveButton,readButton;

    private String filename = "SampleFile.txt";
    private String filepath = "MyFileStorage2";
    File myExternalFile;
    String myData = "";

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

        inputText = (EditText) findViewById(R.id.myInputText);
        response = (TextView) findViewById(R.id.response);
        path = (EditText) findViewById(R.id.myInputText2);

        saveButton =
                (Button) findViewById(R.id.saveExternalStorage);
        saveButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    filename = path.getText().toString();
                    myExternalFile = new File(getExternalFilesDir(filepath), filename);
                    FileOutputStream fos = new FileOutputStream(myExternalFile);
                    fos.write(inputText.getText().toString().getBytes());
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                inputText.setText("");
                response.setText("SampleFile.txt saved to External Storage...");
            }
        });

        readButton = (Button) findViewById(R.id.getExternalStorage);
        readButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    filename = path.getText().toString();
                    myExternalFile = new File(getExternalFilesDir(filepath), filename);
                    FileInputStream fis = new FileInputStream(myExternalFile);
                    DataInputStream in = new DataInputStream(fis);
                    BufferedReader br =
                            new BufferedReader(new InputStreamReader(in));
                    String strLine;
                    while ((strLine = br.readLine()) != null) {
                        myData = myData + strLine;
                    }
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                inputText.setText(myData);
                response.setText("SampleFile.txt data retrieved from external Storage...");
                myData = "";
            }
        });

        if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
            saveButton.setEnabled(false);
        }
        else {
            myExternalFile = new File(getExternalFilesDir(filepath), filename);
        }


    }
    private static boolean isExternalStorageReadOnly() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
            return true;
        }
        return false;
    }

    private static boolean isExternalStorageAvailable() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
            return true;
        }
        return false;
    }


}

manifest :

add :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
above :
<application

so it looks like :


Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.projectnamedomain">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

lv3.

_________________
MB over and out _______________________     
Back to top Go down
View user profile
 
android mobile app dev APK
Back to top 
Page 1 of 3Go to page : 1, 2, 3  Next
 Similar topics
-
» [Hỏi đáp] Làm sao vào giao diện mobile trên pc
» Licensed VPS[sale/Rent]+UAE Unblock Mobile dialer
» UAE Anti blocking pc2phone & mobile dialer for Rent/Purchase
» VPS with relay server based PC2Phone & mobile dialer at $499
» Mobile dialer certified by NOIKA for sale/Rent

Permissions in this forum:You cannot reply to topics in this forum
battle programmers alliance :: battle programming alliance :: battle programming-
Jump to: