2. Fragments Tutorial MainActivity - Czech language
Díl 2.
V prvním dile jsme se něco dozvěděli od XML souborech
Používáme příklad i zip porojekt z https://developer.android.com/training/basics/fragments/creating.html
V tomto díle si rozebereme záludnosti v souboru MainActivity.java.
V prvním dile jsme se něco dozvěděli od XML souborech
a taky jaké označení procesoru pro rok 2016 - Intel® VT-x, Intel® EM64T - musí mít PC pro programování v Android Studiu, tedy hlavně pro spuštění emulátoru - virtuálního telefonu, tabletu atd. jinak nebudete moci testovat aplikace na nejnovějších zařízeních, které tento emulátor umí napodobit.
Dole na stránce odkazu je uvedena minimální konfigurace PC, ale protože Android je již plnokrevný OS, který se neustále rozrůstá, tak tyto hodnoty jsou prakticky nedostatečné a je třeba osadit PC nejnovějšími komponentami.
Používáme příklad i zip porojekt z https://developer.android.com/training/basics/fragments/creating.html
V tomto díle si rozebereme záludnosti v souboru MainActivity.java.
// název balíčku
package com.example.android.fragments;
import android.os.Bundle;
// knihovny nutné pro spuštění na starších zařízeních s verzí Androidu API 4
// API verze a příslušné číslo verze Androidu jsou zde
// https://cs.wikipedia.org/wiki/Historie_verz%C3%AD_Android
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
// HeadlinesFragment je třída se seznamem položek, která díky
// OnHeadlineSelectedListener bude vracet události kliknutí na položku
// Pokud při pokusech přídáme jiný soubor se seznamem, je nutno změnit i název HeadlinesFragment
// na nový název, jinak nic neodchytíme!!!!
public class MainActivity extends FragmentActivity
implements HeadlinesFragment.OnHeadlineSelectedListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// tady se rozhoduje zda si vezme XML pro malé obrazovky, jen s jedním panelem, nebo
// velké se dvěma panely
// Rozhoduje si o tom systém sám, ale můžeme to ovlivnit a pdstrčit mu
// i dvoupanel pro testování - viz předchozí díl //android.okhelp.cz/1-fragments-tutorial-xml-czech-language/
setContentView(R.layout.news_articles);
//// VELKE OBRAZOVKY - layout-large - dual panel /////////
// pokud si systém vybere news_articles.xml z layout-large (dual panel)
// budou fragmenty automaticky naloděny do tagů fragment, kde jsou
// uvedeny absolutní cesty fragmentů!!!!
// např. fragment android:name="com.example.android.fragments.HeadlinesFragment"
// si nalodí sám fragment s linkami - položkami ListView.
// Podobně se sám obslouží při nalodění i fragment s obsahem
// fragment android:name="com.example.android.fragments.ArticleFragment"
// Tyto tagy fragment, s absolutní cestou k fragmentu,
// neumožňují výměnu fragmentu za běhu aplikace!!!!!
// Dynamickou výměnu fragmenut však umožňují kontejnery tagu FrameLayout
//// MALE OBRAZOVKY - jen jeden fragment //////
// Zkontrolujeme, který XML byl naloděn, pokud je activováno R.id.fragment_container
// značí to, že byl vybrán XML ze složky layout, kde je pouze jeden panel a do něj
// vložíme pouze fragment se seznamem, tedy HeadlinesFragment a pak po vybrání položky
// v něm otevřeme ArticleFragment.java s vypsáním obsahu článku atd.
if (findViewById(R.id.fragment_container) != null) {
// Pokud obnovujeme seznam položek vrácením se z předchozího stavu - fragmentu
// pak nepotřebujeme nic dělat a měl bychom opustit tento if, jinak
// dojde překrývání fragmentů, tedy uvídíme překryv textů a dalších elementů původního
// fragmentu fragmentem novým proto uděláme podmínku:
if (savedInstanceState != null) {
return;
}
// vytvoříme instanci HeadlinesFragment s položkami seznamu v ListView
HeadlinesFragment firstFragment = new HeadlinesFragment();
// pokud chceme vložit speciální instrukce pro start odebrané z nějakého Intent,
// odchytíme je zde a vložíme je jako argumenty. Pak je při startu fragmentu
// možno odchytit v onCreate()
firstFragment.setArguments(getIntent().getExtras());
// vložíme fragment do fragment_container FrameLayout-u
// který umožňuje výměnu fragmentů
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
// uživatel klikl na nějakou položku ze seznamu v HeadlinesFragment!
public void onArticleSelected(int position) {
// vybereme určitý článek dle pozice položky vybrané v seznamu ListView
// Provedeme kontrolu jestli je naloděn dual panel, nebo jen jednoduchý
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
if (articleFrag != null) {
// VELKÉ OBRAZOVKY
// protože je aktivní id R.id.article_fragment z news_articles.xml v layout-large složce
// víme, že aplikace používá dual-panel, dva fragmenty vedle sebe
// zde se volá funkce která je obsažena v třídě v souboru ArticleFragment.java
// a provede patřičné příkazy, v našem případě se
// vypíše obsah článku z třídy Ipsum.java
// sloužící jako úložiště textů přiřazených k jednotlivým
// pozicím - položkám seznamu ListView
articleFrag.updateArticleView(position);
} else {
// MALÉ OBRAZOVKY
// jen JEDEN-PANEL se zobrazuje - vybrán soubor news_articles.xml v layout složce
// musíme vyměnit fragemnty !!!!
// Vytvoříme fragment a doplníme argumenty - hodnoty, poslané např. z HeadlinesFragment.java
// jedná se nám především o pozici položky, na kterou bylo kliknuto v ListView
// tato pozice bude určující pro výběr obsahu pro ArticleFragment
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Zde vyměníme původní fragment HeadlinesFragment novým fragmentem s obsahem článku atd.
// Můžeme vyměnit fragment za jiný, protože id fragment_container v layout/news_articles.xml je tagu FrameLayout
transaction.replace(R.id.fragment_container, newFragment);
// addToBackStack umožní uživateli vrátit se zpět na seznam položek v HeadlinesFragment.java
transaction.addToBackStack(null);
// celou transakci předáme ke schválení :)
transaction.commit();
}
}
}
396LW NO topic_id
AD
Další témata ....(Topics)
Samsung Galaxy S nejlepší cena od 4 500 KCZ Kč (únor.2012)
Samsung Galaxy S je chytrý telefon s operačním systémem Android.
Samsung Galaxy S je (22.února2012) 5. a 6. nejpoužívanějším chytrým telefonem u programu Sky Map viz tabulka.
Samsung Galaxy S byl představen firmou Samsung v březnu 2010. Je vybaven 1 GHz ARM "Hummingbird - kolibřík" procesorem, 8-16 GB interní flash pamětí, 4-palcovým 480 × 800 pixelů Super AMOLED kapacitním dotykovým displejem, Wi-Fi připojením, 5-megapixelovým fotoaparátem s maximálním rozlišením 2560x1920 a u vybraných modelů předním čelním 0,3 MP fotoaparátem VGA (640x480).
Samsung Galaxy S photo pic image
Zdroj obrázku: wikipedia
Samsung Galaxy S je chytrý telefon s operačním systémem Android.
Samsung Galaxy S je (22.února2012) 5. a 6. nejpoužívanějším chytrým telefonem u programu Sky Map viz tabulka.
Samsung Galaxy S byl představen firmou Samsung v březnu 2010. Je vybaven 1 GHz ARM "Hummingbird - kolibřík" procesorem, 8-16 GB interní flash pamětí, 4-palcovým 480 × 800 pixelů Super AMOLED kapacitním dotykovým displejem, Wi-Fi připojením, 5-megapixelovým fotoaparátem s maximálním rozlišením 2560x1920 a u vybraných modelů předním čelním 0,3 MP fotoaparátem VGA (640x480).
Samsung Galaxy S photo pic image
Zdroj obrázku: wikipedia
Start Stop Stopwatch Timer Android example source code.
private static long mStartTime = 0L;
Calendar cal;
TextView hTextViewVypis = (TextView)findViewById(R.id.idTextVypis);
void start(){
cal = Calendar.getInstance();
mStartTime = cal.getTimeInMillis();
}
void stop(){
prinOutStopWatchTime();
}
private void prinOutStopWatchTime() {
final long start = mStartTime;
cal = Calendar.getInstance();
long stopTime = cal.getTimeInMillis();
long millis = stopTime - start;
long milisekundy = millis % 1000;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
int hour = minutes / 60;
hour = hour % 60;
if (seconds < 10) {
hTextViewVypis.setText(hour + ":" + minutes + ":0" + seconds + ":" + milisekundy);
} else {
hTextViewVypis.setText(hour + ":" + minutes + ":" + seconds + ":" + milisekundy);
}
}
Example have error code:
//developer.android.com/training/basics/fragments/creating.html
Try to change ArticleFragment.java
//developer.android.com/training/basics/fragments/creating.html
Try to change ArticleFragment.java
/*
* Copyright (C) 2012 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
*
* //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.example.android.fragments;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ArticleFragment extends Fragment {
final static String ARG_POSITION = "position";
int mCurrentPosition = -1;
TextView articleText;
@Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
//
// // If activity recreated (such as from screen rotate), restore
// // the previous article selection set by onSaveInstanceState().
// // This is primarily necessary when in the two-pane layout.
// if (savedInstanceState != null) {
// mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
// }
//
// // Inflate the layout for this fragment
// return inflater.inflate(R.layout.article_view, container, false);
// }
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// If activity recreated (such as from screen rotate), restore
// the previous article selection set by onSaveInstanceState().
// This is primarily necessary when in the two-pane layout.
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
}
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.article_view, container, false);
articleText = (TextView) rootView.findViewById(R.id.article);
return rootView;
}
@Override
public void onStart() {
super.onStart();
// During startup, check if there are arguments passed to the fragment.
// onStart is a good place to do this because the layout has already been
// applied to the fragment at this point so we can safely call the method
// below that sets the article text.
Bundle args = getArguments();
if (args != null) {
// Set article based on argument passed in
updateArticleView(args.getInt(ARG_POSITION));
} else if (mCurrentPosition != -1) {
// Set article based on saved instance state defined during onCreateView
updateArticleView(mCurrentPosition);
}
}
public void updateArticleView(int position) {
//TextView article = (TextView) getActivity().findViewById(R.id.article); //Error: article=null.
if (articleText != null)
articleText.setText(Ipsum.Articles[position]);
mCurrentPosition = position;
}
/* ERROR public void updateArticleView(int position) {
TextView article = (TextView) getActivity().findViewById(R.id.article);
article.setText(Ipsum.Articles[position]);
mCurrentPosition = position;
}*/
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the current article selection in case we need to recreate the fragment
outState.putInt(ARG_POSITION, mCurrentPosition);
}
}
Set in AndroidManifest.xml android:theme="@android:style/Theme.NoTitleBar" AndroidManifest.xml example source code.
AndroidManifest.xml
AndroidManifest.xml
<manifest xmlns:android="//schemas.android.com/apk/res/android"
package="com.myexample.without_titlebar">
<application android:label="My app">
<activity android:name="NoTitleBar"
android:theme="@android:style/Theme.NoTitleBar"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Problem: erroneous entry of id
Solution: @+id/
<RadioButton android:id="idRadio"
android:text="My radio button"/>
Solution: @+id/
<RadioButton android:id="@+id/idRadio"
android:text="My radio button"/>
Editace: 2016-06-28 14:36:04
Počet článků v kategorii: 396
Url:2-fragments-tutorial-mainactivity-czech-language