Android -- (9),SpinnerView ,特殊的fragment等

本文介绍Android开发中的SpinnerView组件及其在Fragment中的应用,包括ListFragment用于显示列表,dialogFragment创建对话框样式,以及PreferenceFragment进行偏好设置的实现。

时间 : 2013/1/14

好久没写了,继续开始,坚持。

一,SpinnerView 组件

ListView用一个长列表来展示items,当你没有这么多位置去展示items的时候,就该用spinnerview了。

1.定义SpinnerVIew -- 也是像其他组件一样,在活动的xml文件里面加入标签来定义。
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true" />

当然,这个spinner现在也没选项,跟之前的一样,可以在string.xml里面定义字符数组,然后在活动的java文件里面动态读取:
presidents= getResources().getStringArray(R.array.presidents_array);
        Spinner s1=(Spinner)findViewById(R.id.spinner1);
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,
        		presidents);
        s1.setAdapter(adapter);

上述方法从string.xml中读取一个presidents数组,是预先设置好的,然后将这个数组传入ArrayAdapter,再将adapter传入spinnerVIew即可。

Spinnerview的事件和其他的控件也类似。传入一个实现该接口的类即可:(这里是onItemSelected事件,传入的类实现的是OnItemSelectedListener接口)
   s1.setOnItemSelectedListener(new OnItemSelectedListener()
        {
        	public void onItemSelected(AdapterView<?> arg0,
        			View arg1,int arg2,long arg3)
        	{
        		int index =arg0.getSelectedItemPosition();
        		Toast.makeText(getBaseContext(), "You have selected item : "+presidents[index], Toast.LENGTH_SHORT).show(); 	
        	}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
        }
		);

传入的类实现了onItemSelected和onNothingSelected方法,在Spinnerview的项目被选中的时候会用toast来显示该项目的值。

同样,也可以将每个string字符串都显示为一个Radiobutton:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, presidents);

二,使用特殊的fragment

fragment让程序可以动态的布置用户界面,让其可以运行在不同的设备上面。可以让一个类继承fragment来创建fragment,除了一般的fragment之外,还有其他几个特殊的fragment控件。

1.ListFragment

--fragment包含一个listView = listFragment。使用方法大概如下:
(1)从fragment的xml文件入手,在res/layout里面创建一个xml文件,名字为fragment1.xml,然后往里面加入一个listView,整个xml文件类似这样:
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
<ListView
android:id=”@id/android:list”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_weight=”1”
android:drawSelectorOnTop=”false”/>
</LinearLayout>

(2)然后为这个fragment创建用来交互的java文件。为了和xml文件保持对应关系,这里创建的类成为Fragment1类:
public class Fragment1 extends ListFragment {
}
由于这个类是继承的是fragment,于是要为其实现onCreate方法(基本),这里外加了一个响应选择事件的方法:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, presidents));
}

这个方法已经在前面介绍过,这里不多说。响应选择事件的方法也和上例的相似:
public void onListItemClick(ListView parent, View v,
int position, long id)
{
Toast.makeText(getActivity(),
“You have selected “ + presidents[position],
Toast.LENGTH_SHORT).show();
}



(3)然后要在fragment要嵌入的活动的xml文件中(此处是主活动的xml文件)里面声明fragment:
<fragment
android:name=”net.learn2develop.ListFragmentExample.Fragment1”
android:id=”@+id/fragment1”
android:layout_weight=”0.5”
android:layout_width=”0dp”
android:layout_height=”200dp” />
这是一个,还有一个:
<fragment
android:name=”net.learn2develop.ListFragmentExample.Fragment1”
android:id=”@+id/fragment1”
android:layout_weight=”0.5”
android:layout_width=”0dp”
android:layout_height=”200dp” />


再次提醒此处的name是PackageName.fragmentName,第二步中创建的类的名字要和这个名字相同,以此来为这个fragment和对应的类结合起来。这里两个fragment载入的都是同一个类,fragment1,而这个类就会用onCreateVIew方法载入用户指定的xml文件,这样就把主方法--fragment--交互类三者结合起来。

2.dialogFragment

--另一种特殊的fragment就是dialogfragment了,它会弹出一个dialog窗口给用户确定。这个控件在需要获得用户的确认后再继续执行操作的情况下常用。

