1.一个FragmentActivity(FragmentsActivity)
2.一个ListFragment(Fragment1),其中有很多标题
3.点击其中一个标题,跳转到一个Fragment(Fragment2),并在此显示点击的标题
注意到Fragment可以通过setArguments和getArguments来通过Bundle传值,在ListFragment的点击事件中,将得到的标题,存放到一个Bundle中,传递到Fragment中,再去设置Fragment中的标题为点击的文字。
Fragment中
public class Fragment2 extends Fragment { private static Bundle bundle; static Fragment2 newInstance(Bundle b){ Fragment2 f2 = new Fragment2(); bundle = b; return f2; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment2, container,false); TextView title = (TextView)v.findViewById(R.id.title2); title.setText(bundle.getString("title")); return v; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
Fragment的布局
<?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:orientation="vertical" > <TextView android:id="@+id/title2" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" android:gravity="center" android:text="class test" /> <EditText android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="4" android:background="@android:color/holo_green_light" android:gravity="top" /> </LinearLayout>
设置EditText的光标指向第一行
android:gravity="top"
ListFragment中
@Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); System.out.println(l.getChildAt(position)); HashMap<String, Object> view= (HashMap<String, Object>) l.getItemAtPosition(position); String title = view.get("title").toString(); Bundle b = new Bundle(); b.putString("title", title); Fragment2 f2 = Fragment2.newInstance(b); getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragments, f2).commit(); }
效果:点击class 3