如何将setAdapter放在静态方法中并从另一个类访问它

时间:2013-11-13 12:15:06

标签: android listview adapter

我有一个ListView,我在其中设置了Adapter onCreate。但是我想把setAdapter放在一个静态方法中,然后在另一个类的onClick中调用它。这有可能吗?现在它说“无法对非静态setAdapter方法进行静态引用”。下面是我的代码:我在代码中提到了我希望在我的静态方法“addItems()”中使用它的部分。建议欢迎。提前致谢

public class LogListView extends ListActivity {
    /** Called when the activity is first created. */
    private static String newString;
    private static EntryAdapter adapter;
    int clickCounter = 0;
    static ArrayList<Item> items = new ArrayList<Item>();
    static SharedPreferences preferences = null;  
    private static Context context = null;
    StringTokenizer tokens;
    String first;
    String second;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = getApplicationContext();

        /*I WANT THIS LOOP TO BE IN  "ADDITEMS() METHOD*/
        preferences = context.getSharedPreferences("LOG", android.content.Context.MODE_PRIVATE);
        newString = preferences.getString("log", "");

        //items.add(new SectionItem("Log Report"));
        items.add(new EntryItem("", newString));

        adapter = new EntryAdapter(this, items);
        setListAdapter(adapter);

        /*I WANT THIS LOOP TO BE IN  "ADDITEMS() METHOD ENDS*/


    }

    //Method which will handle dynamic insertion
    public static void addItems() {
        items.add(new EntryItem("", newString));
        adapter.notifyDataSetChanged();
    }
    //Method which will handle dynamic insertion ends

    @Override
    public void onResume(){
        super.onResume();

    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

        if(!items.get(position).isSection()) {

            EntryItem item = (EntryItem)items.get(position);
            //Toast.makeText(this, "You clicked " + item.title , Toast.LENGTH_SHORT).show();
            Toast.makeText(this, "You clicked " + position , Toast.LENGTH_SHORT).show();

        }

        if (position == 9){

        }

        super.onListItemClick(l, v, position, id);
    }
}

1 个答案:

答案 0 :(得分:1)

我明白了。不需要在静态方法中设置setAdapter。我能做的就是onCreate我可以设置适配器并将它放在一边。并且onClick我可以使用

输入值
adapter.notifyDataSetChanged();