为 Fragment 的Preference 添加自定义的布局

来源:互联网 发布:淘宝0元购平台 编辑:程序博客网 时间:2024/04/30 15:27

添加 Preference 文件:


@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);addPreferencesFromResource(R.xml.system_cloud_sync_settings);}

添加自定义布局:


@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment_cloud_sync_settings, null);}

布局文件:fragment_cloud_sync_settings.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:paddingTop="10dip"    android:paddingLeft="30dip"    android:orientation="vertical" > <TextView        android:id="@+id/tv_title"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/cloud_sync"        android:textAppearance="?android:attr/textAppearanceLarge" />    <TextView        android:id="@+id/tv_summary"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/cloud_sync_title_summary" />    <View     android:layout_width="fill_parent"      android:layout_height="2dp"    android:background="?android:attr/listDivider"  />  <!-- 这个根ListView必不可少,否则 Preference 无法加载,报错 -->    <include layout="@layout/settings_root_layout" /></LinearLayout>

其中settings_root_layout.xml 这个文件必不可少否则Preference无法加载,而且注意id的命名,为系统的id


<ListView xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@android:id/list"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:fadingEdgeLength="0dip"    android:scrollbarStyle="outsideOverlay"    android:scrollbars="none" />





原创粉丝点击