Android Development Snippets
Common tasks in Android development and the required code snippet
Print and Debug:
Log.d("Tag", "Message");
Toast.makeText(MainActivity.this, "hello", Toast.LENGTH_LONG).show();
Updating component
TextView t=(TextView)findViewById(R.id.textViewId);
t.setText("String");
Start activity
Intent in=new Intent("action name");
startActivity(in)
Start Activity and send parameters:
Intent in=new Intent("mabel.xyz");
in.putExtra("num", 100);
startActivityForResult(in, 0);
Return value from Activity:
Intent res=new Intent();
res.putExtra("res", num+20);
setResult(20, res);
finish(); // To close the Activity - optional
Get the Activity result:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int res=data.getIntExtra("res", 99);
}
Dialog Example
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are You Sure?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// code for yes
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
Creating GUI from XML in runtime:
ToggleButton button = (ToggleButton) act.getLayoutInflater().inflate(
R.layout.template_my_button, null);
// The XML:
// <ToggleButton xmlns:android="http://schemas.android.com/apk/res/android"
// style="@style/switch_icon_style"
// />
Recent Stories
Top DiscoverSDK Experts
Mendy Bennett
Experienced with Ad network & Ad servers.
Mobile | Ad Networks and 1 more
View Profile
Karen Fitzgerald
7 years in Cross-Platform development.
Mobile | Cross Platform Frameworks
View Profile
X
Compare Products
Select up to three two products to compare by clicking on the compare icon () of each product.
{{compareToolModel.Error}}Now comparing:
{{product.ProductName | createSubstring:25}} X
{{CommentsModel.TotalCount}} Comments
Your Comment