Note: all the examples use Kotlin and not Java.
Create a layout:
- Right click on "res" folder -> new -> Android resource directory.
- Name it "layout" and also change its type to "layout". Click on "OK" which should create the layout directory
Next create a basic activity
- Right click on the new "layout" directory -> new -> Activity -> Empty Activity
Add default activity to manifest:
- Click on Manifests directory -> AndroidManifest.xml
- Insert the following :
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
val intent = Intent(context,<activity_name>::class.java)
intent.putExtra("var_name", "var_value")
context!!.startActivity(intent)
- Apply changes: click on terminal -> insert
gradlew clean
and press ctrl + enter
- Change text:
textID.text = "some text"
- Center text: in the IDE menu click on
Attributes -> gravity -> center
Go to main activity and under the main activity class, add this
<button_id>.setOnClickListener{
// Add code to execute when the button is clicked on
}
In the UI, set onClick to "change" and add the following function
fun change(view: View) {
}
Note: onClick is set to "change"
fun change(view: View) {
imageView.setImageResource(R.drawable.<image_name>)
}
fun update(view: View) {
textView.text = "text changed! :)"
}
- wrap content - the width of the button will be set based on the content (length of the text for example)
- match parent - the width will be based on the width of the parent in component tree
- Use "pt" measurement for setting the width or height of components (e.g. 30pt)
binding.shareButton.setOnClickListener {
val shareIntent = Intent().apply {
this.action = Intent.ACTION_SEND
this.putExtra(Intent.EXTRA_TEXT, "Check out this app on Google Play\n\n" +
"http://play.google.com/store/apps/details?id=com.X.Y")
this.type = "text/plain"
}
startActivity(shareIntent)
}
binding.rateButton.setOnClickListener {
val rateIntent = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.X.Y"))
startActivity(rateIntent)
}
Palette -> Text -> Plain Text
-
Change input type:
Attributes -> inputType
-
Hint (input text disappears as soon as the user starts typing)
Attributes -> EditText -> hint -> put your text
Attributes -> TextView -> text -> remove text
The id of the input field is x
// string
val userInput = x.text.toString()
// integer
val userInput = Integer.parseInt(x.text.toString())
import java.util.*
val currentYear = Calendar.getInstance().get(Calendar.YEAR)
- You click on the line number to add a breakpoint
- Click on "debug" button to start running (Bug icon, Shift + F9)
You can log messages and see them when clicking on "Logcat" in the IDE.
import android.util.Log
Log.d("Log Tag", "Hey, you logged this line")
<TableRow
android:gravity="center"
...
// Same can be added to table layout to center everything in a table
- Go to res -> values -> colors.xml
- Add a new line like:
<color name="colorAccent">#03DAC5</color>
- You can now use reference it this way:
"@color/colorAccent"
val builder = AlertDialog.Builder(this)
with(builder) {
setTitle("Data Reset Warning")
setPositiveButton("Do It"){dialog, which ->
db.reset()
}
setNegativeButton("Cancel"){dialog, which ->
}
setMessage("This will reset the application data. Are you sure you wanna do that?")
}
val dialog: AlertDialog = builder.create()
dialog.show()
Drag and drop images to res -> drawable (if drawable doesn't exists then right click on "res" -> new -> Android Resource Directory)
R.drawable.<image_name>
binding.someImageView.setImageResource(R.drawable.someOtherImage)
Toast.makeText(this, "Wow!", Toast.LENGTH_LONG).show()
- Add to build.gradle (module level) the following
buildFeatures {
viewBinding true
}
- In MainActivity add and change the following
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
<EditText
android:id="@+id/playerName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="32sp"></EditText>
android:enabled="false"
android:background="@android:color/transparent"
android:maxLength="10"
binding.someEditText.isFocusable=true
binding.someEditText.isEnabled=true
binding.someEditText.isFocusableInTouchMode=true
binding.someEditText.isFocusable=true
binding.someEditText.isCursorVisible=true
binding.someEditText.requestFocus()
val inputMethodManager = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(it, InputMethodManager.SHOW_FORCED)
Go to res -> layout -> activity_main.xml and in "Text" change it to
LinearLayout
Unfortuantely it doesn't seems there is a site with a collection of hardawre profiles, so if you would like to have an hardware profile for an existing phone, you'll have to create a new hardware profile
AVD manager -> Create Virtual Device... -> New Hardware Profile
- Right click on layout directory
- New -> Layout Resource File
- Name it the same "activity_main"
- In directory name append "-mdpi" or any other screen size you would like to support
ctrl + shift + a -> convert java file to kotlin
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, ACCESSLOCATION))
Inside Thread class add the following
runOnUiThread {}
Sleep for 1000 miliseconds
Thread.sleep(1000)
For an application that is using Google Maps you have to obtain an API key
Once obtained, put it in google_maps_api.xml
In order for the app work properly change this line
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
to
<uses-permission android:name="android.permission.INTERNET" />
mMap = googleMap
val sydney = LatLng(-34.0, 151.0)
mMap.addMarker(MarkerOptions()
.position(sydney)
.title("Me")
.snippet("My Location")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.<IMAGE_NAME_IN_DRAWABLE_DIR>)))
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,14f))
Add the following to AndroidManifest.xml: <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Make sure to change google_maps_api.xml from debug to release. Click on "Build Variables" in left side menu and in the dropbox choose "release"
A class for managing Database operations (like create, insert, etc.)
class DatabaseHandler(context: Context) :
SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
companion object {
private const val DATABASE_VERSION = 1
private const val DATABASE_NAME = "MyDatabasse"
private const val TABLE_PLAYER = "PlayerTable"
private const val KEY_ID = "_id"
private const val KEY_NAME = "name"
}
override fun onCreate(db: SQLiteDatabase?) {
val CREATE_PLAYER_TABLE = ("CREATE TABLE "+ TABLE_PLAYER + "("
+KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT" + ")")
db?.execSQL(CREATE_PLAYER_TABLE)
}
}
This is useful for use cases like adding a player. You don't want to add a player every time a user starts the app.
The way to do it is calling the "addPlayer" function once from "onCreate" method of your Database handler class.
Delete database called "MyDatabase"
this.deleteDatabase("MyDatabase")
val booleanVar = cursor.getInt(SOME_KEY_IN_DB) > 0;