Android Development 3, 4 weeks--criminallntent project

Source: Internet
Author: User


Introduction of Criminalintent Project development 1.fragment


Using fragment instead of activity to manage the app UI, you can circumvent the limitations of the Android system activity usage rules.



Fragment is a controller object that the activity can delegate to accomplish some tasks.



These tasks are typically administrative user interfaces. The managed user interface can be part of a full screen or a full screen. Fragment, which manages the user interface, is also known as UI fragment.



It also has a view that is generated from the layout file itself. The fragment view contains visual UI elements that users can interact with.



With fragment, you can easily select different list items to display the corresponding detail view the activity is responsible for replacing one detail fragment with another, as shown in the fragment,1.1.



In this way, the activity is not destroyed during the view switching process.






Figure 1.1


2.fragment and Support Library


We will use two important support library classes, one is the Fragment class (Android.support.v4.app.Fragment).



The other is the Fragmentactivity class (android.support.v4.app.fragment-activity).



The premise of using fragment is that activity knows how to manage fragment, fragmentactivity classes know how to manage supported versions of fragment.


3. Define the container view to create the Fragment container layout (Activity_crime.xml) as follows
<
FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
4. Define the Crimefragment layout


The Crimefragment view displays information that is contained in an instance of the crime class.



The layout includes a vertical linearlayout layout that contains a edittext component.



The EditText component has an area where users can add or edit text messages.


The layout file for the Fragment view (Fragment_crime.xml) is as follows
<
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<
EditText android:id="@+id/crime_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/crime_title_hint"
/>
</LinearLayout>
5. Create the Crimefragment class inheritance fragment Class (Crimefragment.java) as follows
public class Crimefragment extends Fragment {}


When modifying code to inherit the fragment class, we need to select the fragment (Android.support.v4.app) package


6. Implement the Fragment Life cycle overlay Fragment.oncreate (Bundle) method (Crimefragment.java) as follows
public class CrimeFragment extends Fragment {
private Crime mCrime;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCrime = new Crime();
}
}


Fragment.oncreate (bundle) is a public method, and Activity.oncreate (bundle) is a protection method.



This is because only fragment.oncreate (...) Methods and other fragment life-cycle methods are public methods that are managed by the fragment activity to invoke them.


7. Cover Oncreateview (...) Method (Crimefragment.java) is as follows
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, container, false);
return v;
}


In Oncreateview (...) method, the fragment view is directly by calling Layoutinflater.inflate (...). Method and generates the resource ID of the incoming layout.



The second parameter is the parent view of the view because we usually need the parent view to properly configure the component.



The third parameter tells the layout builder whether to add the resulting view to the parent view (here we pass the false parameter because we will add the view as the activity code.) )


8. In fragment, the associated component is generated and uses the EditText component (Crimefragment.java) as follows
public class CrimeFragment extends Fragment {
private Crime mCrime;
private EditText mTitleField;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
  View v = inflater.inflate(R.layout.fragment_crime, container, false);
  mTitleField = (EditText)v.findViewById(R.id.crime_title);
  mTitleField.addTextChangedListener(new TextWatcher() {
  @Override
  public void beforeTextChanged(
  CharSequence s, int start, int count, int after) {
  // This space intentionally left blank
}
@Override
public void onTextChanged(
CharSequence s, int start, int before, int count) {
mCrime.setTitle(s.toString());
}

@Override
public void afterTextChanged(Editable s) {
// This one too
}
});
return v;
}
}


Fragment.oncreateview (...) The component reference in the method is almost identical to the activity.oncreate (...) The processing of the method. The only difference is that we call the View.findviewbyid (int) method of the Fragment view.


9. Add UI fragment to Fragmentmanager


The Fragmentmanager categories are specifically managed by:



? Fragment queue;



? Fragment transaction fallback stack.


Get Fragmentmanager (Crimeactivity.java) as follows
Fragmentmanager fm = Getsupportfragmentmanager ();
Add a crimefragment (Crimeactivity.java) as follows
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = new CrimeFragment();
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}


The fragment transaction is used to add, remove, attach, detach, or replace fragment in the fragment queue. This is the key to using fragment to assemble and reassemble the user interface at run time.



The Fragmentmanager manages the fallback stack for fragment transactions.


10. Creating a user interface using layouts and components


Opens the Crime.java file, adding two instance variables.



The date variable represents the time that crime occurred, and the Boolean variable indicates whether crime has been processed.


Add more variables (Crime.java) as follows
private Date mDate;
private boolean mSolved;
public Crime() {
mId = UUID.randomUUID();
mDate = new Date();
}
Add a new component (Fragment_crime.xml) as follows


Add four components to the Crimefragment layout: Two TextView components, one button component, and one checkbox component


 

