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.
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 :
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):
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"; } } }
Last edited by Moti Barski on Wed Oct 10, 2018 1:15 am; edited 1 time in total
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 //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) {
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 } }
Last edited by Moti Barski on Wed Oct 10, 2018 1:16 am; edited 1 time in total
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"
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(); } }
Last edited by Moti Barski on Wed Oct 10, 2018 1:19 am; edited 1 time in total
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; } }
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
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);
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(" "));
// 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(); } }
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.
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};
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);
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);
@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);
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"/>
// 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; }
// 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)); }
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
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; }
in manifests folder in the solution explorer in the AndroidManifest.xml add internet browsing permission : <uses-permission android:name="android.permission.INTERNET"/>
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.
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'
class RecyclerViewHandler extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnLongClickListener{ public TextView txt_description; public ImageView pic; private ItemClickListener itemClickListener;
class RecyclerViewHandler extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnLongClickListener{ public TextView txt_description; public ImageView pic; private ItemClickListener itemClickListener;
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
Last edited by Moti Barski on Thu Jul 19, 2018 6:19 am; edited 4 times in total
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);
@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"); } } } }
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">
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); }
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 :
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Reading and Writing to External Storage" android:textSize="24sp"/>