20170309
package com.example.wata.myapplication;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BlankFragment blankFragment=BlankFragment.newInstance(10);
FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(
R.id.activity_main,
blankFragment,
blankFragment.getTag()
).commit();
}
public void onFragmentInteraction(String data) {
Toast.makeText(this,data,Toast.LENGTH_LONG).show();
}
}
//
package com.example.wata.myapplication;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class BlankFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private int mParam1;
private OnFragmentInteractionListener mListener;
public BlankFragment() {
}
public static BlankFragment newInstance(int param1) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (getArguments() != null) {
mParam1 = getArguments().getInt(ARG_PARAM1);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Integer total =mParam1*77;
onButtonPressed(total.toString());
return inflater.inflate(R.layout.fragment_blank, container, false);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
public void onButtonPressed(String data) {
if (mListener != null) {
mListener.onFragmentInteraction(data);
}
}
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(String data);
}
}
20161028
Display a Fragment within a Activity
1//New->Fragmentでfragmentを追加、CalendarViewなどをDrag and Dropしてもいい
2//MainActivityは
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BlankFragment blankFragment=new BlankFragment();
getSupportFragmentManager().beginTransaction().add(R.id.activity_main,blankFragment).commit();
}
を追加
20161026
BlankFragmentにButtonを置く
New->BlankFragment->fragment_blank.xmlでRelativeLayoutにしてeditText2こ、button1個を置く
//MainActivity.java
package com.example.kunihiro.myapplication;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
BlankFragment blankFragment=new BlankFragment();
FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_main,blankFragment,blankFragment.getTag()).commit();
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
//BlankFragment.java
package com.example.kunihiro.myapplication;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* A simple {@link Fragment} subclass.
*/
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
EditText editText1,editText2;
Button button;
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_blank, container, false);
editText1=(EditText)view.findViewById(R.id.editText);
editText2=(EditText)view.findViewById(R.id.editText2);
button=(Button)view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
if(editText1.getText().toString().equals("yama")&&editText2.getText().toString().equals("kawa")) {
Toast.makeText(BlankFragment.this.getActivity(), "Correct", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(BlankFragment.this.getActivity(), "Incorrect", Toast.LENGTH_LONG).show();
}
}
});
return view;
}
}
20161025
Fragmentがaddされた時点でonAttachが呼び出される。
private OnFragmentInteractionListener mListener;
を public BlankFragment() { }の前に宣言しておいて
public interface OnFragmentInteractionListener {
void onFragmentInteraction(String data);
}
で
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
Flagmentで定義されたinterfaceをActivityに実装する
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener ,BlankFragment.OnFragmentInteractionListener{
メソッドを実装する
public void onFragmentInteraction(String data) {
Toast.makeText(this,data,Toast.LENGTH_LONG).show();
}
Fragment の側からActivityに渡すことが可能になる
Fragment 側で
public void onButtonPressed(String data) {
if (mListener != null) {
mListener.onFragmentInteraction(data);
}
}
20161025
1//
New->BlankFragment
include fragment factory methods?
include interface callbacks?
両方にチェックを入れる。
2//
MainActivity.java は
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener ,BlankFragment.OnFragmentInteractionListener{
OnFragmentInteractionListenerを追加する
implement methods で onFlagmentInteractionを生成
public void onFragmentInteraction(String data) {
Toast.makeText(this,data,Toast.LENGTH_LONG).show();
}
に変更
//3
} else if (id == R.id.nav_share) {
BlankFragment blankFragment=BlankFragment.newInstance(5);
FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(
R.id.content_main,
blankFragment,
blankFragment.getTag()
).commit();
}
をコピペする
//4
BlankFlagment.javaは
public class BlankFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private int mParam1;
mParam1をStringからintに変更
//5
public static BlankFragment newInstance(int param1) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
に変更
//6
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getInt(ARG_PARAM1);
}
}
に変更
//7
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Integer total =mParam1*5;
onButtonPressed(total.toString());
return inflater.inflate(R.layout.fragment_blank, container, false);
}
に変更
//8
public void onButtonPressed(String data) {
if (mListener != null) {
mListener.onFragmentInteraction(data);
}
}
に変更
//9
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String data);
}
に変更
//すべてのコード
YouTubeで解説されたコード
//MainActivity.java
package com.example.kunihiro.myapplication;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener ,BlankFragment.OnFragmentInteractionListener{
//Fragment をActivityMainで利用するにはBlankFragment.OnFragmentInteractionListenerを実装することが必要になる
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
BlankFragment blankFragment=BlankFragment.newInstance(7);
//Fragmentに値を渡すにはnewInstanceメソッドを実装し受け渡しをする。
FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(
R.id.content_main,
blankFragment,
blankFragment.getTag()
).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
// FragmentからActivityに対してメッセージを送りたい場合が結構あります。
//その場合はinterfaceを使用します。Fragment内で作ったinterfaceを
// //管理しているAvtivityでimplementsすることによりメッセージを送ることが可能になります。
//OnFragmentInteractionListenerを以下の様な形に実装する
public void onFragmentInteraction(String data) {
Toast.makeText(this,data,Toast.LENGTH_LONG).show();
}
}
//BlankFragment.java
package com.example.kunihiro.myapplication;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class BlankFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private int mParam1;
private OnFragmentInteractionListener mListener;
public BlankFragment() {
}
public static BlankFragment newInstance(int param1) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getInt(ARG_PARAM1);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Integer total =mParam1*6;
onButtonPressed(total.toString());
return inflater.inflate(R.layout.fragment_blank, container, false);
}
public void onButtonPressed(String data) {
if (mListener != null) {
mListener.onFragmentInteraction(data);
}
}
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
//FragmentからActivityに対してメッセージを送くる
//onFragmentInteractionはMainActivityで実装されている。
void onFragmentInteraction(String data);
}
}
20161020
Navigation Drawer Activityで
New->Flagmentでinclude fragment factory methods?にチェックを入れてFragmentを追加し、"some1","some2"などのデータ使わない時。
if (id == R.id.nav_camera) {
BlankFragment blankFragment=BlankFragment.newInstance("some1","some2");
FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(
R.id.content_main,
blankFragment,
blankFragment.getTag()
).commit();
fragment_blank.xmlにCalendarViewを配置すれば、CalendarViewが表示される。
データを表示するときはBlankFragment.javaを以下のように追加する。
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("TAG", mParam1);
Log.d("TAG", mParam2);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
20161017
//1
New->Fragment
include fragment factory methods?
include interface callbacks?
のチェックを外す。
BlankFragment1,BlankFragment2 2個のFragmentを作る。
fragment_blank_fragment1.xml にTimePickerを入れる。
fragment_blank_fragment2.xml にDatePickerを入れる。
//2
MainActivity.java
を以下のようにする。
if (id == R.id.nav_camera) {
BlankFragment1 blankFragment1=new BlankFragment1();
FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_main,
blankFragment1,
blankFragment1.getTag()).commit();
} else if (id == R.id.nav_gallery) {
BlankFragment2 blankFragment2=new BlankFragment2();
FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_main,
blankFragment2,
blankFragment2.getTag()).commit();
//3
transaction.replace(R.id.fragment_container, newFragment);
第1引数はFragmentが入るViewのID、第2引数は挿入するFragmentです。
第1引数 R.id.relativelayout_for_fragmentはcontent_main.xmlの
android:id="@+id/relativelayout_for_fragment"である。
replace
FragmentTransaction replace (int containerViewId,
Fragment fragment,
String tag)
Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.
Parameters
containerViewId int: Identifier of the container whose fragment(s) are to be replaced.
fragment Fragment: The new fragment to place in the container.
tag String: Optional tag name for the fragment, to later retrieve the fragment with FragmentManager.findFragmentByTag(String).
Returns
FragmentTransaction Returns the same FragmentTransaction instance.
getTag
Added in API level 11
String getTag ()
Get the tag name of the fragment, if specified.
replace(R.id.relativelayout_for_fragment,
cameraFragment,
cameraFragment.getTag())でcameraFragment.getTag()を削除しても動作する。
if (id == R.id.nav_camera) {
以外の新しいFragmentを作成しないと、画面が変わらない。
20161010
//ListFragment Intent
//manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kunihiro.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:parentActivityName=".MainActivity"
android:name=".SubActivity"
android:label="@string/title_activity_sub"
android:theme="@style/AppTheme.NoActionBar"></activity>
</application>
</manifest>
//DetailFragment.java
package com.example.kunihiro.myapplication;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by kunihiro on 2016/10/10.
*/
public class DetailFragment extends android.support.v4.app.Fragment {
public DetailFragment(){}
public static DetailFragment newInstance(int position){
DetailFragment detailFragment=new DetailFragment();
Bundle args=new Bundle();
args.putInt("position",position);
detailFragment.setArguments(args);
return detailFragment;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){
View detailView =inflater.inflate(R.layout.view_detail,container,false);
((TextView)detailView.findViewById(R.id.detailText))
.setText(News.Details[getArguments().getInt("position")]);
return detailView;
}
}
//MainActivity.java
package com.example.kunihiro.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
//News.java
package com.example.kunihiro.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
//SubActivity.java
package com.example.kunihiro.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class SubActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
int position=getIntent().getIntExtra(TitlesFragment.EXTRA_POSTION,0);
DetailFragment detailFragment=DetailFragment.newInstance(position);
getSupportFragmentManager()
.beginTransaction()
.add(R.id.detailFrame,detailFragment)
.commit();
}
}
//TitlesFragment.java
package com.example.kunihiro.myapplication;
import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Created by kunihiro on 2016/10/10.
*/
public class TitlesFragment extends ListFragment {
public final static String EXTRA_POSTION="com.example.kunihiro.myapplication.POSITION";
public TitlesFragment(){}
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_list_item_1,
News.Titles
));
}
public void onListItemClick(ListView l, View v,int position,long id){
super.onListItemClick(l,v,position,id);
Intent intent =new Intent(getActivity(),SubActivity.class);
intent.putExtra(EXTRA_POSTION,position);
startActivity(intent);
}
}
//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.kunihiro.myapplication.MainActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/titlesFragment"
android:name="com.example.kunihiro.myapplication.TitlesFragment"></fragment>
</LinearLayout>
//activity_sub.xml
<?xml version="1.0" encoding="utf-8"?>
<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:fitsSystemWindows="true"
tools:context="com.example.kunihiro.myapplication.SubActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/detailFrame"
android:padding="16dp">
</FrameLayout>
</LinearLayout>
//content_sub.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/content_sub"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.kunihiro.myapplication.SubActivity"
tools:showIn="@layout/activity_sub">
</RelativeLayout>
//view_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/detailText">
</TextView>
20161009
Fragment 1個
//MainActivity.java
package com.example.kunihiro.myapplication;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment1 fragment1 = new Fragment1();
fragmentTransaction.replace(R.id.frag, fragment1);
fragmentTransaction.commit();
}
}
//Fragment1.java
MainActivityと同じ階層にNew->javaClassで作成する
package com.example.kunihiro.myapplication;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container,false);
}
}
//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:id="@+id/frag"
tools:context="com.example.kunihiro.myapplication.MainActivity" >
</FrameLayout>
//fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="60dp"
android:text="fragment1" />
</LinearLayout>
20161009
FragmentOne FragmentTwo Button 解説つき
//MainActivity
package com.example.kunihiro.myapplication;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import layout.FragmentOne;
import layout.FragmentTwo;
//javaホルダーの直下にlayoutフォルダーを作成して、中にFragmentOne.java FragmentOne.javaを置く
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ChangeFragment(View view){
android.app.Fragment fragment;
if(view == findViewById(R.id.button1)){
//// FragmentManagerからFragmentTransactionを作成
FragmentManager fm=getFragmentManager();
android.app.FragmentTransaction ft=fm.beginTransaction();
// 実際に使用するFragmentの作成
fragment = new FragmentOne();
// Fragmentを組み込む
// 第1引数はFragmentが入るViewのID、第2引数は挿入するFragmentです
//R.id.fragment_placeはactivity_mainの中にある
/* <fragment
android:name="layout.FragmentOne"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment_place"
tools:layout="@layout/fragment_fragment_one"></fragment>*/
ft.replace(R.id.fragment_place,fragment);
// 上記の変更を反映する
ft.commit();
}
if(view == findViewById(R.id.button2)){
fragment = new FragmentTwo();
FragmentManager fm=getFragmentManager();
android.app.FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.fragment_place,fragment);
ft.commit();
}
}
}
//FragmentOne.java
package layout;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.kunihiro.myapplication.R;
public class FragmentOne extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_one, container, false);
}
}
//FragmentTwo.java
package layout;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.kunihiro.myapplication.R;
public class FragmentTwo extends android.app.Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_two, container, false);
}
}
//avtivity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.kunihiro.myapplication.MainActivity"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fragment1"
android:id="@+id/button1"
android:onClick="ChangeFragment" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fragment2"
android:id="@+id/button2"
android:onClick="ChangeFragment" />
<!--defalt layout.FragmentOne android:name="layout.FragmentOne" -->
<fragment
android:name="layout.FragmentOne"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment_place"
tools:layout="@layout/fragment_fragment_one"></fragment>
</LinearLayout>
//fragment_fragment_one.xml
<FrameLayout
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"
tools:context="layout.FragmentOne"
android:background="#ca3412">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="40dp"
android:text="FragmentOne" />
</FrameLayout>
//fragment_fragment_two.xml
<FrameLayout 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"
tools:context="layout.FragmentTwo"
android:background="#00FF00">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="40sp"
android:text="FragmentTwo" />
</FrameLayout>
20160920
DevelopersからダウンロードしたFragment
//ArticleFragment.java//
package com.example.kunihiro.myapplication;
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;
@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);
}
@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);
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);
}
}
//HeadlinesFragment.java//
package com.example.kunihiro.myapplication;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;
// The container Activity must implement this interface so the frag can deliver messages
public interface OnHeadlineSelectedListener {
/** Called by HeadlinesFragment when a list item is selected */
public void onArticleSelected(int position);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We need to use a different list item layout for devices older than Honeycomb
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;
// Create an array adapter for the list view, using the Ipsum headlines array
setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));
}
@Override
public void onStart() {
super.onStart();
// When in two-pane layout, set the listview to highlight the selected list item
// (We do this during onStart because at the point the listview is available.)
if (getFragmentManager().findFragmentById(R.id.article) != null) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Notify the parent activity of selected item
mCallback.onArticleSelected(position);
// Set the item as checked to be highlighted when in two-pane layout
getListView().setItemChecked(position, true);
}
}
//Ipsum.java//
package com.example.kunihiro.myapplication;
public class Ipsum {
static String[] Headlines = {
"Article One",
"Article Two"
};
static String[] Articles = {
"Article One\n\nExcepteur pour-over occaecat squid biodiesel umami gastropub, " +
"nulla laborum salvia dreamcatcher fanny pack. Ullamco culpa retro ea, " +
"trust fund excepteur eiusmod direct trade banksy nisi lo-fi cray messenger bag. " +
"Nesciunt esse carles selvage put a bird on it gluten-free, " +
"wes anderson ut trust fund twee occupy viral. " +
"Laboris small batch scenester pork belly, leggings ut farm-to-table aliquip yr" +
" nostrud iphone viral next level. Craft beer dreamcatcher pinterest truffaut ethnic, " +
"authentic brunch. Esse single-origin coffee banksy do next level tempor. Velit synth " +
"dreamcatcher, magna shoreditch in american apparel messenger bag narwhal PBR ennui " +
"farm-to-table.",
"Article Two\n\nVinyl williamsburg non velit, master cleanse four loko banh mi. " +
"Enim kogi keytar trust fund pop-up portland gentrify. Non ea typewriter dolore deserunt " +
"Austin. Ad magna ethical kogi mixtape next level. Aliqua pork belly thundercats, " +
"ut pop-up tattooed dreamcatcher kogi accusamus photo booth irony portland. Semiotics " +
"brunch ut locavore irure, enim etsy laborum stumptown carles gentrify post-ironic cray. " +
"Butcher 3 wolf moon blog synth, vegan carles odd future."
};
}
//MainActivity.java//
package com.example.kunihiro.myapplication;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends FragmentActivity
implements HeadlinesFragment.OnHeadlineSelectedListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
// Check whether the activity is using the layout version with
// the fragment_container FrameLayout. If so, we must add the first fragment
//news_articles で定義 android:id="@+id/fragment_container"
if (findViewById(R.id.fragment_container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
// Create an instance of ExampleFragment
HeadlinesFragment firstFragment = new HeadlinesFragment();
// In case this activity was started with special instructions from an Intent,
// pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment
// Capture the article fragment from the activity layout
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article);
//article_view.xmlで定義 android:id="@+id/article"
if (articleFrag != null) {
// If article frag is available, we're in two-pane layout...
// Call a method in the ArticleFragment to update its content
articleFrag.updateArticleView(position);
} else {
// If the frag is not available, we're in the one-pane layout and must swap frags...
// Create fragment and give it an argument for the selected article
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
//article_view.xml//
<?xml version="1.0" encoding="UTF-8"?>
<TextView android:textSize="18sp"
android:padding="16dp"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/article"
xmlns:android="http://schemas.android.com/apk/res/android"/>
//fragment_article.xml//
<FrameLayout 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"
tools:context="com.example.kunihiro.myapplication.ArticleFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
//news_articles.xml//
<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/fragment_container"
xmlns:android="http://schemas.android.com/apk/res/android"
/>
20160919
Youtubeを見て作成したFragment
//MainActivity.java//
package com.example.kunihiro.myapplication;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import layout.FragmentOne;
import layout.FragmentTwo;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ChangeFragment(View view){
android.app.Fragment fragment;
if(view == findViewById(R.id.button)){
fragment = new FragmentOne();
FragmentManager fm=getFragmentManager();
android.app.FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.fragment_place,fragment);
ft.commit(); }
if(view == findViewById(R.id.button2)){
fragment = new FragmentTwo();
FragmentManager fm=getFragmentManager();
android.app.FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.fragment_place,fragment);
ft.commit();
}
}
}
//FragmentOne.java//
NEW->Fragment で作成
package layout;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.kunihiro.myapplication.R;
public class FragmentOne extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_one, container, false);
}
}
//FragmentTwo.java//
NEW->Fragment で作成
package layout;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.kunihiro.myapplication.R;
public class FragmentTwo extends android.app.Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_two, container, false);
}
}
//activity_main.xml//
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.kunihiro.myapplication.MainActivity"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fragment1"
android:id="@+id/button"
android:onClick="ChangeFragment" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fragment2"
android:id="@+id/button2"
android:onClick="ChangeFragment" />
<!--defalt layout.FragmentOne android:name="layout.FragmentOne" -->
<fragment
android:name="layout.FragmentOne"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment_place"
tools:layout="@layout/fragment_fragment_one"></fragment>
</LinearLayout>
//fragment_fragment_one.xml//
<FrameLayout
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"
tools:context="layout.FragmentOne"
android:background="#ca3412">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="40dp"
android:text="FragmentOne" />
</FrameLayout>
//fragment_fragment_two.xml//
<FrameLayout 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"
tools:context="layout.FragmentTwo"
android:background="#00FF00">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="40sp"
android:text="FragmentTwo" />
</FrameLayout>
20160919
//MainActivity.java//
package com.example.kunihiro.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
//MyFragment.java////
package com.example.kunihiro.myapplication;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class MyFragment extends Fragment {
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
// 引数で渡ってきたinflaterを使ってレイアウトをinfrateする
//inflate: 拡張する,膨張させる 吹き込む
//メインのlayoutに別のレイアウトを動的に挿入することができる
final View layout = inflater.inflate(R.layout.my_fragment, container);
// 必要に応じてUIにコールバックを設定する
layout.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getContext(), "Hello Fragment!!", Toast.LENGTH_SHORT).show();
}
});
// infrateされたViewをそのまま返す
return layout;
}
}
//activity_main.xml/////////
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.kunihiro.myapplication.MainActivity">
<fragment
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:name="com.example.kunihiro.myapplication.MyFragment"
android:id="@+id/fragment"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
//my_fragment.xml////////////
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is my fragment!"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>