多设备官方教程(5)多屏幕(下)用代码控制运行时各布局应何时显示
Implementing Adaptative UI Flows
Depending on the layout that your application is currently showing, the UI flow may be different. For example, if your application is in the dual-pane mode, clicking on an item on the left pane will simply display the content on the right pane; if it is in single-pane mode, the content should be displayed on its own (in a different activity).
Determine the Current Layout
Since your implementation of each layout will be a little different, one of the first things you will probably have to do is determine what layout the user is currently viewing. For example, you might want to know whether the user is in "single pane" mode or "dual pane" mode. You can do that by querying if a given view exists and is visible:
在有多个布局文件时,通常要判断当前显示的是哪个布局,可用它的visiable属性
1 public class NewsReaderActivity extends FragmentActivity { 2 boolean mIsDualPane; 3 4 @Override 5 public void onCreate(Bundle savedInstanceState) { 6 super.onCreate(savedInstanceState); 7 setContentView(R.layout.main_layout); 8 9 View articleView = findViewById(R.id.article); 10 mIsDualPane = articleView != null && 11 articleView.getVisibility() == View.VISIBLE; 12 } 13 }
Notice that this code queries whether the "article" pane is available or not, which is much more flexible than hard-coding a query for a specific layout.
Another example of how you can adapt to the existence of different components is to check whether they are available before performing an operation on them. For example, in the News Reader sample app, there is a button that opens a menu, but that button only exists when running on versions older than Android 3.0 (because it's function is taken over by the ActionBar
on API level 11+). So, to add the event listener for this button, you can do:
1 Button catButton = (Button) findViewById(R.id.categorybutton); 2 OnClickListener listener = /* create your listener here */; 3 if (catButton != null) { 4 catButton.setOnClickListener(listener); 5 }
React According to Current Layout
Some actions may have a different result depending on the current layout. For example, in the News Reader sample, clicking on a headline from the headlines list opens the article in the right hand-side pane if the UI is in dual pane mode, but will launch a separate activity if the UI is in single-pane mode:
注意当有不同布局时,在显示时同一个功能时,它们可能在同一个布局中,也可能在多个布局中或activity中,处理代码要注意崩溃的问题
1 @Override 2 public void onHeadlineSelected(int index) { 3 mArtIndex = index; 4 if (mIsDualPane) { 5 /* display article on the right pane */ 6 mArticleFragment.displayArticle(mCurrentCat.getArticle(index)); 7 } else { 8 /* start a separate activity */ 9 Intent intent = new Intent(this, ArticleActivity.class); 10 intent.putExtra("catIndex", mCatIndex); 11 intent.putExtra("artIndex", index); 12 startActivity(intent); 13 } 14 }
Likewise, if the app is in dual-pane mode, it should set up the action bar with tabs for navigation, whereas if the app is in single-pane mode, it should set up navigation with a spinner widget. So your code should also check which case is appropriate:
1 final String CATEGORIES[] = { "Top Stories", "Politics", "Economy", "Technology" }; 2 3 public void onCreate(Bundle savedInstanceState) { 4 .... 5 if (mIsDualPane) { 6 /* use tabs for navigation */ 7 actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS); 8 int i; 9 for (i = 0; i < CATEGORIES.length; i++) { 10 actionBar.addTab(actionBar.newTab().setText( 11 CATEGORIES[i]).setTabListener(handler)); 12 } 13 actionBar.setSelectedNavigationItem(selTab); 14 } 15 else { 16 /* use list navigation (spinner) */ 17 actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST); 18 SpinnerAdapter adap = new ArrayAdapter(this, 19 R.layout.headline_item, CATEGORIES); 20 actionBar.setListNavigationCallbacks(adap, handler); 21 } 22 }
Reuse Fragments in Other Activities
A recurring pattern in designing for multiple screens is having a portion of your interface that's implemented as a pane on some screen configurations and as a separate activity on other configurations. For example, in the News Reader sample, the news article text is presented in the right side pane on large screens, but is a separate activity on smaller screens.
In cases like this, you can usually avoid code duplication by reusing the same Fragment
subclass in several activities. For example, ArticleFragment
is used in the dual-pane layout:
fragment的重用性很好,可以多用。
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:layout_width="fill_parent" 3 android:layout_height="fill_parent" 4 android:orientation="horizontal"> 5 <fragment android:id="@+id/headlines" 6 android:layout_height="fill_parent" 7 android:name="com.example.android.newsreader.HeadlinesFragment" 8 android:layout_width="400dp" 9 android:layout_marginRight="10dp"/> 10 <fragment android:id="@+id/article" 11 android:layout_height="fill_parent" 12 android:name="com.example.android.newsreader.ArticleFragment" 13 android:layout_width="fill_parent" /> 14 </LinearLayout>
And reused (without a layout) in the activity layout for smaller screens (ArticleActivity
):
1 ArticleFragment frag = new ArticleFragment(); 2 getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
Naturally, this has the same effect as declaring the fragment in an XML layout, but in this case an XML layout is unnecessary work because the article fragment is the only component of this activity.
One very important point to keep in mind when designing your fragments is to not create a strong coupling to a specific activity. You can usually do that by defining an interface that abstracts all the ways in which the fragment needs to interact with its host activity, and then the host activity implements that interface:
For example, the News Reader app's HeadlinesFragment
does precisely that:
要注意fragment与它的宿主之间的耦合度
1 public class HeadlinesFragment extends ListFragment { 2 ... 3 OnHeadlineSelectedListener mHeadlineSelectedListener = null; 4 5 /* Must be implemented by host activity */ 6 public interface OnHeadlineSelectedListener { 7 public void onHeadlineSelected(int index); 8 } 9 ... 10 11 public void setOnHeadlineSelectedListener(OnHeadlineSelectedListener listener) { 12 mHeadlineSelectedListener = listener; 13 } 14 }
Then, when the user selects a headline, the fragment notifies the listener specified by the host activity (as opposed to notifying a specific hard-coded activity):
1 public class HeadlinesFragment extends ListFragment { 2 ... 3 @Override 4 public void onItemClick(AdapterView<?> parent, 5 View view, int position, long id) { 6 if (null != mHeadlineSelectedListener) { 7 mHeadlineSelectedListener.onHeadlineSelected(position); 8 } 9 } 10 ... 11 }
This technique is discussed further in the guide to Supporting Tablets and Handsets.
Handle Screen Configuration Changes
If you are using separate activities to implement separate parts of your interface, you have to keep in mind that it may be necessary to react to certain configuration changes (such as a rotation change) in order to keep your interface consistent.
For example, on a typical 7" tablet running Android 3.0 or higher, the News Reader sample uses a separate activity to display the news article when running in portrait mode, but uses a two-pane layout when in landscape mode.
This means that when the user is in portrait mode and the activity for viewing an article is onscreen, you need to detect that the orientation changed to landscape and react appropriately by ending the activity and return to the main activity so the content can display in the two-pane layout:
1 public class ArticleActivity extends FragmentActivity { 2 int mCatIndex, mArtIndex; 3 4 @Override 5 protected void onCreate(Bundle savedInstanceState) { 6 super.onCreate(savedInstanceState); 7 mCatIndex = getIntent().getExtras().getInt("catIndex", 0); 8 mArtIndex = getIntent().getExtras().getInt("artIndex", 0); 9 10 // If should be in two-pane mode, finish to return to main activity 11 if (getResources().getBoolean(R.bool.has_two_panes)) { 12 finish(); 13 return; 14 } 15 ... 16 }