Android Activity与Fragment 数据交互时 请注意生命周期
package com.tz.fragmentdata;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements
OnItemClickListener {
public String hobby = "sleep";
private MyListFragment myListFragment;
private FragmentManager fragmentManager;
private TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fragmentManager = this.getSupportFragmentManager();// 获取fragment的管理器
myListFragment = (MyListFragment) fragmentManager
.findFragmentByTag("listfragment");
tv = (TextView) findViewById(R.id.tv);
}
@Override
protected void onResume() {
int count = myListFragment.getListAdapter().getCount();
Toast.makeText(this, "爱好数量:" + count, 1000).show();
super.onResume();
}
// 声明回调函数
public void onItemClick(AdapterView> parent, View view, int position,
long id) {
String text = myListFragment.hobbies[position];
tv.setText(text);
}
}
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
android:layout_width="fill_parent"
android:layout_height="100dp"
android:text="@string/hello"
android:background="#ff0000"
android:id="@+id/tv"
/>
android:name="com.tz.fragmentdata.MyListFragment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:tag="listfragment"
/>
package com.tz.fragmentdata;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MyListFragment extends ListFragment {
String[] hobbies = new String[] { "backetball", "singing", "lol",
"dancing", "dota" };
private MainActivity mActivity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// 先将dota数据改成activity里面的sleep
mActivity = (MainActivity) this.getActivity();
TextView tv = (TextView) mActivity.findViewById(R.id.tv);
hobbies[4] = tv.getText().toString();
ArrayAdapter adapter = new ArrayAdapter(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1,
hobbies);
this.setListAdapter(adapter);
this.getListView().setOnItemClickListener(mActivity);
super.onActivityCreated(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return super.onCreateView(inflater, container, savedInstanceState);
}
}