diff options
author | Philip Milne <pmilne@google.com> | 2014-09-25 00:23:14 +0000 |
---|---|---|
committer | Gerrit Code Review <noreply-gerritcodereview@google.com> | 2014-09-25 00:23:15 +0000 |
commit | 03fd7a2ea00cb9a35ac4bdef2937af362a416c8c (patch) | |
tree | f0e6f4dec6e7cf3398525e090c95322c3e7eab88 | |
parent | 205391af6aaacad911c6ffbe9e48777dbcdd4707 (diff) | |
parent | 9938c2ed4fae779647bc962cc1acdc830ce5e5d7 (diff) | |
download | idea133.tar.gz |
Merge "Add tests for Navigation Editor's pattern matching infrastructure (IIII)" into idea133idea133
26 files changed, 787 insertions, 228 deletions
diff --git a/android/resources/navigationTemplates/AccessTemplates.java.template b/android/resources/navigationTemplates/AccessTemplates.java.template deleted file mode 100644 index 43fb934e2c3..00000000000 --- a/android/resources/navigationTemplates/AccessTemplates.java.template +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2013 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.templates; - -import android.view.Menu; - -public class MenuAccessTemplates { - public static void getMenuItem(Menu $menu, int $id) { - $menu.findItem($id); - } -} diff --git a/android/resources/navigationTemplates/GeneralTemplates.java.template b/android/resources/navigationTemplates/GeneralTemplates.java.template deleted file mode 100644 index 6343058f7da..00000000000 --- a/android/resources/navigationTemplates/GeneralTemplates.java.template +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2013 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.templates; - -public class GeneralTemplates { - private static interface UnaryMethodCall { - Object $method(Object o); - } - private static class $Type {} - private static interface $Interface {} - private static void getFragment(String fragmentName, Object controller) {} - - public static void call(UnaryMethodCall $target, Void $method, Object $argument) { - $target.$method($argument); - } - - public static void defineAssignment(String $fragmentName, Void $messageController) { - getFragment($fragmentName, $messageController); - } - - public static void defineInnerClass(Class $Interface, Void $method, Class $Type, Object $arg, final Statement $f) { - new $Interface() { - public void $method($Type $arg) { - $f.$(); - } - }; - } - - - -} diff --git a/android/resources/navigationTemplates/InstallListenerTemplates.java.template b/android/resources/navigationTemplates/InstallListenerTemplates.java.template deleted file mode 100644 index f0ab4beb13e..00000000000 --- a/android/resources/navigationTemplates/InstallListenerTemplates.java.template +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2013 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.templates; - -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.widget.AdapterView; -import android.widget.ListView; - -public class InstallListenerTemplates { - - public static void installClickListener(View $view, Statement $f) { - $view.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - $f.$(); - } - }); - } - - public static void installItemClickListener(ListView $listView, final Statement $f) { - $listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView<?> parent, View view, int position, long id) { - $f.$$(); - } - }); - } - - public static void installMenuItemClick(MenuItem $menuItem, final Statement $f, final boolean $consume) { - $menuItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { - @Override - public boolean onMenuItemClick(MenuItem menuItem) { - $f.$(); - return $consume; - } - }); - } - - public static void installMenuItemClick(Menu $menu, int $menuItemId, final Statement $f, final boolean $consume) { - installMenuItemClick($menu.findItem($menuItemId), $f, $consume); - } -} diff --git a/android/resources/navigationTemplates/LaunchActivityTemplates.java.template b/android/resources/navigationTemplates/LaunchActivityTemplates.java.template deleted file mode 100644 index 986d4656650..00000000000 --- a/android/resources/navigationTemplates/LaunchActivityTemplates.java.template +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2013 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.templates; - -import android.content.Context; -import android.content.Intent; - -import java.io.Serializable; - -// Add "extends Serializable" so that the putExtra() call below can be resolved. - -public class LaunchActivityTemplates { - public static void launchActivity(Context context, Class activityClass) { - context.startActivity(new Intent(context, activityClass)); - } - - public static <T extends Serializable> void launchActivity(Context context, Class activityClass, String name, T value) { - context.startActivity(new Intent(context, activityClass).putExtra(name, value)); - } - -} diff --git a/android/resources/navigationTemplates/Statement.java.template b/android/resources/navigationTemplates/Statement.java.template deleted file mode 100644 index 39707b1e31b..00000000000 --- a/android/resources/navigationTemplates/Statement.java.template +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (C) 2013 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.android.templates; - -public interface Statement { - Object $(); -} diff --git a/android/src/com/android/tools/idea/actions/AndroidShowNavigationEditor.java b/android/src/com/android/tools/idea/actions/AndroidShowNavigationEditor.java index 4279ecff0e1..9c45559c5c2 100644 --- a/android/src/com/android/tools/idea/actions/AndroidShowNavigationEditor.java +++ b/android/src/com/android/tools/idea/actions/AndroidShowNavigationEditor.java @@ -17,32 +17,21 @@ package com.android.tools.idea.actions; import com.android.tools.idea.editors.navigation.NavigationEditorProvider; +import com.android.tools.idea.editors.navigation.Utilities; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VirtualFile; import icons.AndroidIcons; import org.jetbrains.annotations.Nullable; -import java.io.IOException; - public class AndroidShowNavigationEditor extends AnAction { public AndroidShowNavigationEditor() { super("Navigation Editor", null, AndroidIcons.NavigationEditor); } - private static VirtualFile mkDirs(VirtualFile dir, String path) throws IOException { - for(String dirName : path.split("/")) { - VirtualFile existingDir = dir.findFileByRelativePath(dirName); - dir = (existingDir != null) ? existingDir : dir.createChildDirectory(null, dirName); - } - return dir; - } - public void showNavigationEditor(@Nullable Project project, final String dir, final String file) { if (project == null) { return; @@ -51,24 +40,7 @@ public class AndroidShowNavigationEditor extends AnAction { if (baseDir == null) { // this happens when we have the 'default' project, we can't launch nav editor here return; } - final String relativePathOfNavDir = ".navigation" + "/" + dir; - VirtualFile navFile = baseDir.findFileByRelativePath(relativePathOfNavDir + "/" + file); - if (navFile == null) { - navFile = ApplicationManager.getApplication().runWriteAction(new Computable<VirtualFile>() { - @Override - public VirtualFile compute() { - try { - VirtualFile dir = mkDirs(baseDir, relativePathOfNavDir); - return dir.createChildData(null, file); - } - catch (IOException e) { - assert false; - return null; - } - - } - }); - } + VirtualFile navFile = Utilities.getNavigationFile(baseDir, dir, file); OpenFileDescriptor descriptor = new OpenFileDescriptor(project, navFile, 0); FileEditorManager manager = FileEditorManager.getInstance(project); manager.openEditor(descriptor, true); diff --git a/android/src/com/android/tools/idea/editors/navigation/NavigationEditor.java b/android/src/com/android/tools/idea/editors/navigation/NavigationEditor.java index 754e5d9dce0..d5420b75bb7 100644 --- a/android/src/com/android/tools/idea/editors/navigation/NavigationEditor.java +++ b/android/src/com/android/tools/idea/editors/navigation/NavigationEditor.java @@ -114,7 +114,7 @@ public class NavigationEditor implements FileEditor { if (myRenderingParams != null) { Configuration configuration = myRenderingParams.myConfiguration; Module module = configuration.getModule(); - myAnalyser = new Analyser(project, module); + myAnalyser = new Analyser(module); try { myNavigationModel = read(file); myCodeGenerator = new CodeGenerator(myNavigationModel, module); diff --git a/android/src/com/android/tools/idea/editors/navigation/Utilities.java b/android/src/com/android/tools/idea/editors/navigation/Utilities.java index 0149663c913..92f521f63a0 100644 --- a/android/src/com/android/tools/idea/editors/navigation/Utilities.java +++ b/android/src/com/android/tools/idea/editors/navigation/Utilities.java @@ -15,8 +15,10 @@ */ package com.android.tools.idea.editors.navigation; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Condition; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; @@ -28,6 +30,7 @@ import org.jetbrains.annotations.Nullable; import java.awt.*; import java.awt.geom.AffineTransform; import java.io.File; +import java.io.IOException; public class Utilities { public static final Dimension ZERO_SIZE = new Dimension(0, 0); @@ -233,4 +236,34 @@ public class Utilities { public static VirtualFile virtualFile(File file) { return LocalFileSystem.getInstance().findFileByIoFile(file); } + + public static VirtualFile mkDirs(VirtualFile dir, String path) throws IOException { + for(String dirName : path.split("/")) { + VirtualFile existingDir = dir.findFileByRelativePath(dirName); + dir = (existingDir != null) ? existingDir : dir.createChildDirectory(null, dirName); + } + return dir; + } + + public static VirtualFile getNavigationFile(final VirtualFile baseDir, String deviceQualifier, final String fileName) { + final String relativePathOfNavDir = ".navigation" + "/" + deviceQualifier; + VirtualFile navFile = baseDir.findFileByRelativePath(relativePathOfNavDir + "/" + fileName); + if (navFile == null) { + navFile = ApplicationManager.getApplication().runWriteAction(new Computable<VirtualFile>() { + @Override + public VirtualFile compute() { + try { + VirtualFile dir = mkDirs(baseDir, relativePathOfNavDir); + return dir.createChildData(null, fileName); + } + catch (IOException e) { + assert false; + return null; + } + + } + }); + } + return navFile; + } } diff --git a/android/src/com/android/tools/idea/editors/navigation/macros/Analyser.java b/android/src/com/android/tools/idea/editors/navigation/macros/Analyser.java index 2d7ad37f4d1..e4cccdbf0ec 100644 --- a/android/src/com/android/tools/idea/editors/navigation/macros/Analyser.java +++ b/android/src/com/android/tools/idea/editors/navigation/macros/Analyser.java @@ -47,16 +47,20 @@ public class Analyser { private static final String[] ID_PREFIXES = {"@+id/", "@android:id/"}; private static final boolean DEBUG = false; - private final Project myProject; private final Module myModule; private final Macros myMacros; - public Analyser(Project project, Module module) { - myProject = project; + public Analyser(Module module) { myModule = module; myMacros = Macros.getInstance(myModule.getProject()); } + public NavigationModel getNavigationModel(Configuration configuration) { + NavigationModel result = new NavigationModel(); + deriveAllStatesAndTransitions(result, configuration); + return result; + } + @Nullable private static String qualifyClassNameIfNecessary(@Nullable String packageName, String className) { if (className == null) { @@ -306,7 +310,7 @@ public class Analyser { if (xmlFileName == null) { return null; } - return (XmlFile)NavigationView.getLayoutXmlFile(false, xmlFileName, configuration, myProject); + return (XmlFile)NavigationView.getLayoutXmlFile(false, xmlFileName, configuration, myModule.getProject()); } private void deriveTransitions(final NavigationModel model, @@ -429,7 +433,7 @@ public class Analyser { } public NavigationModel deriveAllStatesAndTransitions(NavigationModel model, Configuration configuration) { - Set<String> activityClassNames = readManifestFile(myProject); + Set<String> activityClassNames = readManifestFile(myModule.getProject()); if (DEBUG) { System.out.println("deriveAllStatesAndTransitions = " + activityClassNames); } diff --git a/android/src/com/android/tools/idea/editors/navigation/macros/Macros.java b/android/src/com/android/tools/idea/editors/navigation/macros/Macros.java index a82534996fb..947d4719736 100644 --- a/android/src/com/android/tools/idea/editors/navigation/macros/Macros.java +++ b/android/src/com/android/tools/idea/editors/navigation/macros/Macros.java @@ -15,6 +15,7 @@ */ package com.android.tools.idea.editors.navigation.macros; +import com.android.tools.idea.editors.navigation.Utilities; import com.intellij.openapi.project.Project; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; @@ -27,11 +28,65 @@ import java.util.IdentityHashMap; import java.util.Map; public class Macros { - private static final String TEMPLATES_PACKAGE = /*"com.android.templates.".replace('.', '/')*/ ""; - private static final String GENERAL_TEMPLATES = TEMPLATES_PACKAGE + "GeneralTemplates"; - private static final String LISTENER_TEMPLATES = TEMPLATES_PACKAGE + "InstallListenerTemplates"; - private static final String ACCESS_TEMPLATES = TEMPLATES_PACKAGE + "AccessTemplates"; - private static final String LAUNCH_ACTIVITY_TEMPLATES = TEMPLATES_PACKAGE + "LaunchActivityTemplates"; + private static final String DEFINE_ASSIGNMENT = + "void macro(String $fragmentName, Void $messageController) {" + + " getFragment($fragmentName, $messageController);" + + "}"; + + private static final String DEFINE_INNER_CLASS = + "void macro(Class $Interface, Void $method, Class $Type, Object $arg, final Statement $f) {" + + " new $Interface() {" + + " public void $method($Type $arg) {" + + " $f.$();" + + " }" + + " };" + + "}"; + + private static final String INSTALL_CLICK_LISTENER = + "void macro(View $view, Statement $f) {" + + " $view.setOnClickListener(new View.OnClickListener() {" + + " @Override" + + " public void onClick(View view) {" + + " $f.$();" + + " }" + + " });" + + "}"; + + private static final String INSTALL_MENU_ITEM_CLICK = + "void macro(MenuItem $menuItem, final Statement $f, final boolean $consume) {" + + " $menuItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {" + + " @Override" + + " public boolean onMenuItemClick(MenuItem menuItem) {" + + " $f.$();" + + " return $consume;" + + " }" + + " });" + + "}"; + + private static final String INSTALL_ITEM_CLICK_LISTENER = + "void macro(ListView $listView, final Statement $f) {" + + " $listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {" + + " @Override" + + " public void onItemClick(AdapterView<?> parent, View view, int position, long id) {" + + " $f.$$();" + + " }" + + " });" + + "}"; + + private static final String GET_MENU_ITEM = + "void macro(Menu $menu, int $id) {" + + " $menu.findItem($id);" + + "}"; + + private static final String LAUNCH_ACTIVITY = + "void macro(Context context, Class activityClass) {" + + " context.startActivity(new Intent(context, activityClass));" + + "}"; + + private static final String LAUNCH_ACTIVITY_WITH_ARG = + "<T extends Serializable> void macro(Context context, Class activityClass, String name, T value) {" + + " context.startActivity(new Intent(context, activityClass).putExtra(name, value));" + + "}"; public final PsiMethod defineAssignment; @@ -83,19 +138,23 @@ public class Macros { return MultiMatch.create(myProject, methodDefinition); } + private PsiMethod getMethodFromText(String definition) { + return Utilities.createMethodFromText(myProject, definition); + } + private Macros(Project project) { myProject = project; - defineAssignment = getMethodsByName(GENERAL_TEMPLATES, "defineAssignment", project)[0]; - PsiMethod defineInnerClassMacro = getMethodsByName(GENERAL_TEMPLATES, "defineInnerClass", project)[0]; + defineAssignment = getMethodFromText(DEFINE_ASSIGNMENT); + PsiMethod defineInnerClassMacro = getMethodFromText(DEFINE_INNER_CLASS); - PsiMethod installClickMacro = getMethodsByName(LISTENER_TEMPLATES, "installClickListener", project)[0]; - PsiMethod installMenuItemClickMacro = getMethodsByName(LISTENER_TEMPLATES, "installMenuItemClick", project)[0]; - PsiMethod installItemClickMacro = getMethodsByName(LISTENER_TEMPLATES, "installItemClickListener", project)[0]; + PsiMethod installClickMacro = getMethodFromText(INSTALL_CLICK_LISTENER); + PsiMethod installMenuItemClickMacro = getMethodFromText(INSTALL_MENU_ITEM_CLICK); + PsiMethod installItemClickMacro = getMethodFromText(INSTALL_ITEM_CLICK_LISTENER); - PsiMethod getMenuItemMacro = getMethodsByName(ACCESS_TEMPLATES, "getMenuItem", project)[0]; + PsiMethod getMenuItemMacro = getMethodFromText(GET_MENU_ITEM); - PsiMethod launchActivityMacro = getMethodsByName(LAUNCH_ACTIVITY_TEMPLATES, "launchActivity", project)[0]; - PsiMethod launchActivityMacro2 = getMethodsByName(LAUNCH_ACTIVITY_TEMPLATES, "launchActivity", project)[1]; + PsiMethod launchActivityMacro = getMethodFromText(LAUNCH_ACTIVITY); + PsiMethod launchActivityMacro2 = getMethodFromText(LAUNCH_ACTIVITY_WITH_ARG); createIntent = createMacro("void macro(Context context, Class activityClass) { new Intent(context, activityClass); }"); installClickAndCallMacro = new MultiMatch(installClickMacro); diff --git a/android/testData/projects/navigationEditor/masterDetail/build.gradle b/android/testData/projects/navigationEditor/masterDetail/build.gradle new file mode 100644 index 00000000000..bb278f5054b --- /dev/null +++ b/android/testData/projects/navigationEditor/masterDetail/build.gradle @@ -0,0 +1,39 @@ +// 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.13.0' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +apply plugin: 'com.android.application' + +android { + compileSdkVersion 19 + buildToolsVersion "19.1.0" + + defaultConfig { + applicationId "com.example.masterdetail" + minSdkVersion 15 + targetSdkVersion 19 + versionCode 1 + versionName "1.0" + } + buildTypes { + release { + runProguard false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + compile 'com.android.support:support-v4:20.0.0' +} diff --git a/android/testData/projects/navigationEditor/masterDetail/src/main/AndroidManifest.xml b/android/testData/projects/navigationEditor/masterDetail/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..b6c67761f29 --- /dev/null +++ b/android/testData/projects/navigationEditor/masterDetail/src/main/AndroidManifest.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="utf-8"?> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.example.masterdetail" > + + <application + android:allowBackup="true" + android:icon="@drawable/ic_launcher" + android:label="@string/app_name" + android:theme="@style/AppTheme" > + <activity + android:name="com.example.masterdetail.ItemListActivity" + android:label="@string/app_name" > + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity> + <activity + android:name="com.example.masterdetail.ItemDetailActivity" + android:label="@string/title_item_detail" + android:parentActivityName="com.example.masterdetail.ItemListActivity" > + <meta-data + android:name="android.support.PARENT_ACTIVITY" + android:value=".ItemListActivity" /> + </activity> + </application> + +</manifest> diff --git a/android/testData/projects/navigationEditor/masterDetail/src/main/java/com/example/masterdetail/ItemDetailActivity.java b/android/testData/projects/navigationEditor/masterDetail/src/main/java/com/example/masterdetail/ItemDetailActivity.java new file mode 100644 index 00000000000..0d50f223d74 --- /dev/null +++ b/android/testData/projects/navigationEditor/masterDetail/src/main/java/com/example/masterdetail/ItemDetailActivity.java @@ -0,0 +1,68 @@ +package com.example.masterdetail; + +import android.content.Intent; +import android.os.Bundle; +import android.app.Activity; +import android.support.v4.app.NavUtils; +import android.view.MenuItem; + + +/** + * An activity representing a single Item detail screen. This + * activity is only used on handset devices. On tablet-size devices, + * item details are presented side-by-side with a list of items + * in a {@link ItemListActivity}. + * <p> + * This activity is mostly just a 'shell' activity containing nothing + * more than a {@link ItemDetailFragment}. + */ +public class ItemDetailActivity extends Activity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_item_detail); + + // Show the Up button in the action bar. + getActionBar().setDisplayHomeAsUpEnabled(true); + + // savedInstanceState is non-null when there is fragment state + // saved from previous configurations of this activity + // (e.g. when rotating the screen from portrait to landscape). + // In this case, the fragment will automatically be re-added + // to its container so we don't need to manually add it. + // For more information, see the Fragments API guide at: + // + // http://developer.android.com/guide/components/fragments.html + // + if (savedInstanceState == null) { + // Create the detail fragment and add it to the activity + // using a fragment transaction. + Bundle arguments = new Bundle(); + arguments.putString(ItemDetailFragment.ARG_ITEM_ID, + getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID)); + ItemDetailFragment fragment = new ItemDetailFragment(); + fragment.setArguments(arguments); + getFragmentManager().beginTransaction() + .add(R.id.item_detail_container, fragment) + .commit(); + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + if (id == android.R.id.home) { + // This ID represents the Home or Up button. In the case of this + // activity, the Up button is shown. Use NavUtils to allow users + // to navigate up one level in the application structure. For + // more details, see the Navigation pattern on Android Design: + // + // http://developer.android.com/design/patterns/navigation.html#up-vs-back + // + NavUtils.navigateUpTo(this, new Intent(this, ItemListActivity.class)); + return true; + } + return super.onOptionsItemSelected(item); + } +} diff --git a/android/testData/projects/navigationEditor/masterDetail/src/main/java/com/example/masterdetail/ItemDetailFragment.java b/android/testData/projects/navigationEditor/masterDetail/src/main/java/com/example/masterdetail/ItemDetailFragment.java new file mode 100644 index 00000000000..1ebd4517515 --- /dev/null +++ b/android/testData/projects/navigationEditor/masterDetail/src/main/java/com/example/masterdetail/ItemDetailFragment.java @@ -0,0 +1,62 @@ +package com.example.masterdetail; + +import android.os.Bundle; +import android.app.Fragment; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + + +import com.example.masterdetail.dummy.DummyContent; + +/** + * A fragment representing a single Item detail screen. + * This fragment is either contained in a {@link ItemListActivity} + * in two-pane mode (on tablets) or a {@link ItemDetailActivity} + * on handsets. + */ +public class ItemDetailFragment extends Fragment { + /** + * The fragment argument representing the item ID that this fragment + * represents. + */ + public static final String ARG_ITEM_ID = "item_id"; + + /** + * The dummy content this fragment is presenting. + */ + private DummyContent.DummyItem mItem; + + /** + * Mandatory empty constructor for the fragment manager to instantiate the + * fragment (e.g. upon screen orientation changes). + */ + public ItemDetailFragment() { + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + if (getArguments().containsKey(ARG_ITEM_ID)) { + // Load the dummy content specified by the fragment + // arguments. In a real-world scenario, use a Loader + // to load content from a content provider. + mItem = DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID)); + } + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + View rootView = inflater.inflate(R.layout.fragment_item_detail, container, false); + + // Show the dummy content as text in a TextView. + if (mItem != null) { + ((TextView) rootView.findViewById(R.id.item_detail)).setText(mItem.content); + } + + return rootView; + } +} diff --git a/android/testData/projects/navigationEditor/masterDetail/src/main/java/com/example/masterdetail/ItemListActivity.java b/android/testData/projects/navigationEditor/masterDetail/src/main/java/com/example/masterdetail/ItemListActivity.java new file mode 100644 index 00000000000..80f3f81b484 --- /dev/null +++ b/android/testData/projects/navigationEditor/masterDetail/src/main/java/com/example/masterdetail/ItemListActivity.java @@ -0,0 +1,83 @@ +package com.example.masterdetail; + +import android.content.Intent; +import android.os.Bundle; +import android.app.Activity; + + + + +/** + * An activity representing a list of Items. This activity + * has different presentations for handset and tablet-size devices. On + * handsets, the activity presents a list of items, which when touched, + * lead to a {@link ItemDetailActivity} representing + * item details. On tablets, the activity presents the list of items and + * item details side-by-side using two vertical panes. + * <p> + * The activity makes heavy use of fragments. The list of items is a + * {@link ItemListFragment} and the item details + * (if present) is a {@link ItemDetailFragment}. + * <p> + * This activity also implements the required + * {@link ItemListFragment.Callbacks} interface + * to listen for item selections. + */ +public class ItemListActivity extends Activity + implements ItemListFragment.Callbacks { + + /** + * Whether or not the activity is in two-pane mode, i.e. running on a tablet + * device. + */ + private boolean mTwoPane; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_item_list); + + if (findViewById(R.id.item_detail_container) != null) { + // The detail container view will be present only in the + // large-screen layouts (res/values-large and + // res/values-sw600dp). If this view is present, then the + // activity should be in two-pane mode. + mTwoPane = true; + + // In two-pane mode, list items should be given the + // 'activated' state when touched. + ((ItemListFragment) getFragmentManager() + .findFragmentById(R.id.item_list)) + .setActivateOnItemClick(true); + } + + // TODO: If exposing deep links into your app, handle intents here. + } + + /** + * Callback method from {@link ItemListFragment.Callbacks} + * indicating that the item with the given ID was selected. + */ + @Override + public void onItemSelected(String id) { + if (mTwoPane) { + // In two-pane mode, show the detail view in this activity by + // adding or replacing the detail fragment using a + // fragment transaction. + Bundle arguments = new Bundle(); + arguments.putString(ItemDetailFragment.ARG_ITEM_ID, id); + ItemDetailFragment fragment = new ItemDetailFragment(); + fragment.setArguments(arguments); + getFragmentManager().beginTransaction() + .replace(R.id.item_detail_container, fragment) + .commit(); + + } else { + // In single-pane mode, simply start the detail activity + // for the selected item ID. + Intent detailIntent = new Intent(this, ItemDetailActivity.class); + detailIntent.putExtra(ItemDetailFragment.ARG_ITEM_ID, id); + startActivity(detailIntent); + } + } +} diff --git a/android/testData/projects/navigationEditor/masterDetail/src/main/java/com/example/masterdetail/ItemListFragment.java b/android/testData/projects/navigationEditor/masterDetail/src/main/java/com/example/masterdetail/ItemListFragment.java new file mode 100644 index 00000000000..c2d99a2c85c --- /dev/null +++ b/android/testData/projects/navigationEditor/masterDetail/src/main/java/com/example/masterdetail/ItemListFragment.java @@ -0,0 +1,152 @@ +package com.example.masterdetail; + +import android.app.Activity; +import android.os.Bundle; +import android.app.ListFragment; +import android.view.View; +import android.widget.ArrayAdapter; +import android.widget.ListView; + + +import com.example.masterdetail.dummy.DummyContent; + +/** + * A list fragment representing a list of Items. This fragment + * also supports tablet devices by allowing list items to be given an + * 'activated' state upon selection. This helps indicate which item is + * currently being viewed in a {@link ItemDetailFragment}. + * <p> + * Activities containing this fragment MUST implement the {@link Callbacks} + * interface. + */ +public class ItemListFragment extends ListFragment { + + /** + * The serialization (saved instance state) Bundle key representing the + * activated item position. Only used on tablets. + */ + private static final String STATE_ACTIVATED_POSITION = "activated_position"; + + /** + * The fragment's current callback object, which is notified of list item + * clicks. + */ + private Callbacks mCallbacks = sDummyCallbacks; + + /** + * The current activated item position. Only used on tablets. + */ + private int mActivatedPosition = ListView.INVALID_POSITION; + + /** + * A callback interface that all activities containing this fragment must + * implement. This mechanism allows activities to be notified of item + * selections. + */ + public interface Callbacks { + /** + * Callback for when an item has been selected. + */ + public void onItemSelected(String id); + } + + /** + * A dummy implementation of the {@link Callbacks} interface that does + * nothing. Used only when this fragment is not attached to an activity. + */ + private static Callbacks sDummyCallbacks = new Callbacks() { + @Override + public void onItemSelected(String id) { + } + }; + + /** + * Mandatory empty constructor for the fragment manager to instantiate the + * fragment (e.g. upon screen orientation changes). + */ + public ItemListFragment() { + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // TODO: replace with a real list adapter. + setListAdapter(new ArrayAdapter<DummyContent.DummyItem>( + getActivity(), + android.R.layout.simple_list_item_activated_1, + android.R.id.text1, + DummyContent.ITEMS)); + } + + @Override + public void onViewCreated(View view, Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + + // Restore the previously serialized activated item position. + if (savedInstanceState != null + && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) { + setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION)); + } + } + + @Override + public void onAttach(Activity activity) { + super.onAttach(activity); + + // Activities containing this fragment must implement its callbacks. + if (!(activity instanceof Callbacks)) { + throw new IllegalStateException("Activity must implement fragment's callbacks."); + } + + mCallbacks = (Callbacks) activity; + } + + @Override + public void onDetach() { + super.onDetach(); + + // Reset the active callbacks interface to the dummy implementation. + mCallbacks = sDummyCallbacks; + } + + @Override + public void onListItemClick(ListView listView, View view, int position, long id) { + super.onListItemClick(listView, view, position, id); + + // Notify the active callbacks interface (the activity, if the + // fragment is attached to one) that an item has been selected. + mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id); + } + + @Override + public void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + if (mActivatedPosition != ListView.INVALID_POSITION) { + // Serialize and persist the activated item position. + outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition); + } + } + + /** + * Turns on activate-on-click mode. When this mode is on, list items will be + * given the 'activated' state when touched. + */ + public void setActivateOnItemClick(boolean activateOnItemClick) { + // When setting CHOICE_MODE_SINGLE, ListView will automatically + // give items the 'activated' state when touched. + getListView().setChoiceMode(activateOnItemClick + ? ListView.CHOICE_MODE_SINGLE + : ListView.CHOICE_MODE_NONE); + } + + private void setActivatedPosition(int position) { + if (position == ListView.INVALID_POSITION) { + getListView().setItemChecked(mActivatedPosition, false); + } else { + getListView().setItemChecked(position, true); + } + + mActivatedPosition = position; + } +} diff --git a/android/testData/projects/navigationEditor/masterDetail/src/main/java/com/example/masterdetail/dummy/DummyContent.java b/android/testData/projects/navigationEditor/masterDetail/src/main/java/com/example/masterdetail/dummy/DummyContent.java new file mode 100644 index 00000000000..48055c37a9a --- /dev/null +++ b/android/testData/projects/navigationEditor/masterDetail/src/main/java/com/example/masterdetail/dummy/DummyContent.java @@ -0,0 +1,55 @@ +package com.example.masterdetail.dummy; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Helper class for providing sample content for user interfaces created by + * Android template wizards. + * <p> + * TODO: Replace all uses of this class before publishing your app. + */ +public class DummyContent { + + /** + * An array of sample (dummy) items. + */ + public static List<DummyItem> ITEMS = new ArrayList<DummyItem>(); + + /** + * A map of sample (dummy) items, by ID. + */ + public static Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>(); + + static { + // Add 3 sample items. + addItem(new DummyItem("1", "Item 1")); + addItem(new DummyItem("2", "Item 2")); + addItem(new DummyItem("3", "Item 3")); + } + + private static void addItem(DummyItem item) { + ITEMS.add(item); + ITEM_MAP.put(item.id, item); + } + + /** + * A dummy item representing a piece of content. + */ + public static class DummyItem { + public String id; + public String content; + + public DummyItem(String id, String content) { + this.id = id; + this.content = content; + } + + @Override + public String toString() { + return content; + } + } +} diff --git a/android/testData/projects/navigationEditor/masterDetail/src/main/res/layout/activity_item_detail.xml b/android/testData/projects/navigationEditor/masterDetail/src/main/res/layout/activity_item_detail.xml new file mode 100644 index 00000000000..2f4eed23a02 --- /dev/null +++ b/android/testData/projects/navigationEditor/masterDetail/src/main/res/layout/activity_item_detail.xml @@ -0,0 +1,7 @@ +<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + android:id="@+id/item_detail_container" + android:layout_width="match_parent" + android:layout_height="match_parent" + tools:context=".ItemDetailActivity" + tools:ignore="MergeRootFrame" /> diff --git a/android/testData/projects/navigationEditor/masterDetail/src/main/res/layout/activity_item_list.xml b/android/testData/projects/navigationEditor/masterDetail/src/main/res/layout/activity_item_list.xml new file mode 100644 index 00000000000..c4d521855f6 --- /dev/null +++ b/android/testData/projects/navigationEditor/masterDetail/src/main/res/layout/activity_item_list.xml @@ -0,0 +1,10 @@ +<fragment xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + android:id="@+id/item_list" + android:name="com.example.masterdetail.ItemListFragment" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:layout_marginLeft="16dp" + android:layout_marginRight="16dp" + tools:context=".ItemListActivity" + tools:layout="@android:layout/list_content" /> diff --git a/android/testData/projects/navigationEditor/masterDetail/src/main/res/layout/activity_item_twopane.xml b/android/testData/projects/navigationEditor/masterDetail/src/main/res/layout/activity_item_twopane.xml new file mode 100644 index 00000000000..4c8311c92b1 --- /dev/null +++ b/android/testData/projects/navigationEditor/masterDetail/src/main/res/layout/activity_item_twopane.xml @@ -0,0 +1,38 @@ +<LinearLayout 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" + android:layout_marginLeft="16dp" + android:layout_marginRight="16dp" + android:baselineAligned="false" + android:divider="?android:attr/dividerHorizontal" + android:orientation="horizontal" + android:showDividers="middle" + tools:context=".ItemListActivity"> + + <!-- + This layout is a two-pane layout for the Items + master/detail flow. See res/values-large/refs.xml and + res/values-sw600dp/refs.xml for an example of layout aliases + that replace the single-pane version of the layout with + this two-pane version. + + For more on layout aliases, see: + http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters + --> + + <fragment + android:id="@+id/item_list" + android:name="com.example.masterdetail.ItemListFragment" + android:layout_width="0dp" + android:layout_height="match_parent" + android:layout_weight="1" + tools:layout="@android:layout/list_content" /> + + <FrameLayout + android:id="@+id/item_detail_container" + android:layout_width="0dp" + android:layout_height="match_parent" + android:layout_weight="3" /> + +</LinearLayout> diff --git a/android/testData/projects/navigationEditor/masterDetail/src/main/res/layout/fragment_item_detail.xml b/android/testData/projects/navigationEditor/masterDetail/src/main/res/layout/fragment_item_detail.xml new file mode 100644 index 00000000000..dd53b8eeaf4 --- /dev/null +++ b/android/testData/projects/navigationEditor/masterDetail/src/main/res/layout/fragment_item_detail.xml @@ -0,0 +1,9 @@ +<TextView xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + android:id="@+id/item_detail" + style="?android:attr/textAppearanceLarge" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:padding="16dp" + android:textIsSelectable="true" + tools:context=".ItemDetailFragment" /> diff --git a/android/testData/projects/navigationEditor/masterDetail/src/main/res/values-large/refs.xml b/android/testData/projects/navigationEditor/masterDetail/src/main/res/values-large/refs.xml new file mode 100644 index 00000000000..b03dc5695e5 --- /dev/null +++ b/android/testData/projects/navigationEditor/masterDetail/src/main/res/values-large/refs.xml @@ -0,0 +1,10 @@ +<resources> + <!-- + Layout alias to replace the single-pane version of the layout with a + two-pane version on Large screens. + + For more on layout aliases, see: + http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters + --> + <item type="layout" name="activity_item_list">@layout/activity_item_twopane</item> +</resources> diff --git a/android/testData/projects/navigationEditor/masterDetail/src/main/res/values-sw600dp/refs.xml b/android/testData/projects/navigationEditor/masterDetail/src/main/res/values-sw600dp/refs.xml new file mode 100644 index 00000000000..b03dc5695e5 --- /dev/null +++ b/android/testData/projects/navigationEditor/masterDetail/src/main/res/values-sw600dp/refs.xml @@ -0,0 +1,10 @@ +<resources> + <!-- + Layout alias to replace the single-pane version of the layout with a + two-pane version on Large screens. + + For more on layout aliases, see: + http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters + --> + <item type="layout" name="activity_item_list">@layout/activity_item_twopane</item> +</resources> diff --git a/android/testData/projects/navigationEditor/masterDetail/src/main/res/values/strings.xml b/android/testData/projects/navigationEditor/masterDetail/src/main/res/values/strings.xml new file mode 100644 index 00000000000..80aa3a6ab9c --- /dev/null +++ b/android/testData/projects/navigationEditor/masterDetail/src/main/res/values/strings.xml @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + + <string name="app_name">MasterDetail</string> + <string name="title_item_detail">Item Detail</string> + +</resources> diff --git a/android/testData/projects/navigationEditor/masterDetail/src/main/res/values/styles.xml b/android/testData/projects/navigationEditor/masterDetail/src/main/res/values/styles.xml new file mode 100644 index 00000000000..ff6c9d2c0fb --- /dev/null +++ b/android/testData/projects/navigationEditor/masterDetail/src/main/res/values/styles.xml @@ -0,0 +1,8 @@ +<resources> + + <!-- Base application theme. --> + <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar"> + <!-- Customize your theme here. --> + </style> + +</resources> diff --git a/android/testSrc/com/android/navigation/NavigationEditorTest.java b/android/testSrc/com/android/navigation/NavigationEditorTest.java new file mode 100644 index 00000000000..c5eb98c19b4 --- /dev/null +++ b/android/testSrc/com/android/navigation/NavigationEditorTest.java @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.navigation; + +import com.android.tools.idea.configurations.Configuration; +import com.android.tools.idea.editors.navigation.Utilities; +import com.android.tools.idea.editors.navigation.macros.Analyser; +import com.android.tools.idea.gradle.IdeaAndroidProject; +import com.android.tools.idea.templates.AndroidGradleTestCase; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.module.ModuleManager; +import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.android.facet.AndroidFacet; +import org.jetbrains.android.sdk.AndroidPlatform; + +import static org.junit.Assume.assumeTrue; + +/** + * Tests for NavigationEditor's parsing infrastructure. + */ +public class NavigationEditorTest extends AndroidGradleTestCase { + private Module myModule; + private AndroidFacet myFacet; + + @Override + public void setUp() throws Exception { + super.setUp(); + assumeTrue(CAN_SYNC_PROJECTS); + + loadProject("projects/navigationEditor/masterDetail"); + assertNotNull(myAndroidFacet); + IdeaAndroidProject gradleProject = myAndroidFacet.getIdeaAndroidProject(); + assertNotNull(gradleProject); + + Module[] modules = ModuleManager.getInstance(getProject()).getModules(); + + assertTrue(modules.length == 1); + myModule = modules[0]; + assertNotNull(myModule); + + myFacet = AndroidFacet.getInstance(myModule); + assertNotNull(myFacet); + + addAndroidSdk(myModule, getTestSdkPath(), getPlatformDir()); + assertNotNull(AndroidPlatform.getInstance(myModule)); + } + + private NavigationModel getNavigationModel(String deviceQualifier) { + VirtualFile navFile = Utilities.getNavigationFile(myModule.getProject().getBaseDir(), deviceQualifier, "main.nvg.xml"); + Configuration configuration = myFacet.getConfigurationManager().getConfiguration(navFile); + Analyser analyser = new Analyser(myModule); + return analyser.getNavigationModel(configuration); + } + + @SuppressWarnings("TestMethodWithIncorrectSignature") + private void testTransitionDerivation(String deviceQualifier, int expectedStateCount, int expectedTransitionCount) { + NavigationModel model = getNavigationModel(deviceQualifier); + assertTrue(model.getStates().size() == expectedStateCount); + assertTrue(model.getTransitions().size() == expectedTransitionCount); + } + + public void testTransitionDerivationForDefaultDevice() throws Exception { + testTransitionDerivation("raw", 2, 1); + } + + /* When a master-detail app like simplemail runs on a tablet, there is one less transition in landscape. */ + public void testTransitionDerivationForTabletInLandscape() throws Exception { + testTransitionDerivation("raw-sw600dp-land", 2, 0); + } +} |