<
TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/crime_title_label"
style="?android:listSeparatorTextViewStyle"
/>
<
EditText android:id="@+id/crime_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:hint="@string/crime_title_hint"
/>
<
TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/crime_details_label"
style="?android:listSeparatorTextViewStyle"
/>
<
Button android:id="@+id/crime_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
/>
<CheckBox android:id="@+id/crime_solved"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:text="@string/crime_solved_label"
/>
Add string resource (Strings.xml) as follows
<string name= "Crime_title_label" >title</string>
<string name= "Crime_details_label" >Details</ String>
<string name= "Crime_solved_label" >Solved</string>
Add component instance variable (Crimefragment.java) as follows


Next, let the checkbox show if crime has been processed. The status value of the msolved variable of the crime will also be updated when the user ticked the checkbox cleared.


Private Button mdatebutton;
private CheckBox Msolvedcheckbox;
Set the text display on the button (Crimefragment.java) as follows
Mdatebutton = (Button) V.findviewbyid (r.id.crime_date); 
Mdatebutton.settext (Mcrime.getdate (). toString ()); 
Mdatebutton.setenabled (FALSE);


Disabling a button ensures that it does not respond to a user's Click event. When disabled, the appearance style of the button changes (grayed out), indicating that it is disabled.


The change in Listen checkbox State (Crimefragment.java) is as follows
mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Set the crime‘s solved property
mCrime.setSolved(isChecked);
}
});


You need to import Android.widget.CompoundButton packages when creating Oncheckedchangelistener.


11. Using Recyclerview


First to import the RECYCLERVIEW-V7 support library


Add the Recyclerview view (fragment_crime_list.xml) to the layout file as follows
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/crime_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
The configuration view for Crimelistfragment (Crimelistfragment.java) is as follows
private RecyclerView mCrimeRecyclerView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mCrimeRecyclerView = (RecyclerView) view
.findViewById(R.id.crime_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}


The task of the Recyclerview class is to recycle and to locate the TextView view on the screen.



In fact, the targeted task was delegated to LayoutManager.



In addition to locating list items on the screen, LayoutManager is also responsible for defining the scrolling behavior of the screen.



Therefore, no layoutmanager,recyclerview will not work properly.


12. Start activity from fragment


In Crimelistfragment's Crimeholder class, replace the toast message processing code with the code that launches the Crimeactivity instance.


Start Crimeactivity (Crimelistfragment.java) as follows
Intent Intent = new Intent (getactivity (), crimeactivity.class); 
startactivity (Intent);
13. Using Viewpager


After adding Viewpager to the UI, users can swipe the screen to switch to the detail page of different list items.


Create Viewpager (Crimepageractivity.java) as follows
public class CrimePagerActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);
}
}


Note: You must use Viewpager's package name (Android.support.v4.view.ViewPager). As shown in 13.1.



Figure 13.1


Set Pager Adapter (Crimepageractivity.java) as follows
public class CrimePagerActivity extends FragmentActivity {
  private ViewPager mViewPager;
  private List<Crime> mCrimes;
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_crime_pager);
  mViewPager = (ViewPager) findViewById(R.id.activity_crime_pager_view_pager);
  mCrimes = CrimeLab.get(this).getCrimes();
  FragmentManager fragmentManager = getSupportFragmentManager();
  mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
  @Override
  public Fragment getItem(int position) {
  Crime crime = mCrimes.get(position);
  return CrimeFragment.newInstance(crime.getId());
  }
@Override
  public int getCount() {
return mCrimes.size();
  }
});
}
}


After finding Viewpager in the activity view, we get the dataset from Crimelab (List of crime) and get the Fragmentmanager instance of the activity.



Set adapter as an anonymous instance of Fragmentstatepageradapter. Creating an Fragment-statepageradapter instance requires Fragmentmanager.


Create the Newintent method (Crimepageractivity.java) as follows
private static final String EXTRA_CRIME_ID =
"com.bignerdranch.android.criminalintent.crime_id";
public static Intent newIntent(Context packageContext, UUID crimeId) {
Intent intent = new Intent(packageContext, CrimePagerActivity.class);
intent.putExtra(EXTRA_CRIME_ID, crimeId);
return intent;
}
UUID crimeId = (UUID) getIntent()
.getSerializableExtra(EXTRA_CRIME_ID);


You then need to modify crimelistfragment so that when the user clicks a list item, Crimelistfragment starts the crimepageractivity instance.


Configuring Startup Crimepageractivity (Crimelistfragment.java)
Intent Intent = crimepageractivity.newintent (Getactivity (), Mcrime.getid ());


Android Development 3, 4 weeks--criminallntent project


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.