【问题标题】:Android Studio, populating listView from innerclassAndroid Studio,从内部类填充 listView
【发布时间】:2017-07-22 16:30:27
【问题描述】:

这是我的代码,当我使用时

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 方法中可以正常工作,但问题是我不能在匿名类中使用“this”。由于某种原因,用 getApplicationContext() 替换 'this' 不起作用,无论是在 onCreate 内部还是外部。

喜欢这个

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

谁能帮我找到我搜索了很多但在任何地方都找不到答案的问题

谢谢

【问题讨论】:

    标签: java android listview android-studio


    【解决方案1】:

    我会通过内部类的构造函数中的参数传递this-pointer并将其保存在内部类字段中,就像这样->

    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;
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      当您使用适配器将某些内容添加到列表或数组中时,您需要提醒列表(在本例中为数组)发生了变化。调用add函数后需要调用adapter.notifyDataSetChanged()

      另外,在声明适配器时,在 onCreate() 之外声明它,然后在 onCreate() 中分配你的值

      adapter = new ArrayAdapter&lt;String&gt;(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();

      希望这会有所帮助!

      【讨论】:

        【解决方案3】:

        我假设你的匿名类在你的 MainActivity 中。如果是这种情况,您可以简单地这样做:

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

        当您在匿名类中使用“this”时,它指的是匿名内部类实例,而不是外部类的实例。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-03-25
          • 1970-01-01
          • 1970-01-01
          • 2023-03-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-28
          相关资源
          最近更新 更多