`
sillycat
  • 浏览: 2542036 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Android UI(2)Getting Started - Supporting Devices and Fragments

 
阅读更多
Android UI(2)Getting Started - Supporting Devices and Fragments

3. Supporting Different Devices
Supporting Different Languages
Keep the UI String to external file instead of in the Java Codes.

Create Locale Directories and String Files
Multiple languages
res/
     values/
         strings.xml
     values-es/
         strings.xml
     values-ft/
          strings.xml

Use the String Resources
In Java Codes
The syntax to refer to a string resource is R.string.<string_name>

In XML files
@string/<string_name>

Supporting Different Screens
4 sizes: small, normal, large, large
4 densities: low(LDPI), medium(MDPI), high(HDPI), extra high(XHDPI)

Create Different Layouts
res/
     layout/
          main.xml
     layout-large/
          main.xml
The system will reference the layout file as usual
protected void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
}

Create Different Bitmaps
@drawable/awesomeimage  will reference to the bitmap.

Supporting Different Platform Versions
…snip…

4. Building a Dynamic UI with Fragments
Download the sample project FragmentBasics.zip

Using the Support Library
Set Up Your Project with the Support Library
Make sure I download the Extras/Android Support

Make sure I copy the jar from /opt/android-sdk/extras/android/support/v4/android-support-v4.jar to libs under my own project.

And change my configuration on Manifest file to
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="17"/>

Import the Support Library APIs
…snip…

Creating a Fragment
A fragment is a muddler section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running. (sub activity which you can reuse in different activities)

Create a Fragment Class
Just extends the Fragment class.

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;

public class ArticleFragment extends Fragment {
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          return inflater.inflate(R.layout.article_view,container, false);
     }
}

The lifecycle of Fragment is as like as Activity.

Add a Fragment to an Activity using XML
FragmentActivity is a special activity provided in the Support Library to handle fragments on system versions older than API level 11. After version 11, we can use a regular Activity.

<LinearLayout …>
     <fragment android:name="com.example.android.fragments.HeadlinesFragment"
                    android:id="@+id/headlines_fragment"
                    android:layout_weight="1"
                    android:layout_width="0dp"
                    android:layout_height="match_parent" />
</LinearLayout>

Building a Flexible UI
The FragmentManager class provides methods that allow you to add, remove, and replace fragments to an activity at runtime.

Add a Fragment to an Activity at Runtime
We only define an empty container here
<FrameLayout …snip…
     android:id="@+id/fragment_container"
     android:layout_width="match_parent"
     android:layout_height="match_parent" />

Inside my activity, call getSupportFragmentManager() to get a FragmentManager using the Support Library APIs. Then call beginTransaction() to create a FragmentTransaction and call add() to add a fragment.

Commit the changes with commit().

HeadlinesFragment firstFragment = new HeadlinesFragment();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, firstFragment).commit();

Replace One Fragment with Another
Use the method replace() instead of add().

ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position); //just remember which article we choose
newFragment.setArguments(args);

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null); //make the back button working

transaction.commit();


Communicating with Other Fragments
All Fragment-to-Fragment communication is done through the associated Activity. 2 Fragments should never communicate directly.


Define an Interface
We define an interface and callback method, implement in Activity.

public class HeadlinesFragment extends ListFragment {
     OnHeadlineSelectedListener mCallback;

     public interface OnHeadlineSelectedListener {
          public void onArticleSelected(int position);
     }

     public void onAttach(Activity activity) {
          super.onAttach(activity);
          try{
               mCallback = (OnHeadlineSelectedListener)activity;
          }catch(ClassCastException e){
               throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener");
          }
     }
}

Send the event to Activity
public void onListItemClick(ListView l, View v, int position, long id) {
     mCallback.onArticleSelected(position);
}

The fragment bind the interface to Activity, send the event.
The activity will implement the interface.

Deliver a Message to a Fragment
If the fragment is there, directly call the method.

ArticleFragment articleFrag = (ArticleFragment) getSupportFragmentManager().findFragmentById(R.id.articles_fragment);
if(articleFrag != null){
     articleFrag.updateArticleView(position);
}else{
     …snip...
}

References:
http://developer.android.com/training/basics/supporting-devices/index.html
http://developer.android.com/training/basics/fragments/creating.html
http://developer.android.com/training/basics/fragments/fragment-ui.html


分享到:
评论

相关推荐

    Android代码-android-material-drawer-template

    android-material-drawer-template NEW I released a new template. You can install it on your Android Studio to create Material Design applications easier than ever. Check it out here: ...

    TPM-Rev-2.0-Part-4-Supporting-Routines-01.38.pdf

    The code in this document augments TPM 2.0 Part 2 and TPM 2.0 Part 3 to provide a complete description of a TPM, including the supporting framework for the code that performs the command actions. ...

    英文原版-Supporting Windows 8 2nd Edition

    Featuring the Latest Windows 8.1 ReleaseSUPPORTING WINDOWS 8 is an essential resource for current and aspiring PC repair technicians who need to know up-to-date information on how to support the ...

    不同平台版本支持 -Supporting Different Platform Versions

    在开发Android应用时,考虑不同平台版本的支持是至关重要的。Android设备具有多种屏幕尺寸和密度,为了确保应用能够在尽可能多的设备上良好运行,开发者需要考虑为不同屏幕尺寸和密度准备相应的资源。 Android系统...

    多语言支持 -Supporting Different Languages

    多语言支持是Android应用开发中的一个重要方面,它允许应用根据不同国家和地区的语言环境提供相应的本地化资源。这不仅包括文本内容的翻译,还可能涉及日期、数字格式以及资源文件(如图片和声音)的本地化。为了...

    Zim free notetaking software -- supporting LaTeX

    Zim is a great offline notetaking software that supports LaTeX equations. The running speed is fairly fast.

    CommonsWare.The.Busy.Coders.Guide.to.Android.Development.Version.8.2.2017

    The Busy Coder’s Guide to Android Development covers a wide range of Android capabilities and APIs, from creating simple user interfaces, to supporting long-running background processes, through the...

    Low-Rate Machine-Type Communication via Wireless Device-to-Device (D2D) Links

    wireless devices that reutilize the cellular spectrum and radio interface. The second is that of Machine-Type Communications (MTC), where the objective is to attach a large number of lowrate low-power...

    Android代码-logback-android

    This library provides a highly configurable logging framework for Android apps, supporting multiple log destinations simultaneously: files SQLite databases logcat sockets syslog email Runs on ...

    TPM 2.0 规范 完整版

    TPM-Rev-2.0-Part-2-Structures-01.38 TPM-Rev-2.0-Part-3-Commands-01.38 TPM-Rev-2.0-Part-3-Commands-01.38-code TPM-Rev-2.0-Part-4-Supporting-Routines-01.38 TPM-Rev-2.0-Part-4-Supporting-Routines-01.38-...

    The Busy Coders Guide to Android Development最终版2019

    Android and Projects Tutorial #2 - Creating a Stub Project Getting Around Android Studio Contents of Android Projects Introducing Gradle and the Manifest Tutorial #3 - Manifest Changes Some Words ...

    全球精准肿瘤治疗报告 -Supporting Precision Oncology -IQVIA.pdf

    精准肿瘤治疗,即精准肿瘤学(Precision Oncology),是一种基于每个患者个体化的癌症治疗方法,其核心在于针对特定的生物过程、遗传突变进行治疗,或者精确增强个体的免疫系统。精准肿瘤治疗始于20世纪70年代,当时...

    PC_101_GettingStarted_en.pdf

    PowerCenter Getting Started is written for the developers and software engineers who are responsible for implementing a data warehouse. It provides a tutorial to help first-time users learn how to use...

    Android代码-android-text

    Android Text Samples These samples show how to work with text in Android. Explore the samples The TextStyling Java and Kotlin samples show how to style text using spans. The RoundedBackground sample ...

    swiftui swift-UI 中文版

    Get started quickly with SwiftUI and Combine reactive programming framework through practice, and master the next generation client UI development technology At WWDC 2019, Apple announced the ...

    Android代码-MaterialDesign风格的Preference页面

    (Currently supporting devices upto api 9 ) Material Preference Library uses com.android.support:preference-v7:x.x.x support library widgets. Also it includes a color chooser dialog widget, that can ...

    pybamm-supporting-material:PyBaMM的支持材料

    "pybamm-supporting-material:PyBaMM的支持材料"这个压缩包包含了PyBaMM框架的相关辅助资料,如幻灯片、海报和论文,为学习和理解PyBaMM提供了一个全面的资源库。 首先,我们来看看这个压缩包中的核心内容。...

Global site tag (gtag.js) - Google Analytics