0

我对ArrayAdapter和有疑问listView。我正在将字符串添加到列表中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();
    }

}
4

1 回答 1

1

您应该尝试setContentView(...)从头开始删除,onResume()因为它会从头开始完全重置您的视图。它真的应该只需要onCreate()

于 2013-01-18T20:16:27.310 回答