我是Android编程的新手,我遇到了这个问题:
在这个简单的例子中,当我点击开始按钮时,我运行了一个片段。当我单击警报按钮时,我会写入一个日志文件。
现在,如果我先单击开始按钮,稍后警报按钮将不会运行。我认为问题在于片段不离开与用户的交互。你能帮助我吗?最好的问候 A.
public class MainActivity extends FragmentActivity {
private static final String FRAG1_TAG = MainActivity.class.getCanonicalName() +".fragment1";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStart.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.i("exemple", "start button Start !!!!!!");
goFragment();
}
});
Button buttonAllarm = (Button) findViewById(R.id.buttonAllarm);
buttonAllarm.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.i("exemple", "start button allarm !!!!!!");
}// fine onClick
});// fine onClickListner
}
void goFragment() {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction xact = fm.beginTransaction();
if (null == fm.findFragmentByTag(FRAG1_TAG)) {
xact.replace(android.R.id.content, new ListFramment(), FRAG1_TAG);
xact.addToBackStack (null); // questo serve devi metterlo
xact.commit();
}
}
这是片段
public class ListFramment extends ListFragment {
// onCreate
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, null);
AppLog.logString("Parte onCreateView");
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
AppLog.logString("Parte onActivityCreated");
ArrayList<Map<String, String>> list = buildData();
String[] from = { "name", "purpose" };
int[] to = { android.R.id.text1, android.R.id.text2 };
SimpleAdapter adapter = new SimpleAdapter(getActivity(), list,
android.R.layout.simple_list_item_2, from, to);
setListAdapter(adapter);
}
private ArrayList<Map<String, String>> buildData() {
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
list.add(putData("Android", "Mobile"));
list.add(putData("iPhone", "iPhone"));
return list;
// TODO Auto-generated method stub
}
private HashMap<String, String> putData(String name, String purpose) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("name", name);
item.put("purpose", purpose);
return item;
}
}