Android DialogFragmentの例
ダイアログを作成する最も柔軟な方法は、andorid.app.Dialogクラスを使うことではなく、DialogFragmentクラスを使うことです。これにより、ViewModels を利用するだけでなく、ダイアログのライフサイクルを観察する能力を含む、完全な Fragment 機能を得ることができます。
DialogFragment とは何ですか?
DialogFragmentは、activityのウィンドウの上にダイアログウィンドウを表示するfragmentです。この fragment にはダイアログオブジェクトが含まれており、fragment` の状態に応じて適切に表示されます。
このクラスでは、フレームワークのandroid.app.dialogFragmentがAPIレベル28で非推奨となったため、dialogfragmentというサポートを使用しています。
私たちの実装では、このクラスをオーバーライドして
onCreateView(LayoutInflater, ViewGroup, Bundle)を実装し、ダイアログのコンテンツを提供します。あるいは、onCreateDialog(Bundle)をオーバーライドして、独自のコンテンツを持つAlertDialogのような、完全にカスタム化されたダイアログを作成することもできます。
この記事では、以下のことを学んでいきます。
- kotlinでListViewを使ったダイアログを作成する。
DialogFragmentを使用して、AlertDialogや入力ダイアログなどのカスタムレイアウトのダイアログを作成する。
- ポップアップメニューの作成
(a). Kotlin Android DialogFragment with ListView
Kotlin Android DialogFragment with ListView tutorial.
シンプルなボタンがクリックされたときに、DialogFragmentを開く方法を見てみましょう。dialogFragmentはタイトルとリストビューで構成されています。
実際には,xmlのレイアウト仕様からLayoutInflaterクラスを介して膨らませています。
ユーザがリストビューのアイテムをクリックすると、それをトーストに表示します。ユーザーがDialogFragmentの外をクリックすると、それ(DialogFragment)を解除します。
それでは、行ってみましょう。
ビデオチュートリアル
これに代わるものとして、ビデオチュートリアルがあります。もし、このようなチュートリアルがお好きでしたら、私たちのYouTubeチャンネルを購読していただくと良いと思います。基本的に私たちはプログラミングのためのテレビを持っており、そこでは毎日、特にアンドロイドのチュートリアルを行っています。
Kotlin Android DialogFragment with Simple ListView
完全な例を見てみましょう。
ツール
- IDE。Android Studio - Jetbrains社とGoogle社がサポートしているandroidの公式IDEです。
- 言語:Kotlin - Jetbrains社が初めて開発した静的型付け言語。
- エミュレータ : Nox Player - 私の遅いマシンでも十分に速いエミュレータです。
Gradle Scripts
まずは、gradleスクリプトの探索から始めます。
(a). build.gradle(App)
これは、アプリレベルの build.gradle ファイルです。ここには依存関係を追加するdependencies DSLがあります。
このファイルは、プロジェクトのappフォルダにあるので、appレベルのbuild.gradleと呼ばれています。
Android Studioのバージョン3以上を使用している場合は、implementationキーワードを使用し、3未満のバージョンを使用している場合は、compileキーワードを使用します。
この build.gradle ファイルを修正したら、プロジェクトを同期する必要があります。Android Studioがそのように促してくれます。
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 28
defaultConfig {
applicationId "info.camposha.kotlindialogfragment"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0-rc01'
}
また、build.gradleファイルの中で、2つのkotlin固有のプラグインを適用することから始めていることがわかります。
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
つまり、kotlin-androidとkotlin-android-extensionsです。
Kotlinのコード
Androidアプリは主にJavaやKotlinで書くことができます。しかし、最近ではFlutterのようにDartのような言語を使ったフレームワークも多くあります。
このクラスでは、Kotlinプログラミング言語を使用します。
私たちのプロジェクトでは、これらのクラスを使用します。
(a). パイオニアフラグメント.kt
FragmentDialogを表すクラスで、実際にはこれから派生します。
1. DialogFragment`の作成
まず、android.support.v4.app.DialogFragmentから派生したKotlinクラスを作成します。なお、android.app.DialogFragmentは非推奨なので、サポートライブラリのfragmentを使用します。
class PioneersFragment : DialogFragment() {..}
上記の記述では、DialogFragmentのデフォルトの空のコンストラクタが含まれていることに注意してください。これにはKotlinのブラケット(())を使用しています。
2. 2. DialogFragment の OnCreateView()をオーバーライドする。
次に、FragmentクラスのonCreateView()メソッドをオーバーライドします。
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {..}
3つのパラメータを渡しています。
- LayoutInflaterオブジェクト。
- ViewGroup オブジェクト。
- Bundle オブジェクト。
**3. レイアウトを DialogFragment にインフレーションする***。
このメソッドでは、まず inflate メソッドで R.layout.fraglayout のレイアウトを、LayoutInflater インスタンスを使ってインフレーションします。
val rootView = inflater.inflate(R.layout.fraglayout, container)
4. Kotlin配列の作成。
次に、arrayOf()メソッドを使って、Kotlinの配列を作成します。これがパイオニアをホストするためのデータソースとなります。これが、DialogFragmentで表示するListViewにバインドされることになります。
var pioneers = arrayOf("Dennis Ritchie", "Rodney Brooks", "Sergey Brin", "Larry Page", "Cynthia Breazeal", "Jeffrey Bezos", "Berners-Lee Tim", "Centaurus A", "Virgo Stellar Stream")
5. ArrayAdapterを使ってListViewをKotlinの配列にバインドする。
次に、ListViewを参照し、アダプタを設定します。ここではarrayadapterを使います。
val myListView = rootView.findViewById(R.id.myListView) as ListView
myListView!!.adapter = ArrayAdapter<String>(activity, android.R.layout.simple_list_item_1, pioneers)
6. ダイアログフラグメント`のタイトルを設定する。
setTitle()メソッドを使って、DialogFragment`のタイトルを設定します。このメソッドには文字列を渡します。
this.dialog.setTitle("Tech Pioneers")
7. KotlinでListViewのClickイベントを聞く。
ListViewがクリックされたときに、クリックされたアイテムを表示して、Toastメッセージを表示したいとします。
myListView.setOnItemClickListener {
adapterView,
view,
position,
l
-> Toast.makeText(activity, pioneers[position], Toast.LENGTH_SHORT).show()
}
ここでは、PioneersFragmentクラスのフルコードを紹介します。
package info.camposha.kotlindialogfragment
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
class PioneersFragment : DialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fraglayout, container)
var pioneers = arrayOf("Dennis Ritchie", "Rodney Brooks", "Sergey Brin", "Larry Page", "Cynthia Breazeal", "Jeffrey Bezos", "Berners-Lee Tim", "Centaurus A", "Virgo Stellar Stream")
val myListView = rootView.findViewById(R.id.myListView) as ListView
//with arrayadapter you have to pass a textview as a resource, and that is simple_list_item_1
myListView!!.adapter = ArrayAdapter<String>(activity, android.R.layout.simple_list_item_1, pioneers)
this.dialog.setTitle("Tech Pioneers")
myListView.setOnItemClickListener {
adapterView,
view,
position,
l
-> Toast.makeText(activity, pioneers[position], Toast.LENGTH_SHORT).show()
}
return rootView
}
}
(c). MainActivity.kt
これは、私たちのMainActivityです。ここにはボタンが含まれており、クリックされると、DialogFragmentを表示したり、開いたりします。
1. Kotlinでアクティビティを作成する。
クラスを作成し、識別子を与えて、android.support.v7.app.AppCompatActivityから派生させるだけです。
class MainActivity : AppCompatActivity() {..}
2. ActivityのonCreate()メソッドをオーバーライドする。
onCreate()`は、アクティビティが作成される際に発生するメソッドです。
ここでは、superクラスのonCreate()メソッドを呼び出します。そして、setContentView()メソッドを使って、activity_main.xmlを膨らませています。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
**3. Kotlinでのウィジェットの参照
アクティビティ](%E3%81%AE)https://camposha.info/android/activity)の%E3%81%AE)findViewById()メソッドを使って、それぞれのレイアウトからウィジェットを参照することができます。
例えば、ボタンの場合は
val openFragmentBtn = findViewById(R.id.openFragmentID) as Button
4. アクティビティのFragmentManagerを取得する。
フラグメントはアクティビティによってホストされます。そのため、activityはプロパティとしてsupportFragmentManagerを保持しています。
これは次のようにして得ることができます。
val fm = supportFragmentManager
5. フラグメントを開く/表示する。
フラグメントを開いたり、表示したりすることができます。しかし、まずそのFragment`をインスタンス化する必要があります。
val pioneersFragment = PioneersFragment()
そして、Fragmentクラスのshow()メソッドを呼び出すことで、ユーザがボタンをクリックしたときにそれを開くことができます。
openFragmentBtn.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View) {
pioneersFragment.show(fm, "PioneersFragment_tag")
}
})
これがMainActivityの全コードです。
package info.camposha.kotlindialogfragment
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val openFragmentBtn = findViewById(R.id.openFragmentID) as Button
val fm = supportFragmentManager
val pioneersFragment = PioneersFragment()
openFragmentBtn.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View) {
pioneersFragment.show(fm, "PioneersFragment_tag")
}
})
}
}
//end
レイアウトリソース
(a). activity_main.xml
これはメインの activity のレイアウトです。ここにはボタンが含まれており、クリックするとDialogFragmentが開きます。
このレイアウトは、メインの activity のユーザーインターフェイスに展開されます。これはActivityのsetContentView()メソッドで行われ、レイアウトを渡す必要があります。
これは、ActivityのonCreate()メソッドの中で行います。
使用する要素は以下の通りです。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
tools_context=".MainActivity">
<Button
android_id="@+id/openFragmentID"
android_text="Open Fragment"
android_background="@color/colorAccent"
android_layout_centerInParent="true"
android_layout_width="wrap_content"
android_layout_height="wrap_content" />
</RelativeLayout>
(b). fraglayout.xml
私たちの DialogFragment レイアウトです。このレイアウトは、ダイアログ Fragment のユーザーインターフェイスとして作成されます。
このレイアウトには、シンプルな ListView が含まれます。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android_orientation="vertical" android_layout_width="match_parent"
android_layout_height="match_parent">
<ListView
android_id="@+id/myListView"
android_layout_width="match_parent"
android_layout_height="wrap_content"/>
</LinearLayout>
価値あるリソース
(a). colors.xml
マテリアルデザインの色です。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="material_amber_700">#ffffa000</color>
<color name="material_amber_800">#ffff8f00</color>
<color name="material_amber_900">#ffff6f00</color>
<color name="material_amber_A100">#ffffe57f</color>
<color name="material_amber_A200">#ffffd740</color>
<color name="material_amber_A400">#ffffc400</color>
</resources>
(b). styles.xml
アプリケーションのスタイルです。
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/material_amber_A400</item>
<item name="colorPrimaryDark">@color/material_amber_900</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
(b). Android DialogFragment - リサイクラービューの表示
Android DialogFragment - Show RecyclerView > *この例では、diaogfragment.exeにリサイクラービューを表示します。
ユーザーが表示ボタンをクリックすると、DialogFragmentを開き、その上にRecyclerViewを表示します。
プロジェクト概要
| --- |
|---|
1. 基本的なアクティビティプロジェクトの作成
- まず、android studioで空のプロジェクトを作成します。File --> New Projectを選択します。
- アプリケーション名を入力し、会社名を選択します。
- 最小限のSDKを選択します。
- Basic
activityを選択します。 - 完了をクリックする。
Basic activityには、ツールバーとフローティングアクションボタンがレイアウトに追加されています。
通常、このオプションでは2つのレイアウトが生成されます。
| --- |
|---|
この例では、基本的な activity を使用しています。
この activity は、android_manifest.xml に自動的に登録されます。Androidアクティビティはコンポーネントなので、通常はアプリケーションコンポーネントとして登録する必要があります。
手動で作成した場合は、以下のように<application>...<application>の中に登録し、MainActivityを自分のactivity名に置き換えます。
<activity android_name=".MainActivity">
<intent-filter>
<action android_name="android.intent.action.MAIN" />
<category android_name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
インテントフィルターとして、1つのアクションとカテゴリーが指定されているのがわかります。カテゴリは、MainActivityをランチャーのactivityにしています。ランチャーアクティビティは、アンドロイドアプリが実行されたときに最初に実行されます。
3. ユーザーインターフェースの作成
今回のプロジェクトのレイアウトを紹介します。
activity_main.xml ※このレイアウトはMainActivityにインフレーションされます。
activity_main.xml * このレイアウトはMainActivityのユーザーインターフェースにインフレーションされます。
- content_main.xmlを含む。
以下は、採用されるウィジェット、ビュー、ビューグループの一部です。"
| --- |
|---|
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_fitsSystemWindows="true"
tools_context="com.tutorials.hp.dialogfragmentrecyclerview.MainActivity">
<android.support.design.widget.AppBarLayout
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android_id="@+id/toolbar"
android_layout_width="match_parent"
android_layout_height="?attr/actionBarSize"
android_background="?attr/colorPrimary"
app_popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android_id="@+id/fab"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_layout_gravity="bottom|end"
android_layout_margin="@dimen/fab_margin"
android_src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
content_main.xml (コンテンツメイン)
このレイアウトは、activity_main.xmlに含まれます。
ここでUIウィジェットを定義します。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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.tutorials.hp.dialogfragmentrecyclerview.MainActivity"
tools_showIn="@layout/activity_main">
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_text="Hello World!" />
</RelativeLayout>
fraglayout.xml
このレイアウトは、DialogFragmentに展開されます。
このレイアウトには、アダプタビューとして RecyclerView が含まれます。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android_orientation="vertical" android_layout_width="match_parent"
android_layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android_id="@+id/mRecyerID"
android_layout_width="match_parent"
android_layout_height="wrap_content"></android.support.v7.widget.RecyclerView>
</LinearLayout>
model.xml
このレイアウトはRecyclerViewのViewアイテムにインフレーションされます。
基本的には、各RecyclerViewアイテムのためのCardViewです。
シンプルなTextViewを含んでいます。
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
android_id="@+id/mCard"
android_orientation="horizontal"
android_layout_width="match_parent"
android_layout_margin="10dp"
card_view_cardCornerRadius="10dp"
card_view_cardElevation="10dp"
android_layout_height="wrap_content">
<RelativeLayout
android_layout_width="match_parent"
android_layout_height="match_parent">
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_textAppearance="?android:attr/textAppearanceLarge"
android_text="Name"
android_id="@+id/nameTxt"
android_padding="10dp"
android_layout_alignParentLeft="true"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
4. Javaクラスの作成
AndroidアプリはJavaプログラミング言語で書かれているので、いくつかのクラスを作ってみましょう。
1. MyHolder.java
私たちのViewHolderクラスです。
package com.tutorials.hp.dialogfragmentrecyclerview.mRecycler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.tutorials.hp.dialogfragmentrecyclerview.R;
public class MyHolder extends RecyclerView.ViewHolder {
TextView nameTxt;
public MyHolder(View itemView) {
super(itemView);
nameTxt= (TextView) itemView.findViewById(R.id.nameTxt);
}
}
2. MyAdapter.java
弊社のリサイクラービューアダプタークラスです。
package com.tutorials.hp.dialogfragmentrecyclerview.mRecycler;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.tutorials.hp.dialogfragmentrecyclerview.R;
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
String[] tvshows;
public MyAdapter(Context c, String[] tvshows) {
this.c = c;
this.tvshows = tvshows;
}
//INITIALIE VH
@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,parent,false);
MyHolder holder=new MyHolder(v);
return holder;
}
//BIND DATA
@Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.nameTxt.setText(tvshows[position]);
}
@Override
public int getItemCount() {
return tvshows.length;
}
}
TVShowFragment.java
これは、私たちの DialogFragment です。このクラスは、android.app.DiloagFragmentから派生しています。
このクラスは RecyclerView を表示します。
package com.tutorials.hp.dialogfragmentrecyclerview;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.tutorials.hp.dialogfragmentrecyclerview.mRecycler.MyAdapter;
public class TVShowFragment extends DialogFragment {
String[] tvshows={"Crisis","Blindspot","BlackList","Game of Thrones","Gotham","Banshee"};
RecyclerView rv;
MyAdapter adapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.fraglayout,container);
//RECYCER
rv= (RecyclerView) rootView.findViewById(R.id.mRecyerID);
rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));
//ADAPTER
adapter=new MyAdapter(this.getActivity(),tvshows);
rv.setAdapter(adapter);
this.getDialog().setTitle("TV Shows");
return rootView;
}
}
4. MainActivity.java
私たちのMainActivityです。
このクラスにはボタンが含まれており、クリックされると DialogFragment が表示されます。
package com.tutorials.hp.dialogfragmentrecyclerview;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
@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);
final FragmentManager fm=getFragmentManager();
final TVShowFragment tv=new TVShowFragment();
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tv.show(fm,"TV_tag");
}
});
}
}
Example 2 - Android DialogFragment - ListView Search/Filter
ダイアログのアイデアは、どこからともなく飛び出すことができるという点で素晴らしいものです。この例では、ダイアログフラグメントを作成します。
この例では、メインのアクティビティからシンプルなボタンがクリックされたときに表示されるダイアログフラグメントを作成します。
このダイアログフラグメントは、シンプルなListViewとSearchViewを含みます。ListViewはプレーヤーのリストを含みます。
サーチビューは、リストからプレーヤーを検索するために使用されます。
1. MainActivityクラス。
これは私たちのメインとなる activity です。
クラスとしては、android.app.Activityから派生しているので、activityになります。
| --- |
|---|
package com.tutorials.dialogfragmenter;
import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FragmentManager fm=getFragmentManager();
final PlayersFragment p=new PlayersFragment();
btn=(Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
p.show(fm, "Best Players");
}
});
}
@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;
}
}
**2. PlayerFragmentクラスです。
これがPlayerFragmentクラスです。
| --- |
|---|
package com.tutorials.dialogfragmenter;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
public class PlayersFragment extends DialogFragment {
Button btn;
ListView lv;
SearchView sv;
ArrayAdapter<String> adapter;
String[] players={"Lionel Messi","Christiano Ronaldo","Neymar","Gareth Bale"};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView=inflater.inflate(R.layout.sports, null);
//SET TITLE DIALOG TITLE
getDialog().setTitle("Best Players In The World");
//BUTTON,LISTVIEW,SEARCHVIEW INITIALIZATIONS
lv=(ListView) rootView.findViewById(R.id.listView1);
sv=(SearchView) rootView.findViewById(R.id.searchView1);
btn=(Button) rootView.findViewById(R.id.dismiss);
//CREATE AND SET ADAPTER TO LISTVIEW
adapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,players);
lv.setAdapter(adapter);
//SEARCH
sv.setQueryHint("Search..");
sv.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String txt) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onQueryTextChange(String txt) {
// TODO Auto-generated method stub
adapter.getFilter().filter(txt);
return false;
}
});
//BUTTON
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
dismiss();
}
});
return rootView;
}
}
**3. 3.メインアクティビティのレイアウト
これがメインの activity レイアウトです。
| --- |
|---|
<RelativeLayout
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=".MainActivity" >
<Button
android_id="@+id/button1"
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_layout_alignParentLeft="true"
android_layout_alignParentTop="true"
android_layout_marginLeft="97dp"
android_layout_marginTop="163dp"
android_text="Show" />
</RelativeLayout>
**4. PlayerFragmentのレイアウト
これは、DialogFragmentのレイアウトです。
役割は以下の通りです。
| --- |
|---|
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_orientation="vertical" >
<SearchView
android_id="@+id/searchView1"
android_layout_width="match_parent"
android_layout_height="wrap_content" >
</SearchView>
<ListView
android_id="@+id/listView1"
android_layout_width="match_parent"
android_layout_height="326dp" >
</ListView>
<Button
android_id="@+id/dismiss"
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_text="Dismiss" />
</LinearLayout>
私たちのマニフェスト)
私たちのアンドロイドマニフェスト.xmlです。ここには activity が登録されています。
<?xml version="1.0" encoding="utf-8"?>
<manifest
package="com.tutorials.dialogfragmenter"
android_versionCode="1"
android_versionName="1.0" >
<uses-sdk
android_minSdkVersion="19"
android_targetSdkVersion="19" />
<application
android_allowBackup="true"
android_icon="@drawable/ic_launcher"
android_label="@string/app_name"
android_theme="@style/AppTheme" >
<activity
android_name="com.tutorials.dialogfragmenter.MainActivity"
android_label="@string/app_name" >
<intent-filter>
<action android_name="android.intent.action.MAIN" />
<category android_name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>