2017-03-02 90 views
0

这里移植ListView是我的代码,当我使用Android Studio中,从内部类

List<String> array = new ArrayList<String>(); 

array.add("kk"); 
array.add("bb"); 

ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,array); 

listView1.setAdapter(adapter); 

这将很好地工作在我的onCreate方法,但问题是我不能我们“这”在anonynmous类。用getApplicationContext()替换'this'由于某种原因不起作用,无论是在onCreate内部还是外部。

这样

ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,array); 

谁能帮我找到我寻觅了很多问题,但不能找到这个答案的任何地方

感谢

回答

0

我假设你的匿名类是您的MainActivity内。如果是这样的话,你可以简单地做:

ArrayAdapter adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array); 

当你用“这个”您的匿名内部类,它指的是匿名内部类的实例,而不是外部类的实例。

+0

曾为完美谢谢 –

1

我会通过这个指针通过内部类的构造函数中的参数并将其保存在内部类字段中,如下所示 - >

public class outerclass{ 
    @Override 
    protected void onCreate(Bundle savedInstanceState){ 
    //.. other stuff 
    innerclass ic = new innerclass(this); 
    //.. other stuff 
    } 

    public class innerclass{ 
     private Context c; 
     public innerclass(Context c){ 
      this.c = c; 
     } 
    } 
} 
1

当你使用一个适配器来添加一些东西到一个列表或数组,您需要提醒的列表,在这种情况下数组,即有一个变化。你调用add函数后,你需要调用adapter.notifyDataSetChanged()

此外,声明适配器时,声明它的onCreate(外),然后指定你的价值观里面的onCreate()

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

请看下图:

public class MainActivity extends AppCompatActivity { 

    // List of array strings that will represent list items 
    public static ArrayList<String> listItems = new ArrayList<String>(); 

    // Array string will handle the information stored in the listview 
    public static ArrayAdapter<String> adapter; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     lView = (ListView) findViewById(R.id.list); 

     adapter = new ArrayAdapter<String>(this, 
       android.R.layout.simple_list_item_1, 
       listItems); 
     lView.setAdapter(adapter); 
    } 
} 

然后,您可以拨打:

listItems.add(<value>); 
adapter.notifyDataSetChanged(); 

然后如果需要的话,你也有机会获得: listItems.clear();adapter.clear();

希望这有助于!