【发布时间】:2014-03-18 15:02:29
【问题描述】:
我在刷新阵列适配器时遇到问题。当我在手机上测试程序时,它运行良好,并且在切换片段时完美刷新。当我使用平板电脑并且两个片段同时出现时,问题就出现了。
这是我的片段代码:
public class HistoryFragment extends Fragment {
private ArrayList<String> history = new ArrayList<String>();
private ArrayAdapter<String> arrayAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle data = getArguments();
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.history, container, false);
ListView view = (ListView) v.findViewById(R.id.list);
if(data != null){
history = data.getStringArrayList("history");
}
arrayAdapter = new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_list_item_1, history);
view.setAdapter(arrayAdapter);
return v;
}
public void setHistory(ArrayList<String> history) {
history.addAll(history);
arrayAdapter.notifyDataSetChanged();
}
}
这是我的活动代码:
public class MainActivity extends Activity implements historyClickListener{
public static ArrayList<String> history = new ArrayList<String>();
CalcFragment mCalcFragment = new CalcFragment();
HistoryFragment mHistFragment = new HistoryFragment();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.container) != null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, mCalcFragment);
fragmentTransaction.commit();
}
}
@Override
public void sendHistory(ArrayList<String> history){
Fragment hf = getFragmentManager().findFragmentById(R.id.historyfrag);
if(hf != null){
mHistFragment.setHistory(history);
}else{
Bundle data = new Bundle();
data.putStringArrayList("history", history);
mHistFragment.setArguments(data);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, mHistFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
sendHistory 是计算器中的一个接口方法,可帮助计算器发送已完成的方程式列表。然后在主要活动中,如果我使用的是平板电脑,那么它所做的就是 setHistory,它是历史片段中的一种方法。我相信问题是我没有在历史片段中正确使用arrayAdapter.notifyDataSetChanged()。有人可以帮忙吗。谢谢!
【问题讨论】:
-
我仍然需要这方面的帮助..
标签: android android-fragments android-arrayadapter