ArrayAdapter更新但未在listView中显示

时间:2013-01-18 19:30:51

标签: android android-listview

ArrayAdapterlistView存在问题。我正在ArrayAdapter中添加字符串列表,正如调试器显示的那样,它没有任何缺陷,但是我看不到listView上添加的任何内容。 我尝试用它做的事情(基于类似的问题):   +将其添加到runOnUiThread内,但这没有帮助,或者我没有正确使用它   +视图无效   +再次设置适配器   +添加到values并使用`adapter.notifyDataSetChanged() 我不知道我能做些什么让它发挥作用

如果有帮助,这是我的代码:

public class RunnerApp extends Activity {

        private ListView listView;
    private ArrayList<String> values;
    private ArrayAdapter<String> adapter;
    private Intent newTable;
    private String newName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_runner_app);
        listView = (ListView) findViewById(R.id.mylist);
        values = new ArrayList<String>();
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
       listView.setAdapter(adapter);
        adapter.add("x");
        adapter.notifyDataSetChanged();
    }

    //handled by android:onClick in layout file
    public void addTable(View v){
        newTable = new Intent(this, AddTable.class);
        startActivityForResult(newTable, 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1 && resultCode == Activity.RESULT_OK && data != null){
            data.getData();
            Log.d("add", "got intent");
            newName = data.getStringExtra("com.example.runnerapp.NAME");
            Log.d("add", "string " + newName);
            Runnable run = new Runnable(){
                public void run(){
                    if(newName != null) {
                        values.add(newName);
                        adapter.notifyDataSetChanged();
                    }
                }
            };
            runOnUiThread(run);
        }
    }

    @Override
    public void onResume(){
        super.onResume();
        setContentView(R.layout.activity_runner_app);
    }
}


public class AddTable extends Activity {

    public final static String EXTRA_NAME = "com.example.runnerapp.NAME";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_table);
    }

    //handled by android:onClick in layout file
    public void addThisTable(View v) {
        Intent addTable = new Intent();
        EditText editText = (EditText) findViewById(R.id.addTableField);
        String name = editText.getText().toString();
        addTable.putExtra(EXTRA_NAME, name);
        setResult(Activity.RESULT_OK, addTable);
        this.finish();
    }

}

1 个答案:

答案 0 :(得分:1)

您应该尝试从setContentView(...)中取出onResume(),因为它会从头开始完全重置您的视图。它应该只在onCreate()

中使用