当用户响应活动时,我的列表视图不会更新?

时间:2014-04-12 19:43:55

标签: java android android-fragments android-listview notifydatasetchanged

我有一个包含许多片段的主要活动,其中一个包含列表视图,带有适配器homeworkListAdapter,此适配器会显示homeworkItems中的所有项目。我的活动会打开另一个活动(HomeworkAddActivity,它会从用户处获取一个字符串并将其放入数组homeworkItems中,这一切都正常,因为我已经独立检查了每个步骤。但是当我尝试更新时使用这个新项目列出视图(使用.notifyDataSetChanged)它没有更新,我一直试图解决这个问题3-4个小时,请帮忙。

代码

MainActivity

    public static ArrayAdapter<String> homeworkListAdapter;

public static ArrayList<String> homeworkItems; 

  ....

protected void onCreate(Bundle savedInstanceState) {
....
homeworkItems = new ArrayList<String>();

homeworkListAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, homeworkItems);
....

 public static class HomeworkListViewFragment extends Fragment {

....

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(
                R.layout.fragment_homework_listview, container, false);

        homeworkListView = (ListView) rootView
                .findViewById(R.id.homework_listview);

        homeworkListView.setAdapter(homeworkListAdapter);

        return rootView;
    }

HomeworkAddActivity

public class HomeworkAddActivity extends ActionBarActivity {

....

public void buttonAddHomework(View v) {
    NavUtils.navigateUpFromSameTask(this);
    EditText editText = (EditText) findViewById(R.id.text_new_homework_name);
    String homeworkItem = (String) editText.getText().toString();
    if (!(TextUtils.isEmpty(homeworkItem))) {
        //MainActivity.homeworkList.addItem(homeworkItem);
        MainActivity.homeworkItems.add(homeworkItem);
        MainActivity.homeworkListAdapter.notifyDataSetChanged();
    }
}
 }

1 个答案:

答案 0 :(得分:0)

你可以这样检查:

if (!TextUtils.isEmpty(homeworkItem)) {
Toast.makeText(getBaseContext(),"ADDING AN ITEM!!!",Toast.LENGH_SHORT).show()
    homeworkItems.add(homeworkItem);
    homeworkListAdapter.notifyDataSetChanged();
}

只是为了确保通过检查。如果它(并且你会看到吐司)然后尝试

    if (!TextUtils.isEmpty(homeworkItem)) {
        homeworkItems.add(homeworkItem);
homeworkListAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, homeworkItems);
homeworkListView.setAdapter(homeworkListAdapter);
    }

<强>更新
最后我假设你的ListView具有属性android:height设置为&#34; wrap_content&#34; - 尝试将其更改为&#34; match_parent&#34; :)它更新但你看不到它 - 尝试滚动:))如果是这样你应该回到notifyDatasetChanged()