

<!-- res/values/styles.xml -->
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
<!-- Customize your theme here. -->
</style>
</resources>
<!-- AndroidManifest.xml -->
<application ... android:theme="@style/AppTheme">ActionBar actionBar;
if (Build.VERSION.SDK_INT >= 11) {
actionBar = getActionBar();
} else {
actionBar = getSupportAction();
}
actionBar.hide();
actionBar.show();onCreateOptionsMenu() de la classe Activity est appelée pour initialiser la barre d'action
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the
// action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(
R.menu.main_activity_actions,
menu
);
return super.onCreateOptionsMenu(menu);
}<!-- res/menu/main_activity_actions.xml -->
<menu
xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_compose"
android:icon="@drawable/ic_action_compose"
android:title="@string/action_compose"
android:showAsAction="ifRoom|withText"/>
<item
android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:title="@string/action_search"
showAsAction="never"/>
</menu>Activité
Définition XML du menu
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_compose:
composeMessage();
return true;
case R.id.action_search:
openSearch();
return true;
default:
return super.onOptionsItemSelected(item);
}
}<!-- The main/home activity (has no parent activity) -->
<activity
android:name="com.example.app.MainActivity"
... >
...
</activity>
<!-- A child of the main activity -->
<activity
android:name="com.example.app.DisplayMessageActivity"
android:label="@string/title_activity_display_message"
android:parentActivityName="com.example.app.MainActivity">
<!-- Parent activity meta-data to support API level 7+ -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.app.MainActivity" />
</activity>AndroidManifest.xml
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}DisplayMessageActivity.java




FragmentTransaction T = getFragmentManager()
.beginTransaction();
ExampleFragment F = new ExampleFragment();
T.add(R.id.example_container, F);
T.commit();<LinearLayout
xmlns:android="..."
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:name="com.example.ExampleFragment"
android:id="@+id/example_container"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>Définition dans le code
Définition XML dans un layout
public static class FragmentA extends ListFragment {
// Container Activity must implement this interface
public interface OnArticleSelectedListener {
public void onArticleSelected(Uri articleUri);
}
private OnArticleSelectedListener mListener;
// ...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activity containing this fragment must
// implement its callbacks
if (!(activity instanceof OnArticleSelectedListener)) {
throw new ClassCastException ("Activity must "
+"implement fragment's callbacks.");
}
// will be used to share events with activity
// by calling callbacks
mListener = (OnArticleSelectedListener) activity;
}
@Override
public void onListItemClick
(ListView l, View v, int position, long id) {
// Append the clicked item's row ID
// with the content provider Uri
Uri noteUri = ContentUris.withAppendedId
(ArticleColumns.CONTENT_URI, id);
// Send the event and Uri to the host activity
mListener.onArticleSelected(noteUri);
}
// ...
}
public class ArticleActivity extends Activity
implements FragmentA.OnArticleSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article);
}
@Override
public void onItemSelected(String id) {
// Show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(ArticleColumns.CONTENT_URL, id);
FragmentB fragment = new FragmentB();
fragment.setArguments(arguments);
getFragmentManager()
.beginTransaction()
.replace(
R.id.article_detail_container,
fragment
)
.commit();
}
// ...
}ArticleActivity.java
FragmentA.java
| Répertoire | Type |
|---|---|
| res/animator | Descriptions d'animations au format XML |
| res/color | Couleurs utilisées en fonction de l'état d'un widget |
| res/drawable | Images matricielles (GIF, JPEG, PNG) ou descriptions au format XML |
| res/layout | Descriptions de parties de l'interface graphique au format XML |
| res/menu | Descriptions de menus de l'application au format XML |
| res/raw | Fichiers de données brutes (musiques, pages HTML, etc) |
| res/values | Différentes variables définies en XML (chaînes, booléens, dimensions, styles, ...) |
| res/xml | Divers fichiers XML utilisées par l'application |
Permet d'appliquer une couleur à un widget en fonction de son état
<elector xmlns:android="...">
<!-- pressed -->
<item android:state_pressed="true"
android:color="#ffff0000"/>
<!-- focused -->
<item android:state_focused="true"
android:color="#ff0000ff"/>
<!-- default -->
<item android:color="#ff000000"/>
</selector><Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/button_text"
android:textColor="@color/button_text" />res/color/button_text.xml
Dans un fichier de layout XML
Android supporte de nombreux types d'images. Ici nous nous intéressons aux images Bitmap
Resources res = getResources();
Drawable drawable =
res.getDrawable(R.drawable.filename);<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/filename" />Java
XML
Différents types de menus peuvent être définis en XML et transformés en Java avec un MenuInflater
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.example_menu, menu);
return true;
}
public void onGroupItemClick(MenuItem item) {
// One of the group items was clicked
// The item parameter passed here
// indicates which item it is
// All other menu item clicks are
// handled by onOptionsItemSelected()
}
public void onOptionsItemSelected(MenuItem item) {
// TODO
}<menu xmlns:android="...">
<group android:id="@+id/group">
<item android:id="@+id/group_item1"
android:onClick="onGroupItemClick"
android:title="@string/group_item1"
android:icon="@drawable/group_item1_icon" />
<item android:id="@+id/group_item2"
android:onClick="onGroupItemClick"
android:title="@string/group_item2"
android:icon="@drawable/group_item2_icon" />
</group>
<item android:id="@+id/submenu"
android:title="@string/submenu_title"
android:showAsAction="ifRoom|withText" >
<menu>
<item android:id="@+id/submenu_item1"
android:title="@string/submenu_item1" />
</menu>
</item>
</menu>Code Java
res/menu/example_menu.xml
Android préconise la déclaration de chaînes de caractères dans des fichiers XML.
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" /><?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello!</string>
</resources>Dans un fichier de layout XML
res/values/strings.xml
Android supporte des tableaux et des mots pluriels
Un style définit le "look" de l'interface graphique. Il peut s'appliquer à l'application, une activité ou un widget
<?xml version="1.0" encoding="utf-8"?>
<EditText
style="@style/CustomText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello, World!" /><?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomText" parent="@style/Text">
<item name="android:textSize">20sp</item>
<item name="android:textColor">#008</item>
</style>
</resources>Dans un fichier de layout XML
res/values/styles.xml


