1

我必须将从数据库中查询的名称列表放入列表(不是列表视图)。我可以通过使用自定义视图膨胀线性布局来做到这一点。我创建了一个新类,其中有一个使用自定义视图扩展布局的方法。在那种方法中,我实现了一个 onclicklistener,但它不起作用。代码:

public static void showPeopleInvitedList(Context context, View view, final LinearLayout layout) {
    dbAdapter = new DatabaseHandler(context);
    String[] ENTRIES = dbAdapter.getItems("user_friend_name");
    for (int i = 0; i < 5; i++ ) {
        LayoutInflater inflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflator.inflate(R.layout.people, layout, false);

        view.setId(layout.getChildCount() + 1);
        params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        view.setLayoutParams(params);
        view.setOnClickListener(myClickListener);
        layout.addView(view, 0, params);    


    }

    myClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Log.d("click", "clicked");
            layout.removeView(v);
        }
    };
}

但是 onclicklistener 不起作用。我在主要活动中调用此方法。此方法在扩展 LinearLayout 的类中 有什么建议吗?

4

1 回答 1

1

您尚未实例化 myClickListener,因此您将视图设置onClickListenernull. 将其初始化移动到for循环之前。

public static void showPeopleInvitedList(Context context, View view, final LinearLayout layout) {
    dbAdapter = new DatabaseHandler(context);
    String[] ENTRIES = dbAdapter.getItems("user_friend_name");

    myClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Log.d("click", "clicked");
            layout.removeView(v);
        }
    };
    for (int i = 0; i < 5; i++ ) {
        LayoutInflater inflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflator.inflate(R.layout.people, layout, false);

        view.setId(layout.getChildCount() + 1);
        params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        view.setLayoutParams(params);
        view.setOnClickListener(myClickListener);
        layout.addView(view, 0, params);    


    }

}

于 2012-09-28T19:12:10.427 回答