(1)和上面的listFragment类似,也是先创建一个java类继承dialogFragment:
public class Fragment1 extends DialogFragment {
}
(2)这里用了一个静态方法来返回一个Fragment1的实例:
static Fragment1 newInstance(String title) {
Fragment1 fragment = new Fragment1();
Bundle args = new Bundle();
args.putString(“title”, title);
fragment.setArguments(args);
return fragment;
}

在创建实例的时候同时传入一个bundle变量,用来向fragment里面传入参数。
(3)如何显示出Dialog呢?当主活动里面的一个Fragment1 变量 调用show方法的时候,Fragment1类中定义的onCreateDialog就会被调用,从而在界面上创建一个dialog。为了达到这个效果,要在Fragment1类中定义onCreateDialog这个方法:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments().getString(“title”);
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.ic_launcher)
.setTitle(title)
.setPositiveButton(“OK”,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
((DialogFragmentExampleActivity)
getActivity()).doPositiveClick();
}
})
.setNegativeButton(“Cancel”,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
((DialogFragmentExampleActivity)
getActivity()).doNegativeClick();
}
}).create();
}

这个方法返回一个alertDialog,并加入了两个button -- OK和Cancel 。这两个button对应着主活动里面的doPositiveClick()和doNegativeClick()方法(稍后定义)。
(4)正如上一步所说的,在主活动中应该调用一个Fragment1类的show方法,从而调用该类里面的onCreateDialog方法,再者,因为在onCreateDialog方法里面的两个button都调用了主方法活动里面的两个方法,所以这两个方法也应该定义:
public void doPositiveClick() {
//---perform steps when user clicks on OK---
Log.d(“DialogFragmentExample”, “User clicks on OK”);
}
public void doNegativeClick() {
//---perform steps when user clicks on Cancel---
Log.d(“DialogFragmentExample”, “User clicks on Cancel”);
}

定义了对应类中的两个button的调用方法。

然后在主活动的onCreate方法里面添加:
 Fragment1 dialogFragment =Fragment1.newInstance("Are you sure you want to do this ?");
 dialogFragment.show(getFragmentManager(), "dialog");
原因是现在只有一个活动,这个活动也只有一个控件-- dialogFragment,所以在这里可以顺带调用dialogFragment的show方法。让主活动一创建就马上展示alertDialog。当然也可以在主活动中添加一个button来触发啦。


3.PreferenceFragment


--可以用一个fragment来让用户选择其偏好的设置。用户在这个设置面保存的设置都会用文件保存起来。

(1)正如其他fragment一样,首先要用一个类来继承preferenceFragment类:
public class Fragment1 extends PreferenceFragment {
}

(2)在res/下创建一个xml的文件夹,里面加入xml文件preferences。用于创建preferenceFragment的界面:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Category 1">
<CheckBoxPreference
android:title="Checkbox"
android:defaultValue="false"
android:summary="True of False"
android:key="checkboxPref" />
</PreferenceCategory>
<PreferenceCategory android:title="Category 2">
<EditTextPreference
android:name="EditText"
android:summary="Enter a string"
android:defaultValue="[Enter a string here]"
android:title="Edit Text"
android:key="editTextPref" />
<RingtonePreference
android:name="Ringtone Preference"
android:summary="Select a ringtone"
android:title="Ringtones"
android:key="ringtonePref" />
<PreferenceScreen
android:title="Second Preference Screen"
android:summary=
"Click here to go to the second Preference Screen"
android:key="secondPrefScreenPref">
<EditTextPreference
android:name="EditText"
android:summary="Enter a string"
android:title="Edit Text (second Screen)"
android:key="secondEditTextPref" />
</PreferenceScreen>
</PreferenceCategory>
</PreferenceScreen>

(3)然后在继承preferenceFragment的类中用addPreferencesFromResource()方法将preferenceFragment的xml文件载入preferenceFragment中。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//---load the preferences from an XML file---
addPreferencesFromResource(R.xml.preferences);
}


(4)在主活动中,用以下代码来展示刚创建的preferenceFragment:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
Fragment1 fragment1 = new Fragment1();
fragmentTransaction.replace(android.R.id.content, fragment1);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值