<resources>
<!-- Etendre le thème Material ou l'une de ses extensions -->
<style name="AppTheme" parent="android:Theme.Material">
<!-- Personnalisations du thème -->
</style>
</resources><!-- Couleur de l'ActionBar -->
<item name="android:colorPrimary">@color/primary</item>
<!-- Couleur de la StatusBar -->
<item name="android:colorPrimaryDark">@color/primary_dark</item>
<!-- Couleur des éléments de formulaire (zones de texte, checkboxes, ...)-->
<item name="android:colorAccent">@color/accent</item>
public class MyActivity extends Activity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mAdapter = new MyAdapter(myDataset);
mRecyclerView.setAdapter(mAdapter);
}
// ...
}
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto">
<!-- A CardView that contains a TextView -->
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_gravity="center"
android:layout_width="200dp"
android:layout_height="200dp"
card_view:cardCornerRadius="4dp">
<TextView
android:id="@+id/info_text"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v7.widget.CardView>
</LinearLayout><style name="Theme.MyTheme" parent="Theme.AppCompat.Light">
<!-- customize the color palette -->
<item name="colorPrimary">@color/material_blue_500</item>
<item name="colorPrimaryDark">@color/material_blue_700</item>
<item name="colorAccent">@color/material_green_A200</item>
</style>dependencies {
compile 'com.android.support:appcompat-v7:21.0.+'
compile 'com.android.support:cardview-v7:21.0.+'
compile 'com.android.support:recyclerview-v7:21.0.+'
}if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Call some material design APIs here
} else {
// Implement this feature without material design
}<!-- added in AndroidManifest.xml -->
<uses-permission android:name="android.permission.INTERNET" /><WebView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.example.com");myWebView.loadData("<html><body><h1>Hello world!</h1></body></html>",
"text/html", "UTF-8");myWebView.setWebViewClient(new WebViewClient());myWebView.getSettings().setJavascriptEnabled(true);public class WebViewActivity extends Activity {
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.example.com")) { // This is my web site, so do not override,
return false; // let my WebView load the page
}
URLs Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); // Otherwise, the link is not
startActivity(intent); // for a page on my site, so launch
return true; // another Activity that handles
}
}
private class WebAppInterface { // Exemple de code d’une page web
Context mContext; // utilisant l’interface associée :
public WebAppInterface(Context c) { // <script type="text/javascript">
mContext = c; // function showAndroidToast(toast) {
} // Android.showToast(toast);
@JavascriptInterface // }
public void showToast(String toast) { // </script>
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); // <input type="button"
} // onClick="showAndroidToast('Hello Android!')"
} // value="Say hello" />
private WebView myWebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webpage);
myWebView = (WebView) findViewById(R.id.webview);
myWebView.getSettings().setJavascriptEnabled(true);
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.setWebChromeClient(new WebChromeClient() {
public boolean onConsoleMessage(ConsoleMessage cm) {
Log.d("MyApplication", cm.message()
+" -- From line "+ cm.lineNumber() +" of "+ cm.sourceId());
return true;
}
});
myWebView.addJavascriptInterface (new WebAppInterface(this), "Android");
myWebView.loadUrl("http://www.example.com");
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if keyCode is the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event); // bubble up to the default system behavior
}
}