Android Tips
Android Tips
v=dF0m_PG111g - very
good for round button cration in Android studio..
Code Implementation
Button btn = (Button) findViewById(R.id.mybutton);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myFancyMethod(v);
}
});
Note that with the XML above, Android will look for the onClick method myFancyMethod() only in
the current Activity. This is important to remember if you are using fragments, since even if you
add the XML above using a fragment, Android will not look for the onClick method in
the .java file of the fragment used to add the XML.
Another important thing I noticed. You mentioned you don't prefer anonymous methods. You
meant to say you don't like anonymous classes.
-------x-------------------x---------------x-------
1
how to read value from string.xml in android?
String mess = getResources().getString(R.string.mess_1);
‘’
Media Player Looping : Android
down vote accepted mMediaPlayer.setLooping(true);
Vibrate onclick
is there a way to get a button to vibrate but only when the if condition is verified?
Yes. It looks like you have 95% of the code there already. Where did you get stuck?
You already have a Vibrator Object and a conditional. All you need to do now is
call vibrate() like so:
Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
Try:
import android.os.Vibrator;
...
Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);
Note:
Don't forget to include permission in AndroidManifest.xml file:
<uses-permission android:name="android.permission.VIBRATE"/>
2
Use this approach to get your desired look.
button_selector.xml :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<layer-list>
<item android:right="5dp" android:top="5dp">
<shape>
<corners android:radius="3dp" />
<solid android:color="#D6D6D6" />
</shape>
</item>
<item android:bottom="2dp" android:left="2dp">
<shape>
<gradient android:angle="270"
android:endColor="#E2E2E2" android:startColor="#BABABA" />
<stroke android:width="1dp" android:color="#BABABA" />
<corners android:radius="4dp" />
<padding android:bottom="10dp" android:left="10dp"
android:right="10dp" android:top="10dp" />
</shape>
</item>
</layer-list>
</item>
</selector>
And in your xml layout:
<Button
android:background="@drawable/button_selector"
...
..
/>
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because
they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger
than they were intended. Because of this, they use the next size up.
3
how to arrange xml code in android studio
1. Choose File > Settings > Code Style > XML > Set from > Predefined Style > Android.
2. Set File > Settings > Editor > Formatting > Show "Reformat Code" dialog.
3. Run formatting on a XML file ( CTRL+ALT+L by default)
4. You will see a popup window, set the Rearrange entries flag.
????????????????????????????????????????????????????????????????????????????????
Step1:
Goto
http://console.firebase.google.com
4
Step2:
In the above screen give the Project Name and Country Region then press the Create Project
5
In the above screen choose the ‘Add Firebase to your Android app’ button
6
of your android program then press ‘ADD APP’, then it gives a Json file named
google-services.json. Put this file to your Android app Module root directory
7
In the above screen press the CONTINUE button.
After press the ‘CONTINUE’ button it gives the following screen. Based on the
screen. It gives some dependency values. Put these dependency values to your
android program’s gradle build file and sync. The gradle build file.
8
compile 'com.google.firebase:firebase-messaging:9.0.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
9
This screen gives the server key, copy the server key and put the notification php file.
Server key
AIzaSyDYXDCCj5n7jQ558Lqu63qGWrKimhjtxzY
Sender ID
1062771646447
The above server key and Sender ID created from [email protected] account.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Server key
AIzaSyBz0hq5qRM1S73JOgBF6bs-aN_UhKEnxgk
Sender ID
271373187896
The above server key and Sender ID created from [email protected] account.
10
For push notification in Sri Ramanasramam Live Video Android app
????????????????????????????????????????????????????????????????????????????????
I
To insert more than one record at once, we can do this, with each set of field values
separated by a comma:
????????????????????????????????????????????????????????????????????????????????
11
Map<String,String> map=new HashMap<>();
Map.Entry<String,String> entry=map.entrySet().iterator().next();
String key= entry.getKey();
String value=entry.getValue();
But you need to know HashMap not grantee the insertion order. You can use LinkedHashMap for
keep order.
Eg:
Active
33
????????????????????????????????????????????????????????????????????????????????
12
You could use a Timer and add a TimerTask that is executed after a specific delay.
Here is a more or less completed example:
}, 10000);
The example above executes a new TimerTask in 10 seconds. Inside the TimerTask you can
override the run method. In the run method you can start your new activity. The run method is
executed after the delay. In this example it is 10'000 milliseconds.
<RelativeLayout 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" >
<Button
android:id="@+id/previousButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="New Button" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:layout_alignParentBottom="true"
android:id="@+id/nextButton"
android:layout_toRightOf="@id/previousButton"
/>
</RelativeLayout>
13
????????????????????????????????????????????????????????????????????????????????
Adjust with your current API Level. If the API level isn't in the list, you'll need to install it via the
SDK Mangager.
14
????????????????????????????????????????????????????????????????????????????????
Configuration examples
To help you target some of your designs for different types of devices, here are some numbers for typical
screen widths:
320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
Using the size qualifiers from table 2, your application can switch between your different layout resources
for handsets and tablets using any number you want for width and/or height. For example, if 600dp is the
smallest available width supported by your tablet layout, you can provide these two sets of layouts:
In this case, the smallest width of the available screen space must be 600dp in order for the tablet layout
to be applied.
For other cases in which you want to further customize your UI to differentiate between sizes such as 7”
and 10” tablets, you can define additional smallest width layouts:
Notice that the previous two sets of example resources use the "smallest width" qualifier, sw<N>dp, which
specifies the smallest of the screen's two sides, regardless of the device's current orientation. Thus,
usingsw<N>dp is a simple way to specify the overall screen size available for your layout by ignoring the
screen's orientation.
However, in some cases, what might be important for your layout is exactly how much width or height
iscurrently available. For example, if you have a two-pane layout with two fragments side by side, you
might want to use it whenever the screen provides at least 600dp of width, whether the device is in
landscape or portrait orientation. In this case, your resources might look like this:
15
res/layout/main_activity.xml # For handsets (smaller than 600dp available width)
res/layout-w600dp/main_activity.xml # Multi-pane (any screen with 600dp available width
or more)
Notice that the second set is using the "available width" qualifier, w<N>dp. This way, one device may
actually use both layouts, depending on the orientation of the screen (if the available width is at least
600dp in one orientation and less than 600dp in the other orientation).
If the available height is a concern for you, then you can do the same using the h<N>dp qualifier. Or, even
combine the w<N>dp and h<N>dp qualifiers if you need to be really specific.
????????????????????????????????????????????????????????????????????????????????
First we will create a php script that will fetch the data from the database.
1 <?php
2 define('HOST','mysql.hostinger.in');
3 define('USER','u813815354_user');
4 define('PASS','bhaq2010');
5 define('DB','u813815354_db');
7 $con = mysqli_connect(HOST,USER,PASS,DB);
10
16
11 $res = mysqli_query($con,$sql);
1 $res = mysqli_query($con,$sql);
Push the fetched data in the array as key=>value format (associative array).
Key would be the column name.
1 while($row = mysqli_fetch_array($res)){
2 array_push($result,
3 array('id'=>$row[0],
4 'name'=>$row[1],
5 'address'=>$row[2]
6 ));
7}
1 echo json_encode(array("result"=>$result));
17
3 mysqli_close($con);
5 ?>
1 <?php
2 define('HOST','mysql.hostinger.in');
3 define('USER','u813815354_user');
4 define('PASS','bhaq2010');
5 define('DB','u813815354_db');
7 $con = mysqli_connect(HOST,USER,PASS,DB);
10
11 $res = mysqli_query($con,$sql);
12
13 $result = array();
14
15 while($row = mysqli_fetch_array($res)){
16 array_push($result,
17 array('id'=>$row[0],
18 'name'=>$row[1],
19 'address'=>$row[2]
20 ));
21 }
22
23 echo json_encode(array("result"=>$result));
18
24
25 mysqli_close($con);
26
27 ?>
You can copy the above code. Save the code with some name (Extension must be .php). Upload the
file to your server and try executing it.
The above link will give JSON String. Itt has an array of objects name result. In result we have
objects containing all the value. Each object has three values id, name and address.
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
3 android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
4 android:paddingRight="@dimen/activity_horizontal_margin"
5 android:paddingTop="@dimen/activity_vertical_margin"
6 android:orientation="vertical"
7 android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
19
10 <ListView
11 android:layout_width="match_parent"
12 android:layout_height="wrap_content"
13 android:id="@+id/listView" />
14 </LinearLayout>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="fill_parent"
4 android:layout_height="wrap_content"
5 android:orientation="vertical"
6 android:padding="10dp"
7 android:paddingLeft="10dp"
8 android:paddingRight="10dp" >
10
11 <TextView
12 android:id="@+id/id"
13 android:layout_width="fill_parent"
14 android:layout_height="wrap_content"
15 android:paddingBottom="2dip"
16 android:paddingTop="6dip"
17 android:textStyle="bold" />
20
18
19
20 <TextView
21 android:id="@+id/name"
22 android:layout_width="fill_parent"
23 android:layout_height="wrap_content"
24 android:paddingBottom="2dip"
25 android:textStyle="bold"/>
26
27
28 <TextView
29 android:id="@+id/address"
30 android:layout_width="wrap_content"
31 android:layout_height="wrap_content"
32 android:gravity="left"
33 android:textStyle="bold" />
34
35 </LinearLayout>
3 String myJSON;
21
8 private static final String TAG_ADD ="address";
11
13
14 ListView list;
myJSON is the string where we will store the JSON string from server.
We have declared some final String TAGS for getting the values from JSON String and
A JSONArray peoples for storing the JSON Array and
An array list for creating a list from JSON and
A ListView for displaying the list in the Activity
Come to onCreate method
1 @Override
3 super.onCreate(savedInstanceState);
4 setContentView(R.layout.activity_main);
7 getData();
8 }
22
1 public void getData(){
4 @Override
10 httppost.setHeader("Content-type", "application/json");
11
14 try {
17
18 inputStream = entity.getContent();
22
25 {
26 sb.append(line + "\n");
27 }
23
28 result = sb.toString();
29 } catch (Exception e) {
30 // Oops
31 }
32 finally {
34 }
35 return result;
36 }
37
38 @Override
40 myJSON=result;
41 showList();
42 }
43 }
45 g.execute();
46 }
getData is executing an AsyncTask. In the AyncTask class the doInBackgroundMethod will return the
JSON String.
In onPostExecute method we will store that String to myJSON. Then we will call a new showList()
method to show the JSON string in the ListView after parsing.
2 try {
24
4 peoples = jsonObj.getJSONArray(TAG_RESULTS);
6 for(int i=0;i<peoples.length();i++){
7 JSONObject c = peoples.getJSONObject(i);
8 String id = c.getString(TAG_ID);
11
13
14 persons.put(TAG_ID,id);
15 persons.put(TAG_NAME,name);
16 persons.put(TAG_ADD,address);
17
18 personList.add(persons);
19 }
20
23 new String[]{TAG_ID,TAG_NAME,TAG_ADD},
25 );
26
27 list.setAdapter(adapter);
28
29 } catch (JSONException e) {
30 e.printStackTrace();
31 }
32
33 }
25
Our final complete MainActivity.java is
1 package net.simplifiedcoding.fetchjson;
3 import android.os.AsyncTask;
4 import android.support.v7.app.ActionBarActivity;
5 import android.os.Bundle;
6 import android.view.Menu;
7 import android.view.MenuItem;
8 import android.widget.ListAdapter;
9 import android.widget.ListView;
10 import android.widget.SimpleAdapter;
11 import android.widget.TextView;
12
13 import org.apache.http.HttpEntity;
14 import org.apache.http.HttpResponse;
15 import org.apache.http.client.methods.HttpPost;
16 import org.apache.http.impl.client.DefaultHttpClient;
17 import org.apache.http.params.BasicHttpParams;
18 import org.json.JSONArray;
19 import org.json.JSONException;
20 import org.json.JSONObject;
21
22 import java.io.BufferedReader;
23 import java.io.InputStream;
24 import java.io.InputStreamReader;
25 import java.util.ArrayList;
26 import java.util.HashMap;
26
27
28
30
31 String myJSON;
32
37
39
41
42 ListView list;
43
44 @Override
46 super.onCreate(savedInstanceState);
47 setContentView(R.layout.activity_main);
50 getData();
51 }
52
53
55 try {
57 peoples = jsonObj.getJSONArray(TAG_RESULTS);
27
58
59 for(int i=0;i<peoples.length();i++){
60 JSONObject c = peoples.getJSONObject(i);
61 String id = c.getString(TAG_ID);
64
66
67 persons.put(TAG_ID,id);
68 persons.put(TAG_NAME,name);
69 persons.put(TAG_ADD,address);
70
71 personList.add(persons);
72 }
73
76 new String[]{TAG_ID,TAG_NAME,TAG_ADD},
78 );
79
80 list.setAdapter(adapter);
81
82 } catch (JSONException e) {
83 e.printStackTrace();
84 }
85
86 }
87
28
89 class GetDataJSON extends AsyncTask<String, Void, String>{
90
91 @Override
95
97 httppost.setHeader("Content-type", "application/json");
98
101 try {
104
109
112 {
114 }
117 // Oops
118 }
119 finally {
29
120 try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
121 }
123 }
124
125 @Override
127 myJSON=result;
128 showList();
129 }
130 }
132 g.execute();
133 }
134
135 @Override
137 // Inflate the menu; this adds items to the action bar if it is present.
140 }
141
142 @Override
144 // Handle action bar item clicks here. The action bar will
148
30
151 return true;
152 }
153
155 }
156 }
2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3 package="net.simplifiedcoding.fetchjson" >
8 <application
9 android:allowBackup="true"
10 android:icon="@mipmap/ic_launcher"
11 android:label="@string/app_name"
12 android:theme="@style/AppTheme" >
13 <activity
14 android:name=".MainActivity"
15 android:label="@string/app_name" >
16 <intent-filter>
18
31
20 </intent-filter>
21 </activity>
22 </application>
23
24 </manifest>
32
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.support.v4.util.SimpleArrayMap;
import android.support.v4.util.ArrayMap;
String myJSON;
private static final String TAG_RESULTS = "res";
private static final String TAG_ID = "event";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> eventList;
TextView view, t1, t2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jason_event);
Typeface font1 = Typeface.createFromAsset(getAssets(), "TAU_CHON.TTF");
Typeface font = Typeface.createFromAsset(getAssets(), "FutuLt_0.ttf");
t1 = (TextView) findViewById(R.id.headertxt);
t1.setTypeface(font1);
view = (TextView) findViewById(R.id.jasonTxt);
t2 = (TextView) findViewById(R.id.txtV3);
view.setTypeface(font);
33
Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.blink);
view.startAnimation(animation1);
t2.setTypeface(font);
eventList = new ArrayList<HashMap<String, String>>();
getData();
//view.setText(xx);
@Override
protected String doInBackground(String... params) {
//DefaultHttpClient httpclient = new DefaultHttpClient(new
BasicHttpParams());
//HttpPost httppost = new HttpPost("http://simplifiedcoding.16mb.com/get-
data.php");
}
result = buffer.toString();
return result;
}
34
@Override
protected void onPostExecute(String result) {
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
//String name = c.getString(TAG_NAME);
//String address = c.getString(TAG_ADD);
persons.put(TAG_ID,id);
//persons.put(TAG_NAME,name);
//persons.put(TAG_ADD,address);
eventList.add(persons);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void goBack(View view){
finish();
}
}
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
35
Code name Version API level
36
Code name Version API level
Log.e: This is for when bad stuff happens. Use this tag in places like inside a catch
statment. You know that an error has occurred and therefore you're logging an error.
Log.w: Use this when you suspect something shady is going on. You may not be
completely in full on error mode, but maybe you recovered from some unexpected behavior.
Basically, use this to log stuff you didn't expect to happen but isn't necessarily an error. Kind
of like a "hey, this happened, and it's weird, we should look into it."
Log.i: Use this to post useful information to the log. For example: that you have
successfully connected to a server. Basically use it to report successes.
Log.d: Use this for debugging purposes. If you want to print out a bunch of messages so
you can log the exact flow of your program, use this. If you want to keep a log of variable
values, use this.
Log.v: Use this when you want to go absolutely nuts with your logging. If for some reason
you've decided to log every little thing in a particular part of your app, use the Log.v tag.
And as a bonus...
Log.wtf: Use this when stuff goes absolutely, horribly, holy-crap wrong. You know those
catch blocks where you're catching errors that you never should get...yea, if you wanna log
them use Log.wtf
37
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
2. Density Classes
Class Name Density Factor Drawable Folder Comment
sp = 3/4 *
ldpi low density 120 dpi drawable-ldpi
dp
sp = 2 x
xhdpi extra high density 320 dpi drawable-xhdpi
dp
38
96x96 / 64x64 / 64x64 / 32x32 / 24x24
xhdpi 96x96 px 48x48 / 44x44 px 64x64 px
64x64 px 48x48 px 56x56 px px
144x144
xxhdpi (1) (1) (1) (1) (1) (1)
px
192x192
xxxhdpi (1) (1) (1) (1) (1) (1)
px
(1) Google documentation says: "Applications should not generally worry about this density; relying
on XHIGH graphics being scaled up to it should be sufficient for almost all cases."
Launcher icons for Android Market: 512x512 px.
960x720
xlarge layout-xlarge 10" tablet (720x1280 mdpi, 800x1280 mdpi, etc.)
dp
WVGA800
WQVGA400
(480x800)
(240x400)
normal HVGA (320x480) WVGA854 640x960
WQVGA432
(480x854)
(240x432)
600x1024
39
WVGA854 600x1024
(480x854)(2)
(1) To emulate this configuration, specify a custom density of 160 when creating an Android Virtual
Device that uses a WVGA800 or WVGA854 skin.
(2) To emulate this configuration, specify a custom density of 120 when creating an Android Virtual
Device that uses a WVGA800 or WVGA854 skin.
(3) This skin is available with the Android 3.0 platform.
6. Screen Orientation
Orientation Name Layout Folder, Example
7. Best Practices
1. Use wrap_content, match_parent, or dp units when specifying dimensions in an XML layout file.
o except for defining text sizes: sp (scaling depends on user setting)
o Note: fill_parent is deprecated since API level 8.
2. Do not use hard coded pixel values in your application code.
3. Do not use AbsoluteLayout.
o deprecated since Android 1.5
o alternative: RelativeLayout
4. Supply alternative bitmap drawables for different screen densities.
5. Provide a launcher icon for xxhdpi, but no other icons.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Pixel Densities
Android icons require five separate sizes for different screen pixel densities. Icons for lower resolution are created
automatically from the baseline.
40
hdpi: 240 dpi 1.5×
xhdpi: 320 dpi 2×
xxhdpi: 490 dpi 3×
xxxhdpi: 640 dpi 4×
Launcher icons
24 × 24 area in 32 × .png These icons are used in the action bar menu. The first number is the
32 (mdpi) size of the icon area, and the second is file size.
36 × 36 area in 48 ×
48 (hdpi)
48 × 48 area in 64 ×
64 (xhdpi)
72 × 72 area in 96 ×
96 (xxhdpi)
96 × 96 area in 128 ×
128 (xxxhdpi)
16 × 16 (mdpi) .png Small icons are used to surface actions and/or provide status for specific
24 × 24 (hdpi) items. For example, in the Gmail app, each message has a star icon that
32 × 32 (xhdpi) marks the message as important.
48 × 48 (xxhdpi)
64 × 64 (xxxhdpi)
Notification icons
22 × 22 area in 24 × .png These are used to represent application notifications in the status bar.
24 (mdpi) They should be flat (no gradients), white and face-on perspective
33 × 33 area in 36 ×
36 (hdpi)
41
44 × 44 area in 48 ×
48 (xhdpi)
66 × 66 area in 72 ×
72 (xxhdpi)
88 × 88 area in 96 ×
96 (xxxhdpi)
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
42
<activity android:name="MainActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation">
However, your application can be interrupted at any time, e.g. by a phone call, so you really should
add code to save the state of your application when it is paused.
<activity
android:name="MainActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
First create your own error page in HTML and put it in your assets folder, Let's call it
myerrorpage.html Then with onReceivedError:
mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String
failingUrl) {
mWebView.loadUrl("file:///android_asset/myerrorpage.html");
}
});
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
What is Gradle?
For those who can talk in computer languages, Gradle is an automation tool that Google
chose to use for building dependencies & compiling, running unit tests before deployment,
and deploying your application. For the ordinary folks, it's a magical program that computer
wizards at Google chose to help us building nice-and-tight Android apps. It supports beyond
Android as well: Java, Groovy (The language Gradle use), Scala, Assembly, C/C++,
Objective-C, and so on.
When Gradle was first released, I remember struggling to use it. Android Studio was still
unstable, and the build kept failing as my head kept banging against the wall. But when the
life gives you lemons, make lemonade. After learning more about Gradle, I'm here to give
you some Gradle usage and tips. SPOILER ALERT: This is going to be a long blog post.
1. Do you have open source/3rd party libraries or binary JAR files? Gradle can add and
import them!
44
2. You can create a list of tasks for Gradle to perform before building or compiling Android
app.
3. You can create multiple flavors of your app by overriding your project files and its
inheritance. (Pro/Free version is the easiest example.)
4. You can run unit tests before building so that your app unit features would be all tested
before compiling.
5. Many more!
It is very different perspective to look at what Gradle does comparing to what we develop
software by programming. It's about the building process until its successful deployment. It's
not about programming bugs or creating features.
When you create a new Android app project using Android Studio, a default Gradle task list
is also generated. It handles a lot of things for us such as compiling Java codes to its class
files, compiling your project libraries into JAR binary files, generating DEX byte codes, JAR
signing, Zip-aligning, and finally creating the APK executable binary file.
As you can see, Gradle can handle your project's library dependencies. You can create your
own build process if you want. You can accomplish the freemium model (A typical Android
app revenue model) or region-specific app variants. You can make sure that your app will
not crash when it's bulit because of the unit tests run by Gradle.
45
// build.gradle file
// Top-level build file where you can add configuration options common to all sub-
projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.12.2'
allprojects {
repositories {
jcenter()
mavenCentral()
maven {
url "SOME OTHER MAVEN REPOSITORY URLS"
}
}
}
What was that settings.gradle file? This is a file responsible for finding your sub projects and
linking them properly when building. In a new Android project, you'll see app folder which is
the actual Android project directory. However if you have Android Wear or TV project folders
additionally, settings.gradle file would be the one to include those folders so that Gradle can
know sub-project modules when building the app.
// settings.gradle
46
include ':app', ':wear',' ':tv'
Your project folder is structured by Gradle in a way that you can have multiple sub-project
modules as you witnessed above. This allows us to build your app by the platform: Mobile,
Smartwatch, and TV. That being said, each sub-project module has its own build.gradle only
for itself.
Sub-project folder
- build
-- generated
-- intermediates
- libs
- src
-- androidTest
-- main
--- java
--- res
- build.gradle
The key points here are src folder and build.gradle file. Let's look at the build.gradle file for
this sub-project folder.
android {
compileSdkVersion 20
buildToolsVersion "20.0.0"
47
defaultConfig {
applicationId "com.tivix.android.gradlePlayground"
minSdkVersion 16
targetSdkVersion 20
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
debuggable true
runProguard false
}
productFlavors {
demo {
applicationId "com.tivix.android.gradlePlayground.demo"
versionName "1.0-demo"
}
full {
applicationId "com.tivix.android.gradlePlayground.full"
versionName "1.0-full"
}
}
48
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:support-v4:20.0.0'
compile 'com.google.android.gms:play-services:5.2.08'
compile 'com.google.maps.android:android-maps-utils:0.3'
}
This gradle file is specific for Android phone application. There are many information here
but many of them are straightforward such as compileSdkVersion, buildToolsVersion, and
defaultConfig.
If you look at dependencies portion, that's where you would add your project libraries
to import. Do you have raw Java JAR files? no problem. Put them in libs folder in this sub-
project folder. These days, many of Android/Java libraries are available in Maven repository.
It's essentially PyPi for Java. Gradle would visit the Maven repository, download the library,
and compile down to Gradle-friendly AAR format to import your libraries.
Notice buildTypes portion. This is where you can create a list of build configurations.I
have two build types: release and debug. Each build type has its own build settings to
target. Additionally, you can specify a different JAR signing key file per each build type here
using signingOptions.
Notice productFlavors portions. This is for app-variants. If you're coming from Django
world, Gradle product flavor works like Django's template inheritance. You can override the
project components by adding files in the product flavor. You can add exclusive contents for
the product flavor by adding new files.
All of the product flavors and build types extend src/main folder. Thus, you can assume
that Gradle has a default product called "main." In order to get this working, you need to
create actual folders in the filesystem to represent these, as that is the way Gradle finds the
product flavor in actual build process and can execute the build settings. That being said,
you can mix the product flavor and build type. Above build.gradle can generate below app-
variants:
demo-debug
49
demo-release
full-debug
full-release
debug
release
Now when you synchronize Gradle with your changed filesystem, Gradle actually create
additional tasks for these new variants. Boom. You can now build a specific variant with no
problem from now on. Moreover, each product flavor can now detect its unit test module by
creating the folder androidTest<FlavorName>. For main unit testing, androidTest folder
would run its Gradle task to run its unit tests. At the end, Gradle can actually store the test
result if you specify.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
50
When creating icons, UI images, splash screen, and
other UI images for Android, the designer should
think about the screen size and DPI for quality
drawable resources.
I love the Android platform. The platform is very flexible from OS to app development
aspects, and many people love customizing their phone to show their personality. Because
Android is open-sourced, many phone manufacturers appeal their own form-factor and
customized OS theme. In order to accommodate this, Android has a concept of
Fragmentation to support multiple screen sizes & screen DPIs. However, this is somewhat
painful when it comes to design image resources. If the image has a wrong DPI, then the
image looks blurred, too pixelated, or small-scaled to the original screen. If the resolution is
wrong, the image may not look in fitted size on the screen. Literally, there is a ton of different
screen configurations for the contents to be displayed. Thankfully, Android has a set of
screen size & DPI categories.
Medium - 160DPI
High - 240DPI
Extra Extra Extra High - 640DPI (Available starting from Android 4.3 APIs. For 4K
resolution! Holy Moly!)
51
Android auto-scales the drawables if the device does not match the drawable DPI. If the
only drawables are created in high density, lower DPI screens will down-scale a resource to
fit in a layout. Con is that Android always goes to process the scaling every draw
time in UI thread.
52
What if my drawable doesn’t need to be resized by
different screen factors?
Put your drawables in drawable or drawable-nodpi folder.
This folder would contain drawables available to all screen factors despite of DPIs such as
style XMLs, colors, and others.
If your drawables are fews, try to target all DPIs and sizes.
If your drawables are a lot, try to use one high DPI and size setting for auto-scale.
If your target Android OS version is higher than Ice Cream Sandwich, chances are the
device can handle auto-scale pretty smoothly because of their general hardware specs.
These are some of my insights on drawable resources that the app comes with it to use for
itself. You don't need to worry about actual visual content necessarily. Android will have to
use ImageView or other appropriate layout element to placeholder that visual content with
defined density width & height. That will bring another topic which is mem/disk caching for
images. But as far as designing UI elements for Android, this is sufficient enough to start
off. Android is all about flexibility for developers. Go for one that you feel comfortable and
right about it!
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
</style>
</resources>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
If you want to show a button over a button in a same place in android use the FrameLayout
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView"
android:src="@drawable/play" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton2"
android:layout_alignTop="@+id/imageButton"
android:layout_toRightOf="@+id/imageButton"
android:layout_toEndOf="@+id/imageButton"
android:src="@drawable/pause" />
</FrameLayout>
In the above example play and pause buttons are showing in the same place
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
54
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Toast.makeText(getActivity(), (String)data.result,
Toast.LENGTH_LONG).show();
Another example...
int LENGTH_LONG Show the view or text notification for a long period of time.
int LENGTH_SHORT Show the view or text notification for a short period of time.
Read more about "Toasts"
Another option, customizing your toast:
LayoutInflater myInflater=LayoutInflater.from(this);
View view=myInflater.inflate(R.layout.your_custom_layout,null);
Toast mytoast=new Toast(this);
mytoast.setView(view);
mytoast.setDuration(Toast.LENGTH_LONG);
mytoast.show();
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
LISTVIEW
<ListView
android:layout_height="fill_parent"
android:id="@+id/listView2"
android:layout_width="match_parent"
android:background="@color/red_bg"
android:listSelector="@color/red_bg"
android:cacheColorHint="@color/red_bg"
android:choiceMode="singleChoice"
android:divider="@color/red_bg"
android:dividerHeight="3dip">
</ListView>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
55
how to programmatically hide a button in android sdk
playButton = (Button) findViewById(R.id.play);
playButton.setVisibility(1);
playButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//when play is clicked show stop button and hide play button
playButton.setVisibility(View.GONE);
stopButton.setVisibility(View.VISIBLE);
}
});
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
56
Screen Size
Screen density
Density-independent pixel
A virtual pixel unit that you should use when defining UI layout. Based on a 160 dpi screen.
Size
Small
Normal
Large
Xlarge
Density
Ldpi
Mdpi
Hdpi
Xhdpi
Nodpi
Orientation
Land
Port
Aspect ratio
Lang
Not long
res/layout/my_layout.xml
res/layout-small/my_layout.xml
res/layout-large/my_layout.xml
res/layout-xlarge/my_layout.xml
res/layout-xlarge-land/my_layout.xml
57
Use wrap_content, fill_parent or device independent pixel units when specifying dimensions in an
XML layout file.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and
resources.
* @param context
*/
public DatabaseConnectionAPI(Context context)
{
58
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException
{
if(dbExist)
{
//do nothing - database already exist
}
else
{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try
{
copyDataBase();
}
catch (IOException e)
{
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
59
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
60
@Override
public synchronized void close() {
if(db != null)
db.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
/**
* Use this function to set the value of a particular column
*
* @param columnName The column name whose value is to be changed
* @param newColumnValue The value to be replaced in the column
* @param whereColumnName The column name to be compared with the where clause
* @param whereColumnValue The value to be compared in the where clause
*/
void onUpdateSet(String columnName, String newColumnValue, String[] whereColumnName, String[]
whereColumnValue){
String expanded_ColumnNames = new String(whereColumnName[0]);
String expanded_ColumnValues = new String(whereColumnValue[0]);
for(int i=1;i
{
expanded_ColumnNames = expanded_ColumnNames+","+whereColumnName[i];
expanded_ColumnValues = expanded_ColumnValues+","+whereColumnValue[i];
}
try
{
openDataBase();
db.execSQL("update recipe set \""+columnName+"\" = \""+newColumnValue+"\" where
\""+expanded_ColumnNames+"\" = \""+expanded_ColumnValues+"\"");
}
catch(Exception e)
{
System.out.println("Update couldnt complete "+e);
}
/**
* Query the given table, returning a Cursor over the result set.
61
*
* @param table The table name to compile the query against.
* @param columns A list of which columns to return. Passing null will return all columns,
* which is discouraged to prevent reading data from storage that isn't going to be used.
* @param selection A filter declaring which rows to return, formatted
* as an SQL WHERE clause (excluding the WHERE itself). Passing null
* will return all rows for the given table.
* @param selectionArgs You may include ?s in selection, which will be
* replaced by the values from selectionArgs, in order that they appear
* in the selection. The values will be bound as Strings.
* @param groupBy A filter declaring how to group rows, formatted as an
* SQL GROUP BY clause (excluding the GROUP BY itself). Passing null
* will cause the rows to not be grouped.
* @param having A filter declare which row groups to include in the
* cursor, if row grouping is being used, formatted as an SQL HAVING
* clause (excluding the HAVING itself). Passing null will cause all
* row groups to be included, and is required when row grouping is
* not being used.
* @param orderBy How to order the rows, formatted as an SQL
* ORDER BY clause (excluding the ORDER BY itself). Passing
* null will use the default sort order, which may be unordered.
* @return A Cursor object, which is positioned before the first entry
*/
Cursor onQueryGetCursor(String table, String[] columns, String selection, String[] selectionArgs, String
groupBy, String having, String orderBy)
{
Cursor query = null;
try
{
openDataBase();
query = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
System.out.println("@@@@@ Query is :"+query);
}
catch(Exception e)
{
System.out.println("Query couldnt complete "+e);
}
return query;
}
/**
* Use this method to search a particular String in the provided field.
*
*
* @param columns The array of columns to be returned
* @param table The table name
* @param whereColumn The where clause specifying a particular columns
* @param keyword The keyword which is to be searched
*
62
* @return The cursor containing the result of the query
*/
Cursor onSearchGetCursor(String[] columns, String table, String[] whereColumn, String keyword)
{
String expColumns = new String(columns[0]);
Cursor rawquery=null;
for(int i=1;i
expColumns = expColumns+","+columns[i];
try
{
openDataBase();
rawquery = db.rawQuery("SELECT "+expColumns+" from "+table+" where "+whereColumn[0]+" like
\"%"+keyword+"%\" or "+whereColumn[1]+" like \"%"+keyword+"%\" or "+whereColumn[2]+" like
\"%"+keyword+"%\"", null);
}
catch(Exception e)
{
System.out.println("Raw Query couldnt complete "+e);
}
return rawquery;
}
}
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
63
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Image sizes
640 X 1024
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
import java.io.IOException;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
64
String fileName;
Context contex;
MediaPlayer mp;
//Constructor
public AudioPlayer(String name, Context context) {
fileName = name;
contex = context;
playAudio();
}
//Play Audio
public void playAudio() {
mp = new MediaPlayer();
try {
AssetFileDescriptor descriptor = contex.getAssets()
.openFd(fileName);
mp.setDataSource(descriptor.getFileDescriptor(),
descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
mp.setLooping(true);
mp.start();
mp.setVolume(3, 3);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//Stop Audio
public void stop() {
mp.stop();
}
}
Call this class from any activity like as new AudioPlayer(file_name, mContext);
65
audioPlayer.playAudio();
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
The Android Layout Finder helps you create the code that ties
your Android UI and Java code together.
http://www.technotalkative.com/android/ - good for android tutorial
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Note: This codes are not founded by me, i have just collected through search and
sorted it out.
1. *#*#4636#*#*
This code can be used to get some interesting information about your phone and
battery. It shows following 4 menus on screen:
Phone information
Battery information
Battery history
Usage statistics
2. *#*#7780#*#*
This code can be used for a factory data reset. It’ll remove following things:
Downloaded applications
66
Current system software and bundled applications
PS: Once you give this code, you get a prompt screen asking you to click on “Reset
phone” button. So you get a chance to cancel your operation.
3. *2767*3855#
Think before you give this code. This code is used for factory format. It’ll remove all
files and settings including the internal memory storage. It’ll also reinstall the phone
firmware.
PS: Once you give this code, there is no way to cancel the operation unless you
remove the battery from the phone. So think twice before giving this code.
4. *#*#34971539#*#*
This code is used to get information about phone camera. It shows following 4
menus:
WARNING: Never use the first option otherwise your phone camera will stop working
and you’ll need to take your phone to service center to reinstall camera firmware.
5. *#*#7594#*#*
This one is my favorite one. This code can be used to change the “End Call / Power”
button action in your phone. Be default, if you long press the button, it shows a
screen asking you to select any option from Silent mode, Airplane mode and Power
off.
67
You can change this action using this code. You can enable direct power off on this
button so you don’t need to waste your time in selecting the option.
6. *#*#197328640#*#*
This code can be used to enter into Service mode. You can run various tests and
change settings in the service mode
8. *#*#8255#*#* => This code can be used to launch GTalk Service Monitor.
11. To get to a File copy screen for backing up your images, videos, voice
memos, and other media files, type in *#*#273283*255*663282*#*#*
12. If you want to change default actions for the End Call and Power button, punch
in *#*#7594#*#* and change those settings.
69
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
70
<ListView
android:layout_height="fill_parent"
android:id="@+id/listView2"
android:layout_width="match_parent"
android:background="@color/red_bg"
android:listSelector="@color/red_bg"
android:cacheColorHint="@color/red_bg"
android:choiceMode="singleChoice"
android:divider="@color/red_bg"
android:dividerHeight="3dip">
</ListView>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Mostly Used:
0000 => android:numColumns=”auto_fit”
0001 => android:verticalSpacing=”5dp”
0010 => android:horizontalSpacing=”10dp”
0011 => android:stretchMode=”columnWidth”
0100 => android:columnWidth=”90dp”
0101 => android:smoothScrollbar=”true”
Rarely Used:
0110 => android:listSelector=”@color/red”
0111 => android:drawSelectorOnTop=”true”
1000 => android:scrollbarStyle=”insideOverlay”
1001 => android:scrollbars=”vertical”
0000. android:numColumns
71
Used to set number of columns we wants inside the GridView. we can also set
“auto_fit” value so that we developer need not to bother about number of columns.
0001. android:verticalSpacing
Used to set spacing between two gridview items vertically.
0010. android:horizontalSpacing
Used to set spacing between two gridview items horizontally.
0011. andorid:stretchMode
Used to control how items are stretched to fill their space.
0100. android:columnWidth
Used to set Width of the Column.
0101. android:smoothScrollbar=”true”
Used to control scrollbar effectively and When set to true, the list will use a more
refined calculation method based on the pixels height of the items visible on screen.
0110. android:listSelector=”@color/red”
Used to define the Selector image/color, selector image/color will be appeared
whenever we focus/pressed on the GridView item.
0111. android:drawSelectorOnTop=”true”
Used to control the selector image/color and When set to true, the selector will be
drawn over the selected item.
1000. android:scrollbarStyle=”insideOverlay”
Used to define the scroll bar position and its style.
1001. android:scrollbars=”vertical”
Used to define scrollbars such as Horizontal, vertical or both.
For example:
01 <GridView
02 android:id="@+id/gridViewImages"
72
03 android:layout_below="@+id/header"
04 android:layout_height="match_parent"
android:layout_width="fill_parent"
05 android:numColumns="auto_fit"
06 android:verticalSpacing="5dp"
07 adroid:horizontalSpacing="10dp"
08 android:smoothScrollbar="true">
09 </GridView>
10
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<WebView android:id="@+id/webview1"
android:layout_above="@+id/btnOk"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"/>
<Button android:text="Ok"
android:id="@+id/btnOk"
android:layout_width="120px"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_centerHorizontal="true"/>
</LinearLayout>
shareimprove this answer
Only thing I changed in my above layout is adding layout-weight="1" and keeping everything else, but it works. Or
should I still change to LinearLayout? – Demonick Jun 13 '11 at 13:45
No. If it works as-is then feel free to stick with it. I'm please that it fixed things for you
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
myDialog.show();
Window window = myDialog.getWindow();
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
its integer parameters of width and height. Simply use something like
window.setLayout(300,300);
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
http://angrytools.com/android/button/
http://hateum.github.io/AndroidDrawableGenerator/
http://android-holo-colors.com/
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
First, get the intent which has started your activity using the getIntent() method:
Intent intent = getIntent();
If your extra data is represented as strings, then you can use intent.getStringExtra(String
name)method. In your case:
String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
You need to pass some parameters into an activity while launching it.
Solution
A quick solution is to use Intent.putExtra() to push our data. And then use
getIntent().getExtras().getString() to retrieve it.
74
Discussion
Push Data
import android.content.Intent;
...
Intent intent =
new Intent(
this,
MyActivity.class );
intent.putExtra( "paramName", "paramValue" );
startActivity( intent );
The above code might be inside the main activity. "MyActivity.class" is the second Activity we want to
launch; it must be explicitly included in your AndroidManifest.xml file.
Pull Data
import android.os.Bundle;
...
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background_common">
<TextView
android:text="Left Text"
75
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"/>
<TextView
android:text="Right Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"/>
</FrameLayout>
Layout_gravity tells the parent where to put the child. In a FrameLayout, children can go anywhere
and are unobstructed by other children. If there is overlap, the last child added is on top. Good luck!
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<style name="AudioFileInfoOverlayText">
<item name="android:paddingLeft">4px</item>
<item name="android:paddingBottom">4px</item>
<item name="android:textColor">#ffffffff</item>
<item name="android:textSize">12sp</item>
<item name="android:shadowColor">#000000</item>
<item name="android:shadowDx">1</item>
<item name="android:shadowDy">1</item>
<item name="android:shadowRadius">1</item>
</style>
And in your layout, use the style like this:
<TextView android:id="@+id/info"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="@style/AudioFileInfoOverlayText"
android:gravity="center" />
Edit: the source code can be viewed here: http://code.google.com/p/ringdroid/
Edit2: To set this style programmatically, you'd do something like this (modified from this
example to match ringdroid's resources from above)
TextView infoTextView = (TextView) findViewById(R.id.info);
infoTextView.setTextAppearance(getApplicationContext(),
R.style.AudioFileInfoOverlayText);
The signature for setTextAppearance is
public void setTextAppearance (Context context, int resid)
76
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Example:
<string name="nice_html">
<![CDATA[
<p>This is a html-formatted string with <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>
]]>
</string>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
For example:
myTextView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
77
Android align textview to right
Actually our code is working but it will be clear if you give width less than parent, try this change
<TextView
android:id="@+id/textview_example"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:gravity="center_vertical|right"
android:textColor="#474747"
android:text="ABAGSADGDBAJDHADNA"
android:textSize="14sp" />
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:id="@+id/mytextview1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:id="@+id/mytextview2"/>
</RelativeLayout>
Also, you should probably be using dip (or dp) rather than sp in your layout. sp reflect text settings
as well as screen density so they're usually only for sizing text items.
78
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
I just encountered a situation very similar to the one you explained. I needed to have an
ImageView on top of the layout, which had to be stretched ONLY HORIZONTALLY and retain
its height when the phone gets into landscape orientation. I succeeded with just this:
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/main_header"
android:scaleType="fitXY"
/>
and, of course, with activity's attribute:
<activity android:configChanges="keyboardHidden|orientation">
Hope this helps. Thank you.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
i would like to have three buttons taking equal amount of available space horizontally in a row. I
used android:layout_gravity. What is the problem?
layout xml :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1.0"
>
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Bg"
android:background="@drawable/button_red"
android:layout_weight=".2"
android:layout_gravity="left"
79
/>
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Bm"
android:background="@drawable/button_red"
android:layout_weight=".2"
android:textColor="#ffffff"
android:layout_gravity="center"
/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_red"
android:layout_weight=".2"
android:text="@string/Bf"
android:layout_gravity="right"
/>
</LinearLayout>
if someone see whats wrong, thanks.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="3"
>
<Button android:id="@+id/button1"
...
android:layout_weight="1"/>
<Button android:id="@+id/button2"
...
android:layout_weight="1"/>
<Button
android:id="@+id/button3"
...
android:layout_weight="1"/>
</LinearLayout>
shareedit
80
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Intent i = getIntent();
stock_list = i.getStringArrayListExtra("stock_list");
The way you have it you've just created a new empty intent without any extras.
If you only have a single extra you can condense this down to:
stock_list = getIntent().getStringArrayListExtra("stock_list");
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
In order to read:
Bundle b=this.getIntent().getExtras();
String[] array=b.getStringArray(key);
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
There has also been some talk on whether they should enforce UTF-8 or not in the future, so
you should start changing to UTF-8 asap :)
Click File -> Settings (or click Ctrl + Alt + S) and find File Encodings in your Androd Studio.
See the image below as a reference.
Now you have three options
81
change UTF-8 to match other encoding
or change project encoding to match UTF-8 since both Gradle and Android Lint use this
(recommended)
Ignore the warning
You can also see the current encoding of your file at the bottom right corner of Android studio.
You can also change it there. See the image below.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
82
I just encountered a situation very similar to the one you explained. I needed to have an
ImageView on top of the layout, which had to be stretched ONLY HORIZONTALLY and retain its
height when the phone gets into landscape orientation. I succeeded with just this:
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/main_header"
android:scaleType="fitXY"
/>
and, of course, with activity's attribute:
<activity android:configChanges="keyboardHidden|orientation">
Hope this helps. Thank you.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Get Assets folder path and read txt file to string Android
example code
// Path for a WebView
String sAssets = "file:///android_asset/" + "index.htm";
WebView mWebView = (WebView)findViewById(R.id.webview1);
mWebView.loadUrl(sAssets);
// Path to Assets folder Context.getAssets
// getContext().getAssets()
// getAssets() - Return an AssetManager instance for your application's
package.
// file to inputstream
InputStream input = getAssets().open("myData.txt");
// myData.txt can't be more than 2 gigs.
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
83
3. Open the DisplayMessageActivity.java file.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Solution 1:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#cc8181"
>
<ImageView
android:id="@+id/image"
android:layout_width="50dip"
android:layout_height="fill_parent"
android:src="@drawable/icon"
android:layout_marginLeft="3dip"
android:scaleType="center"/>
</LinearLayout>
Step 2: create an Activity
Solution 2:
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
84
I have added an image to my Android project which I want to use in the UI. I have added the
file my-image.png to the drawable directory (to all 4 drawable directories created with the
project), and added the ImageView to the layout:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/textView"
android:layout_marginBottom="63dp"
android:src="@drawable/my-image" />
The problem is that I get the following error:
Rendering Problems
ANSWER:
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
85
inherits from View) so you can nest layouts. You could also create your own custom layout by making a class
that inherits from ViewGroup.
AbsoluteLayout
FrameLayout
LinearLayout
RelativeLayout
TableLayout
FrameLayout
FrameLayout is designed to display a single item at a time. You can have multiple elements within a
FrameLayout but each element will be positioned based on the top left of the screen. Elements that overlap will
be displayed overlapping. I have created a simple XML layout using FrameLayout that shows how this works.
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:src="@drawable/icon"
android:scaleType="fitCenter"
android:layout_height="fill_parent"
android:layout_width="fill_parent"/>
<TextView
android:text="Learn-Android.com"
android:textSize="24sp"
android:textColor="#000000"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>
86
You can see I had both the ImageView and TextView fill the parent in both horizontal and vertical layout.
Gravity specifies where the text appears within its container, so I set that to center. If I had not set a gravity
then the text would have appeared at the top left of the screen.
FrameLayout can become more useful when elements are hidden and displayed programmatically. You can
use the attribute android:visibility in the XML to hide specific elements. You can call setVisibility from the code
to accomplish the same thing. The three available visibility values are visible, invisible (does not display, but
still takes up space in the layout), and gone (does not display, and does not take space in the layout).
So you could, for example, have a game in a FrameView where text displayed to the user is visible in the
middle of the screen at appropriate times (e.g. “Game Over”).
LinearLayout
LinearLayout organizes elements along a single line. You specify whether that line is verticle or horizontal
using android:orientation. Here is a sample Layout XML using LinearLayout.
87
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/backbutton"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="Last Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Here is a screenshot of the same XML except that the android:orientation has been changed to horizontal.
88
You might note that the EditText field at the end of the line has had its width reduced in order to fit. Android will
try to make adjustments when necessary to fit items on screen. The last page of this tutorial will cover one
method to help deal with this.
I mentioned on the first page that Layouts can be nested. LinearLayout is frequently nested, with horizontal
and vertical layouts mixed. Here is an example of this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/backbutton"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:text="Last Name"
89
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
As you can see we have a Vertical LinearLayout whose children are a button, and two horizontal
LinearLayouts. Each horizontal LinearLayout has two child controls. You should note that in the child
LinearLayout elements I used android:layout_height=”wrap_content” instead of fill_parent. If I had used
fill_parent the first name TextView and EditView would have taken all of the available space on the screen, and
the Last Name would not have been displayed. Here is what this XML does display.
Nested Layouts do not have to be of one type. I could, for example, have a LinearLayout as one of the children
in a FrameLayout.
RelativeLayout
RelativeLayout lays out elements based on their relationships with one another, and with the parent container.
This is arguably the most complicated layout, and we need several properties to actually get the layout we
want.
Relative To Container
These properties will layout elements relative to the parent container.
90
android:layout_alignParentBottom – Places the bottom of the element on the bottom of the container
android:layout_alignParentLeft – Places the left of the element on the left side of the container
android:layout_alignParentRight – Places the right of the element on the right side of the container
android:layout_alignParentTop – Places the element at the top of the container
android:layout_centerHorizontal – Centers the element horizontally within its parent container
android:layout_centerInParent – Centers the element both horizontally and vertically within its
container
android:layout_centerVertical – Centers the element vertically within its parent container
android:layout_alignBaseline – Aligns baseline of the new element with the baseline of the specified
element
android:layout_alignBottom – Aligns the bottom of new element in with the bottom of the specified
element
android:layout_alignLeft – Aligns left edge of the new element with the left edge of the specified
element
android:layout_alignRight – Aligns right edge of the new element with the right edge of the specified
element
android:layout_alignTop – Places top of the new element in alignment with the top of the specified
element
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
91
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/backbutton"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/firstName"
android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/backbutton" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/firstName"
android:layout_alignBaseline="@id/firstName" />
<TextView
android:id="@+id/lastName"
android:text="Last Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/firstName" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/lastName"
android:layout_alignBaseline="@id/lastName" />
</RelativeLayout>
92
I wanted to show this to you because the first time I made a RelativeLayout I did exactly this and then looked
at the screen and said, “Hang on a minute, that’s not what I wanted!” The problem here is that when Android
draws the TextView lastName below the TextView firstName it only sets aside the space it needs for the
TextView. Android only reads the Layout XML one time so it doesn’t know that an EditView is the next item
and doesn’t plan for it. So when the EditView is drawn to the right of the TextView it only has the height of the
TextView to work with so it overlaps the EditView above it. Here is the Layout XML I wrote to create the form
the way it should look.
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/backbutton"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/firstName"
android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/backbutton" />
<EditText
android:id="@+id/editFirstName"
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/firstName"
android:layout_below="@id/backbutton"/>
<EditText
android:id="@+id/editLastName"
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editFirstName"
android:layout_alignLeft="@id/editFirstName"/>
<TextView
android:id="@+id/lastName"
android:text="Last Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/editLastName"
android:layout_below="@id/editFirstName" />
</RelativeLayout>
You probably noticed that I had to rearrange the elements in the XML since, as I already mentioned, you
cannot reference an element that has not already been laid out. Here is what the updated RelativeLayout
produces.
93
TableLayout
TableLayout organizes content into rows and columns. The rows are defined in the layout XML, and the
columns are determined automatically by Android. This is done by creating at least one column for each
element. So, for example, if you had a row with two elements and a row with five elements then you would
have a layout with two rows and five columns.
You can specify that an element should occupy more than one column using android:layout_span. This can
increase the total column count as well, so if we have a row with two elements and each element has
android:layout_span=”3″ then you will have at least six columns in your table.
By default, Android places each element in the first unused column in the row. You can, however, specify the
column an element should occupy using android:layout_column.
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TableRow>
<Button
android:id="@+id/backbutton"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView
94
android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView
android:text="Last Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
95
2. in
Inches - based on the physical size of the screen.
1 Inch = 2.54 centimeters
3. mm
Millimeters - based on the physical size of the screen.
4. pt
Points - 1/72 of an inch based on the physical size of the screen.
5. dp or dip
Density-independent Pixels - an abstract unit that is based on the physical density of the
screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen.
The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct
proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent
with "sp".
6. sp
Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size
preference. It is recommend you use this unit when specifying font sizes, so they will be
adjusted for both the screen density and user's preference.
+----------------+----------------+---------------+------------------------------
-+
| Density Bucket | Screen Density | Physical Size | Pixel Size
|
+----------------+----------------+---------------+------------------------------
-+
| ldpi | 120 dpi | 0.5 x 0.5 in | 0.5 in * 120 dpi = 60x60 px
|
+----------------+----------------+---------------+------------------------------
-+
| mdpi | 160 dpi | 0.5 x 0.5 in | 0.5 in * 160 dpi = 80x80 px
|
+----------------+----------------+---------------+------------------------------
-+
| hdpi | 240 dpi | 0.5 x 0.5 in | 0.5 in * 240 dpi = 120x120 px
|
+----------------+----------------+---------------+------------------------------
-+
| xhdpi | 320 dpi | 0.5 x 0.5 in | 0.5 in * 320 dpi = 160x160 px
|
+----------------+----------------+---------------+------------------------------
-+
| xxhdpi | 480 dpi | 0.5 x 0.5 in | 0.5 in * 480 dpi = 240x240 px
|
+----------------+----------------+---------------+------------------------------
-+
| xxxhdpi | 640 dpi | 0.5 x 0.5 in | 0.5 in * 640 dpi = 320x320 px
|
+----------------+----------------+---------------+------------------------------
-+
+---------+-------------+---------------+-------------+--------------------+
| Unit | Description | Units Per | Density | Same Physical Size |
| | | Physical Inch | Independent | On Every Screen |
96
+---------+-------------+---------------+-------------+--------------------+
| px | Pixels | Varies | No | No |
+---------+-------------+---------------+-------------+--------------------+
| in | Inches | 1 | Yes | Yes |
+---------+-------------+---------------+-------------+--------------------+
| mm | Millimeters | 25.4 | Yes | Yes |
+---------+-------------+---------------+-------------+--------------------+
| pt | Points | 72 | Yes | Yes |
+---------+-------------+---------------+-------------+--------------------+
| dp | Density | ~160 | Yes | No |
| | Independent | | | |
| | Pixels | | | |
+---------+-------------+---------------+-------------+--------------------+
| sp | Scale | ~160 | Yes | No |
| | Independent | | | |
| | Pixels | | | |
+---------+-------------+---------------+-------------+--------------------+
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Android - Fragments
A Fragment is a piece of an activity which enable more modular activity design. It
will not be wrong if we say, a fragment is a kind ofsub-activity.
A fragment has its own layout and its own behaviour with its own life cycle callbacks.
You can add or remove fragments in an activity while the activity is running.
You can combine multiple fragments in a single activity to build a multi-plane UI.
Fragment life cycle is closely related to the life cycle of its host activity which means
when the activity is paused, all the fragments available in the activity will also be
stopped.
Fragments were added to the Android API in Honeycomb version of Android which
API version 11.
97
You create fragments by extending Fragment class and You can insert a
fragment into your activity layout by declaring the fragment in the
activity's layout file, as a <fragment> element.
98
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
https://www.youtube.com/watch?v=Qb2olFyoMV4 - good
youtube for adding any physical device to android studio
Some Android mobile are hidden the developer options. I you want to
invoke the developer options. Go to settings in the phone and select
about phone. In the about phone there is a builder number. You juse
press 7 times on Build Number, now the developer option is unhided
from the Phone/
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
http://programmerguru.com/android-tutorial/how-to-create-android-app-with-movable-to-sd-
card-feature/# - this also good website for android
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
99
Difference between ArrayAdapter and ListAdapter in
Android?
This is not related to Android. But a general Java question.
When you use ListAdapter as the type for your variable, you are really interested in the
interface. You may not be interested in calling some specific method
of ArrayAdapter<String> not available in ListAdapter. That is mainly because you will just assign
the adapter as the list adapter for the view.
You may use the precise type of ArrayAdapter<String> if you really need to call some specific
methods.
It all depends on your use case.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
import java.util.*;
100
/*This is how elements should be added to the array list*/
obj.add("Ajeet");
obj.add("Harry");
obj.add("Chaitanya");
obj.add("Steve");
obj.add("Anuj");
Currently the array list has following elements:[Ajeet, Harry, Chaitanya, Steve, Anuj]
Current array list is:[Rahul, Justin, Ajeet, Steve, Anuj]
Current array list is:[Rahul, Ajeet, Steve, Anuj]
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
101
2. On the next screen just click Finish.
102
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Fragment
A Fragment is a piece of an activity which enable more modular activity design. It will not be wrong if we say,
a fragment is a kind of sub-activity.
A fragment has its own layout and its own behaviour with its own life cycle callbacks.
You can add or remove fragments in an activity while the activity is running.
You can combine multiple fragments in a single activity to build a multi-plane UI.
A fragment can be used in multiple activities.
Fragment life cycle is closely related to the life cycle of its host activity which means when
the activity is paused, all the fragments available in the activity will also be stopped.
A fragment can implement a behaviour that has no user interface component.
Fragments were added to the Android API in Honeycomb version of Android which API
version 11.
You create fragments by extending Fragment class and You can insert a fragment into your activity
layout by declaring the fragment in the activity's layout file, as a <fragment> element.
Prior to fragment introduction, we had a limitation because we can show only a single activity on the
screen at one given point in time. So we were not able to divide device screen and control different
parts separately. But with the introduction of fragment we got more flexibility and removed the
limitation of having a single activity on the screen at a time. Now we can have a single activity but
each activity can comprise of multiple fragments which will have their own layout, events and
complete life cycle.
Following is a typical example of how two UI modules defined by fragments can be combined into
one activity for a tablet design, but separated for a handset design.
103
The application can embed two fragments in Activity A, when running on a tablet-sized device.
However, on a handset-sized screen, there's not enough room for both fragments, so Activity A
includes only the fragment for the list of articles, and when the user selects an article, it starts Activity
B, which includes the second fragment to read the article.
Android fragments have their own life cycle very similar to an android activity. This section briefs
different stages of its life cycle.
104
Fragment lifecycle
Here is the list of methods which you can to override in your fragment class −
onAttach()The fragment instance is associated with an activity instance.The fragment and the
activity is not fully initialized. Typically you get in this method a reference to the activity
which uses the fragment for further initialization work.
onCreate() The system calls this method when creating the fragment. You should initialize
essential components of the fragment that you want to retain when the fragment is paused or
stopped, then resumed.
onCreateView() The system calls this callback when it's time for the fragment to draw its
user interface for the first time. To draw a UI for your fragment, you must return a View
component from this method that is the root of your fragment's layout. You can return null if
the fragment does not provide a UI.
onActivityCreated()The onActivityCreated() is called after the onCreateView() method when
the host activity is created. Activity and fragment instance have been created as well as the
view hierarchy of the activity. At this point, view can be accessed with the findViewById()
method. example. In this method you can instantiate objects which require a Context object
onStart()The onStart() method is called once the fragment gets visible.
onResume()Fragment becomes active.
onPause() The system calls this method as the first indication that the user is leaving the
fragment. This is usually where you should commit any changes that should be persisted
beyond the current user session.
onStop()Fragment going to be stopped by calling onStop()
onDestroyView()Fragment view will destroy after call this method
onDestroy()onDestroy() called to do final clean up of the fragment's state but Not guaranteed
to be called by the Android platform.
First of all decide how many fragments you want to use in an activity. For example let's we
want to use two fragments to handle landscape and portrait modes of the device.
Next based on number of fragments, create classes which will extend the Fragment class. The
Fragment class has above mentioned callback functions. You can override any of the
functions based on your requirements.
Corresponding to each fragment, you will need to create layout files in XML file. These files
will have layout for the defined fragments.
Finally modify activity file to define the actual logic of replacing fragments based on your
requirement.
Types of Fragments
105
Single frame fragments − Single frame fragments are using for hand hold devices like
mobiles, here we can show only one fragment as a view.
List fragments − fragments having special list view is called as list fragment
Fragments transaction − Using with fragment transaction. we can move one fragment to
another fragment.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
TextWatcher
A Text Watcher is really helpful for scenarios like login/register screen validation. As an when user is
entering the data, you can keep an eye on user input and notify early instead of waiting till user press
submit button manually. Another great realtime example is Google search; it shows user the realtime
search suggestion while user entering data.
Implementing Text watcher is quite easy, you have to call addTextChangedListener() method and
pass the reference to TextWatcher instance. You can override the following TextWatcher
class method to take various actions, when the content of EditText changes.
For Ex. We can use TextWatcher to have checks on the password field that minimum number of characters
are entered or not, or We can check the password Strength depending on number of characters entered in
Password field .
TextWatcher class has 3 methods and we need override these methods to implement our own functionality.
106
2: public abstract void beforeTextChanged (CharSequence s, int start, int count, int after)
This method is called to notify you that, within s, the count characters beginning at start are about to be
replaced by new text with length after. It is an error to attempt to make changes to s from this callback.
3: public abstract void onTextChanged (CharSequence s, int start, int before, int count)
This method is called to notify you that, within s, the count characters beginning at start have just
replaced old text that had length before. It is an error to attempt to make changes to s from this callback.
TextWatcher Example
In this post I have given an Example in which we have a password field of type EditText , in which user
will enter his password and we will show strength of password according to the number of characters
entered by the user, we also show that maximum characters has been is entered when user enter 20
characters.
EditText editTextPassword;
TextView textViewPasswordStrengthIndiactor;
inside onCreate()
editTextPassword.addTextChangedListener(mTextEditorWatcher);
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
107
cv.put("Field1","Bob"); //These Fields should be your String values of actual column
names
cv.put("Field2","19");
cv.put("Field2","Male");
Then use the update method, it should work now:
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
myWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Sample:
this.mWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
});
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
108
WebView wv;
public Calendar() {
this.language = "";
}
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
So basically, what you have to do is a big string of JavaScript code that will get those fields and put
values on them; also, you can enable/disable the submit button from JavaScript.
You should update your app so that when running on API 19 or above, it uses evaluateJavaScript, and
falls back to loadUrl when running on older devices. Something like:
109
if (android.os.Build.Version.SDK_INT >= 19) {
webview.evaluateJavaScript("...", null);
} else {
webview.loadUrl("javascript:...");
}
You'll need to use a WebViewClient, and wait for the page to finish loading before you execute your
javascript. Try the onPageFinished callback, but be careful that you can sometimes get multiple
callbacks because of iFrames and the like.
1. You should call setWebViewClient with your WebViewClient implementation before you
call loadUrl. However, loadUrl is asynchronous, so it probably would not make a
difference, but this is worth a try I think.
2. You are not calling super.onPageFinished(view, url); in onPageFinshed. You should
add this call.
EDIT 2:
I finally took a look at the actual page you are working with. The problem is that the page loads
content in a different frame, so you actually have to make the getElementsByName call on a different
document. The frame in which both of the inputs you want are located has the name mainFrame in
your page. So, you should write the javascript like this and load that into the WebView as you have
done above:
window.frames["mainFrame"].document.
getElementsByName('p_codigo_c')[0].value = "user";
window.frames["mainFrame"].document.
getElementsByName('p_clave_c')[0].value = "password";
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
110
Color
#9c6b4d #cb4000
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
http://www.appiconsizes.com/
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
1 Genymotion
Anyone who is familiar with the default Android Emulator will know that starting the emulator and
running an app can be an extremely slow and tedious process. Genymotion solves this problem by
providing a free (for personal uses) hardware accelerated Android emulator which is screaming fast.
111
Genymotion virtual devices support various Android API levels and work seamlessly with Android
Studio. Download it ASAP, it will save you a lot of time.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Android Button Maker is online tool to generate buttons code for Android Apps. Android API
provide Drawable Resources where XML file defines geometric shape, including colors, border and
gradients.
These button is generating based on shape drawable XML code which load faster compare to normal
png buttons. You can customize button properties in setting panel and get source code.
http://angrytools.com/android/button/
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
http://www.technotalkative.com/lazy-android-part-7-useful-tools/ -
<<<<<<<<<<<<<<< <<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
112
Android Layout Finder | Buzzing Android
https://www.buzzingandroid.com/tools/android-layout-finder/ - this is a very good site
get the android code.
If you paste your layout xml file in the above site, if finds the controls and their
variables then generate the java code for initializing the controls .
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
113
How to Apply Shadow Effect on Android
TextView
This example explains how to apply Shadow Effect on Android TextView. You can apply Shadow
Effect on Android TextView in two ways. Either we do it pragmatically or we can change in the xml
layout.
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:shadowColor="#000"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="50"
android:text="Text Shadow Example1"
android:textColor="#FBFBFB"
android:textSize="28dp"
android:textStyle="bold" />
<TextView
android:id="@+id/textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Text Shadow Example2"
android:textColor="#FBFBFB"
android:textSize="28dp"
android:textStyle="bold" />
</LinearLayout>
In the above XML layout code, the textview1 is given with Shadow effect in the layout. below are the
configuration items are
android:shadowDx – specifies the X-axis offset of shadow. You can give -/+ values, where -Dx draws a
shadow on the left of text and +Dx on the right
android:shadowDy – it specifies the Y-axis offset of shadow. -Dy specifies a shadow above the text
and +Dy specifies below the text.
android:shadowRadius – specifies how much the shadow should be blurred at the edges. Provide a
small value if shadow needs to be prominent.
android:shadowColor – specifies the shadow color
114
Shadow Effect on Android TextView pragmatically
Use below code snippet to get the shadow effect on the second TextView pragmatically.
Output
<<<<<< <<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
115
Android make activity as Fullscreen (Removing Title Bar or Action Bar)
If want to make an activity to fullscreen in some cases like playing video in fullscreen mode, playing
game etc., you can do that by following one of the methods.
Method 1
<activity android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.Holo.Light.NoActionBar.Fullscreen">
</activity>
Method 1
Another way is, do this through code in the activity. In your activity do the following before calling
setContentView() function
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
I declared a style inheriting everything from my general style and then disabling the titleBar.
Now I can set this style to every Activity in which I want to hide the title bar overwriting the a
pplication wide style and inheriting all the other style informations, therefor no duplication in the
116
style code.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
A: Ifnothing
you don't see a drawable folder for the DPI that you need, you can create it yourself. There's
magical about it; it's just a folder which needs to have the correct name.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
http://angrytools.com/ -
this is a good website for CSS gradian generator, Android b
utton maker CSS generator
117
mipmap vs drawable folders [duplicate]
The mipmap folders are for placing your app icons in only. Any other drawable assets you use should
be placed in the relevant drawable folders as before.
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they
are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
You may then define the icon in your AndroidManifest.xml file as such:
<application android:icon="@drawable/icon_name"
android:label="@string/app_name" >
....
</application>
118
Sqlite database
119
How to display Toast in Android?
Toast.makeText(getApplicationContext(), (String)data.result,
Toast.LENGTH_LONG).show();
other example...
int LENGTH_LONG Show the view or text notification for a long period of time.
int LENGTH_SHORT Show the view or text notification for a short period of time.
LayoutInflater myInflater=LayoutInflater.from(this);
View view=myInflater.inflate(R.layout.your_custom_layout,null);
Toast mytoast=new Toast(this);
mytoast.setView(view);
mytoast.setDuration(Toast.LENGTH_LONG);
mytoast.show();
/data/data/the.app.package.name/databases/the_name_of_db
And no, you cannot access that file in a non-rooted phone. Fortunately the emulator is rooted.
120
ote ac cepted Cyrillic comments. In Android Studio which is based on IntelliJ IDEA you can solve it
in two ways:
android {
...
compileOptions.encoding = 'windows-1251' // write your encoding
here
...
To convert file encoding use the menu at the bottom right corner of IDE. Select right
file encoding first -> press Reload -> select UTF-8 -> press Convert.
Also read this Use the UTF-8, Luke! File Encodings in IntelliJ IDEA
would this add the string value to my arraylist and save it for later use?
For example If I click three different buttons this will add three different className values to the
arraylist. Would this then store a string value that would hold three different string values for my
members arraylist?
If you tell to your button's onClickListener to add a string to the members ArrayList then it will be
done and no matter if you already had previously added that member to the ArrayList because array
lists don't care if there is duplicated data or not.
How would I check each item in my arraylist to see if the values are being added when a new activity
is started?
You have to iterate your array list with a for or a for-each cicle and then print that member name as a
log entry.
For-each cicle
F or (String member : members){
Log.i("Member name: ", member);
121
}
If you try to print/ log a value which index is out of range, i.e., i < 0 || i >= listSize then a
IndexOutOfBoundsException will be thrown and crash your app.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
http://blog.softeq.com/2012/12/using-pre-populated-
sqlite-database-in.html - good tutorial for SQLite datab ase
handling
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
A ListAdapter that manages a ListView backed by an array of arbitrary objects. By default this class
expects that the provided resource id references a single TextView. If you want to use a more
complex layout, use the constructors that also takes a field id. That field id should reference a
TextView in the larger layout resource. However the TextView is referenced, it will be filled with the
toString() of each object in the array. You can add lists or arrays of custom objects. Override the
toString() method of your objects to determine what text will be displayed for the item in the list. To
use something other than TextViews for the array display, for instance, ImageViews, or to have some
of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the
type of view you want.
122
lv = (ListView) findViewById(R.id.your_list_view_id);
lv.setAdapter(arrayAdapter);
}
}
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Java Program
1 import java.util.ArrayList;
import java.util.Collections;
2 import java.util.Enumeration;
3 import java.util.Iterator;
4 import java.util.List;
5
6 public class ArrayListDemo
7 {
8
public static void main(String args[])
9 {
10 List list = new ArrayList();
123
11
12 //Adding values to the ArrayList
13 list.add("test1");
list.add("test2");
14 list.add("test3");
15
16 System.out.println("Retrieving values from ArrayList using Iterator");
17 retrieveValuesFromListMethod1(list);
18 System.out.println("**********************\n\n");
19
20 System.out.println("Retrieving values from ArrayList using get
method");
21
retrieveValuesFromListMethod2(list);
22 System.out.println("**********************\n\n");
23
24 System.out.println("Retrieving values from ArrayList using
25Enumeration");
26 retrieveValuesFromListMethod3(list);
27 System.out.println("**********************\n\n");
}
28
29
30 /*This method retrieves values from ArrayList using Iterator
31 */
32 public static void retrieveValuesFromListMethod1(List list)
33 {
34 Iterator itr = list.iterator();
while(itr.hasNext())
35
{
36 System.out.println(itr.next());
37 }
38 }
39
40 /*This method retrieves values from ArrayList using get method
41 */
public static void retrieveValuesFromListMethod2(List list)
42 {
43 //Retrieving values from list
44 int size = list.size();
45 for(int i=0;i<size;i++)
46 {
System.out.println(list.get(i));
47 }
48 }
49
50
51 /*This method retrieves values from ArrayList using Enumeration
52 */
53 public static void retrieveValuesFromListMethod3(List list)
{
54
Enumeration e = Collections.enumeration(list);
55 while(e.hasMoreElements())
56 {
57 System.out.println(e.nextElement());
58 }
124
59
60 }
61
62}
63
64
65
66
67
68
69
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
125
Center a button in a Linear layout
If you want to center an item in the middle of the screen don't use a LinearLayout as these are
meant for displaying a number of items in a row.
Use a RelativeLayout instead.
So replace:
android:layout_gravity="center_vertical|center_horizontal"
for the relevant RelativeLayout option:
android:layout_centerInParent="true"
So your layout file will look like this:
<ImageButton android:id="@+id/btnFindMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/findme"></ImageButton>
</RelativeLayout>
????????????????????????????????????????????????????????????????????
Set button's parent linear layout gravity to center
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:color/white"
android:orientation="horizontal"
android:gravity="center">
<Button
android:id="@+id/okbutton"
android:layout_width="wrap_content"
android:layout_height="300dp"
android:text="SET"
android:gravity="center"
android:textSize="50sp" />
</LinearLayout>
126