我在Android的編程新手,我有這樣的問題:按鈕在活動片段後,不工作開始
在這個簡單的例子,當我點擊啓動按鈕,我運行一個片段。當我點擊報警按鈕時,我會寫入日誌文件。
現在,如果我先點擊開始按鈕,稍後報警按鈕不會運行。我認爲問題是片段不要離開與用戶的交互。你可以幫我嗎? 最好regads 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;
}
}
感謝您的回覆,在此鏈接中您可以看到xml文件pastebin.com/jcPW4dUT我有這個想法,我使用了一個片段沒有佈局,這個片段詳細說明了數據,並稍後將這些數據提供給一個可包裝的類,在那裏我鏈接到xml文件中的列表視圖的適配器。你認爲這是一個好主意嗎? – Ant 2012-08-17 07:49:50
製作沒有佈局的片段是很好的,但這不是你在上面引用的代碼中做的。對於你剛剛描述的情況,我想你想要的是一個ListFragment和一個ContentProvider。 – Sparky 2012-08-17 08:03:05
感謝您的迴應,我是Android編程的新手,現在我升級項目提供您的想法thx。 – Ant 2012-08-17 14:55:13