android – listview项目中的OnClickListener始终占据最后一行

android – listview项目中的OnClickListener始终占据最后一行,第1张

概述我从服务器下载数据并用它们填写listview.列表视图中的每个项目都有3个按钮,我想在每个按钮上创建一个onclicklistener.当用户单击其中一个按钮时,它应该例如打开新活动.每一行(对象)都有一些id,当我点击其中一些按钮时,id总是例如15(它总是listview中最后一行的id). 我试图用许多不同的方式声明OnClickListeners,结果是一样的. LawsAdapter 我从服务器下载数据并用它们填写ListvIEw.列表视图中的每个项目都有3个按钮,我想在每个按钮上创建一个onclickListener.当用户单击其中一个按钮时,它应该例如打开新活动.每一行(对象)都有一些ID,当我点击其中一些按钮时,ID总是例如15(它总是ListvIEw中最后一行的ID).
我试图用许多不同的方式声明OnClickListeners,结果是一样的.

LawsAdapter

public class LawsAdapter extends ArrayAdapter<Law> implements VIEw.OnClickListener {private LayoutInflater inflater;private Context context;private UserLocalStore userLocalStore;private IsVotedStorage isVotedStorage;private VIEw convertVIEw;private VIEwHolder vIEwHolder;/** * Constructor,declares storages,context and inflater * @param context * @param textVIEwResourceID */public LawsAdapter(Context context,int textVIEwResourceID) {    super(context,textVIEwResourceID);    this.context = context;    inflater =  ((Activity) context).getLayoutInflater();    userLocalStore = new UserLocalStore(context);    isVotedStorage = new IsVotedStorage(context);}/** * Second constructor,here you can set the resource (againstr the prevIoUs one) * @param context * @param resource * @param items */public LawsAdapter(Context context,int resource,List<Law> items) {    super(context,resource,items);    this.context = context;    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);    userLocalStore = new UserLocalStore(context);    isVotedStorage = new IsVotedStorage(context);}/** * OverrIDen method getVIEw,declares graphic objects (btns... ) and set Listeners * @param position * @param convertVIEw * @param parent * @return vIEw */@OverrIDepublic VIEw getVIEw(int position,VIEw convertVIEw,VIEwGroup parent) {    if (convertVIEw == null) {        convertVIEw = inflater.inflate(R.layout.law_item,parent,false);        this.convertVIEw = convertVIEw;        vIEwHolder = new VIEwHolder();        vIEwHolder.tvname = (TextVIEw) convertVIEw.findVIEwByID(R.ID.lawItemname);        vIEwHolder.tvDescription = (TextVIEw) convertVIEw.findVIEwByID(R.ID.lawItemDescription);        vIEwHolder.tvstatus = (TextVIEw) convertVIEw.findVIEwByID(R.ID.lawItemStatus);        vIEwHolder.btnDownVote = (button) convertVIEw.findVIEwByID(R.ID.lawItemDownVote);        vIEwHolder.btnUpVote = (button) convertVIEw.findVIEwByID(R.ID.lawItemUpVote);        vIEwHolder.btnMakeComment = (button) convertVIEw.findVIEwByID(R.ID.lawItemmakeComment);        vIEwHolder.currentLaw = getItem(position);        Log.d("VIEw holder","new one");        Log.d("LAW ID,ADAPTER",String.valueOf(vIEwHolder.currentLaw.getID()));        vIEwHolder.tvname.setText(vIEwHolder.currentLaw.getname());        vIEwHolder.tvDescription.setText(vIEwHolder.currentLaw.getDescription());        vIEwHolder.tvstatus.setText(vIEwHolder.currentLaw.getStateValue());        setSurfacescolors();        vIEwHolder.btnMakeComment.setonClickListener(this);        vIEwHolder.btnDownVote.setonClickListener(this);        vIEwHolder.btnUpVote.setonClickListener(this);        disableIfVoted();        convertVIEw.setTag(vIEwHolder);    }    else {        vIEwHolder = (VIEwHolder) convertVIEw.getTag();        Log.d("VIEw holder","get tag");    }    return convertVIEw;}/** * Set the colors of surfaces */private voID setSurfacescolors() {    vIEwHolder.sfleft = (SurfaceVIEw) convertVIEw.findVIEwByID(R.ID.lawItemSurfaceleft);    vIEwHolder.sfBackground = (SurfaceVIEw) convertVIEw.findVIEwByID(R.ID.lawItemSurfaceBackground);    Log.d("VoteS","Positive: " +  vIEwHolder.currentLaw.getPositiveVotes() + " Negative: " + vIEwHolder.currentLaw.getNegativeVotes());    if ((vIEwHolder.currentLaw.getNegativePercent() + vIEwHolder.currentLaw.getNegativeVotes()) > 1) {        vIEwHolder.sfBackground.setBackgroundcolor(context.getResources().getcolor(R.color.redSurfaceBckg));        vIEwHolder.sfleft.setBackgroundcolor(context.getResources().getcolor(R.color.btnsubmitcolor));        int screenWIDth = getScreenWIDth();        int upVote = vIEwHolder.currentLaw.getNegativePercent();        int downVote = vIEwHolder.currentLaw.getPositivePercent();        int positivePixels = (screenWIDth / 100) * upVote;        int negativePixels = (screenWIDth / 100) * downVote;        vIEwHolder.sfBackground.getHolder().setFixedSize(negativePixels,5);        vIEwHolder.sfleft.getHolder().setFixedSize(positivePixels,5);        Log.d("UPDATE","NOTIFY");    }    else {        vIEwHolder.sfBackground.setBackgroundcolor(context.getResources().getcolor(R.color.greySurface));        vIEwHolder.sfleft.setBackgroundcolor(context.getResources().getcolor(R.color.greySurface));    }}/** * UpVote * @param law */private voID upVote(Law law) {    ServerRequest serverRequest = new ServerRequest(context);    serverRequest.upVoteLawInBackground(law.getID(),new updownCallback() {        @OverrIDe        public voID done(Law law) {            vIEwHolder.currentLaw = law;            setSurfacescolors();            Log.e("VoteS in UPVote","Positive: " + vIEwHolder.currentLaw.getPositiveVotes() + " Negative: " + vIEwHolder.currentLaw.getNegativeVotes());        }    });}/** * DownVote * @param law */private voID downVote(Law law) {    ServerRequest serverRequest = new ServerRequest(context);    serverRequest.downVoteLawInBackground(law.getID(),new updownCallback() {        @OverrIDe        public voID done(Law law) {            vIEwHolder.currentLaw = law;            setSurfacescolors();        }    });}/** * Get screen wIDth in pixels * @return int screen wIDth */private int getScreenWIDth() {    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);    display display = wm.getDefaultdisplay();    Point size = new Point();    display.getSize(size);    int wIDth = size.x;    return wIDth;}/** * disable voting button if I have already Voted */private voID disableIfVoted() {    if (isVotedStorage.isVoted(vIEwHolder.currentLaw.getID())) {        vIEwHolder.btnUpVote.setEnabled(false);        vIEwHolder.btnDownVote.setEnabled(false);    }}@OverrIDepublic voID onClick(VIEw v) {    switch (v.getID()) {        case R.ID.lawItemmakeComment:            if (userLocalStore.isUserLoggedIn()) {                Log.d("ON CliCK LAW ID",String.valueOf(vIEwHolder.currentLaw.getID()));                Intent commentsIntent = new Intent(context,DialogCommentsActivity.class);                commentsIntent.putExtra("law_ID",vIEwHolder.currentLaw.getID());                commentsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_top);                Log.d("CURRENT LAW",vIEwHolder.currentLaw.getID() + " " + vIEwHolder.currentLaw.getname());                context.startActivity(commentsIntent);            } else {                context.startActivity(new Intent(context,DialogSignInActivity.class));            }            break;        case R.ID.lawItemDownVote:            if (userLocalStore.isUserLoggedIn()) {                isVotedStorage.setVoted(true,vIEwHolder.currentLaw.getID());                downVote(vIEwHolder.currentLaw);                disableIfVoted();                notifyDataSetChanged();            } else {                context.startActivity(new Intent(context,DialogSignInActivity.class));            }            break;        case R.ID.lawItemUpVote:            if (userLocalStore.isUserLoggedIn()) {                isVotedStorage.setVoted(true,vIEwHolder.currentLaw.getID());                upVote(vIEwHolder.currentLaw);                disableIfVoted();                notifyDataSetChanged();            } else {                context.startActivity(new Intent(context,DialogSignInActivity.class));            }            break;    } }/** * Holds items per row */private static class VIEwHolder {    private TextVIEw tvname;    private TextVIEw tvDescription;    private TextVIEw tvstatus;    private button btnUpVote;    private button btnDownVote;    private button btnMakeComment;    private SurfaceVIEw sfBackground;    private SurfaceVIEw sfleft;    private Law currentLaw;}

}

law_item.xml

<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"    androID:layout_wIDth="match_parent"    androID:layout_height="170dp"    androID:gravity="bottom"    androID:padding="6pt"    androID:background="@color/button_material_light">    <relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"        androID:layout_wIDth="match_parent"        androID:layout_height="140dp"        androID:gravity="bottom"        androID:background="@color/background_floating_material_light"        androID:theme="@style/Apptheme"        androID:ID="@+ID/rel">        <SurfaceVIEw            androID:layout_wIDth="match_parent"            androID:layout_height="wrap_content"            androID:ID="@+ID/lawItemSurfaceBackground"            androID:layout_alignParenttop="true"            androID:layout_alignParentleft="true"            androID:layout_alignParentStart="true" />        <SurfaceVIEw            androID:layout_wIDth="wrap_content"            androID:layout_height="wrap_content"            androID:ID="@+ID/lawItemSurfaceleft"            androID:layout_alignBaseline="@+ID/lawItemSurfaceBackground"            androID:layout_alignBottom="@+ID/lawItemSurfaceBackground"            androID:layout_alignParentleft="true"            androID:layout_alignParentStart="true" />        <TextVIEw            androID:layout_wIDth="match_parent"            androID:layout_height="wrap_content"            androID:ID="@+ID/lawItemname"            androID:textAppearance="?androID:attr/textAppearanceLarge"            androID:layout_below="@+ID/lawItemSurfaceBackground"            androID:layout_margintop="2pt"            androID:layout_marginBottom="3pt"            androID:layout_marginleft="3pt"            androID:layout_marginRight="3pt"            androID:padding="1pt"/>        <TextVIEw            androID:layout_wIDth="match_parent"            androID:layout_height="wrap_content"            androID:layout_below="@+ID/lawItemname"            androID:textAppearance="?androID:attr/textAppearanceMedium"            androID:padding="1pt"            androID:layout_marginleft="3pt"            androID:layout_marginRight="3pt"            androID:layout_marginBottom="3pt"            androID:ID="@+ID/lawItemDescription" />        <TextVIEw            androID:layout_wIDth="wrap_content"            androID:layout_height="wrap_content"            androID:padding="1pt"            androID:layout_marginBottom="3pt"            androID:ID="@+ID/lawItemStatus"            androID:layout_marginRight="30pt"            androID:layout_below="@+ID/lawItemDescription"            androID:layout_alignParentRight="true"            androID:layout_alignParentEnd="true" />        <linearLayout            androID:layout_wIDth="match_parent"            androID:layout_height="38dp"            androID:layout_below="@ID/lawItemStatus"            androID:orIEntation="horizontal">            <button androID:layout_weight="1"                androID:layout_height="wrap_content"                androID:background="@color/btnsubmitcolor"                androID:textcolor="@color/btnsubmitTextcolor"                androID:layout_wIDth="match_parent"                androID:focusable="false"                androID:text="@string/button_upVote"                androID:ID="@+ID/lawItemUpVote" />            <button androID:layout_weight="1"                androID:layout_height="wrap_content"                androID:layout_wIDth="match_parent"                androID:background="@color/btnsubmitcolor"                androID:textcolor="@color/btnsubmitTextcolor"                androID:text="@string/button_downVote"                androID:focusable="false"                androID:ID="@+ID/lawItemDownVote" />            <button androID:layout_weight="1"                androID:layout_height="wrap_content"                androID:layout_wIDth="match_parent"                androID:background="@color/btnsubmitcolor"                androID:textcolor="@color/btnsubmitTextcolor"                androID:focusable="false"                androID:text="@string/button_comment"                androID:ID="@+ID/lawItemmakeComment" />        </linearLayout>    </relativeLayout></linearLayout>

示例:我在第一行单击btnMakeComment,新的Activity打开并从ID为15的对象的db注释下载.然后我单击第三行中的btnMakeComment并打开新的Activity并从对象的db注释下载具有相同的ID,就像上次(再次15).
但是在ListVIEw中不是相同的行/对象,它们在点击时是不同的,看起来它们会是相同的.

DialogCommentsActivity

/** * Activity for adding and reading comments */public class DialogCommentsActivity extends AppCompatActivity implements AbsListVIEw.OnItemClickListener,AbsListVIEw.OnScrollListener,VIEw.OnClickListener {    private int lawID;    private int limit;    private int offset;    private int preLast;    private int page;    private ListVIEw ListVIEw;    private EditText etAddComment;    private List<Comment> activityCommentList;    private UserLocalStore userLocalStore;    private User user;    private button btnsubmit;    private CommentsAdapter commentsAdapter;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_comments_dialog);        setTitle("");        setFinishOntouchOutsIDe(true);        ListVIEw = (ListVIEw) findVIEwByID(R.ID.commentDialogListVIEw);        limit = 5;        offset = 0;        page = 1;        userLocalStore = new UserLocalStore(this);        user = userLocalStore.getLoggedUser();        etAddComment = (EditText) findVIEwByID(R.ID.commentDialogEditAdd);        btnsubmit = (button) findVIEwByID(R.ID.commentsDialogsubmit);        btnsubmit.setEnabled(false);        ListVIEw.setonItemClickListener(this);        ListVIEw.setonScrollListener(this);        btnsubmit.setonClickListener(this);        Bundle extras = getIntent().getExtras();        String username;        dumpIntent(getIntent());        if (extras != null) {            lawID = extras.getInt("law_ID");        }        Log.e("LAW ID HOHOHO",String.valueOf(lawID));        fillAdapter(limit,offset);        etAddComment.addTextChangedListener(new TextWatcher() {            @OverrIDe            public voID onTextChanged(CharSequence s,int start,int before,int count) {                if (s.toString().trim().length() == 0) {                    btnsubmit.setEnabled(false);                } else {                    btnsubmit.setEnabled(true);                }            }            @OverrIDe            public voID beforeTextChanged(CharSequence s,int count,int after) {                // Todo auto-generated method stub            }            @OverrIDe            public voID afterTextChanged(Editable s) {                // Todo auto-generated method stub            }        });    }    @OverrIDe    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_detail_law,menu);        return true;    }    @OverrIDe    public boolean onoptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button,so long        // as you specify a parent activity in AndroIDManifest.xml.        int ID = item.getItemID();        //noinspection SimplifiableIfStatement        if (ID == R.ID.action_settings) {            return true;        }        return super.onoptionsItemSelected(item);    }    @OverrIDe    public voID onScrollStateChanged(AbsListVIEw vIEw,int scrollState) {    }    @OverrIDe    public voID onScroll(AbsListVIEw absListVIEw,int firstVisibleItem,int visibleItemCount,int totalitemCount) {        switch(ListVIEw.getID()) {            case R.ID.commentDialogListVIEw:                Log.d("SCRolL","scroll");                boolean loadMore =  firstVisibleItem + visibleItemCount >= totalitemCount-1;                if (loadMore) {                    page += 1; //                   offset = (page * limit) - limit + 1; //                   fillAdapter(limit,offset);//                    commentsAdapter.notifyDataSetChanged(); Todo                }        }    }    @OverrIDe    public voID onItemClick(AdapterVIEw<?> parent,VIEw vIEw,int position,long ID) {    }    public voID fillAdapter(int limit,int offset) {        ServerRequest serverRequest = new ServerRequest(this);        Log.e("LAWID BEFORE REQUEST",String.valueOf(lawID));        serverRequest.fetchCommentsInBackground(lawID,limit,offset,new GetCommentsCallback() {            @OverrIDe            public voID done(List<Comment> comments) {                commentsAdapter = new CommentsAdapter(getApplicationContext(),R.layout.comment_item,comments);                ListVIEw.setAdapter(commentsAdapter);                activityCommentList = commentsAdapter.getList();            }        });    }    public voID loadData(int limit,new GetCommentsCallback() {            @OverrIDe            public voID done(List<Comment> comments) {                // Updating parsed JsON data into ListVIEw                for (Comment comment : comments) {                    Log.d("COMMENT OBJECT",comment.getText());                    activityCommentList.add(comment);                }            }        });    }    /**     * Handle click events,comments adding     * @param v     */    @OverrIDe    public voID onClick(VIEw v) {        switch (v.getID()) {            case R.ID.commentsDialogsubmit:                String text = String.valueOf(etAddComment.getText());                Date dt = new Date();                Log.d("Click","Click");                if (userLocalStore.isUserLoggedIn()) {                    Log.e("LAW ID NEW COMM",String.valueOf(lawID));                    Comment comment = new Comment(text,dt,user,lawID);                    addComment(comment);                    etAddComment.setText("");                    //notifyData(limit,offset);                    limit = 15;                    offset = 0;                    fillAdapter(limit,offset);                    commentsAdapter.notifyDataSetChanged();                    Log.e("NUMBER OF COMMENTS",String.valueOf(activityCommentList.size()));                }                break;        }    }    /**     * Insert comment     * @param comment     */    public voID addComment(Comment comment) {        ServerRequest serverRequest = new ServerRequest(this);        serverRequest.storeCommentInBackground(comment,new GetCommentsCallback() {            @OverrIDe            public voID done(List<Comment> List) {                Log.d("Comment","Comment was added.");            }        });    }    private voID dumpIntent(Intent i) {        Bundle bundle = i.getExtras();        if (bundle != null) {            Set<String> keys = bundle.keySet();            Iterator<String> it = keys.iterator();            Log.e("EXTRAS","DumPing Intent start");            while (it.hasNext()) {                String key = it.next();                Log.e("EXTRAS","[" + key + "=" + bundle.get(key) + "]");            }            Log.e("EXTRAS","DumPing Intent end");        }    }}

解:

我添加了VIEwHolder vIEwHolder = v.getTag();在每个监听器中(以及在每个按钮上的getVIEw中的setTag(vIEwHolder)之前)

@OverrIDe    public VIEw getVIEw(int position,VIEwGroup parent) {        if (convertVIEw == null) {            convertVIEw = inflater.inflate(R.layout.law_item,false);            this.convertVIEw = convertVIEw;            vIEwHolder = new VIEwHolder();            vIEwHolder.position = position;            vIEwHolder.tvname = (TextVIEw) convertVIEw.findVIEwByID(R.ID.lawItemname);            vIEwHolder.tvDescription = (TextVIEw) convertVIEw.findVIEwByID(R.ID.lawItemDescription);            vIEwHolder.tvstatus = (TextVIEw) convertVIEw.findVIEwByID(R.ID.lawItemStatus);            vIEwHolder.btnDownVote = (button) convertVIEw.findVIEwByID(R.ID.lawItemDownVote);            vIEwHolder.btnUpVote = (button) convertVIEw.findVIEwByID(R.ID.lawItemUpVote);            vIEwHolder.btnMakeComment = (button) convertVIEw.findVIEwByID(R.ID.lawItemmakeComment);            vIEwHolder.btnMakeComment.setTag(vIEwHolder);            vIEwHolder.btnDownVote.setTag(vIEwHolder);            vIEwHolder.btnUpVote.setTag(vIEwHolder);            convertVIEw.setTag(vIEwHolder);        }        else {            vIEwHolder = (VIEwHolder) convertVIEw.getTag();            Log.d("VIEw holder","get tag");        }        vIEwHolder.currentLaw = getItem(position);        Log.d("VIEw holder",String.valueOf(vIEwHolder.currentLaw.getID()));        vIEwHolder.tvname.setText(vIEwHolder.currentLaw.getname());        vIEwHolder.tvDescription.setText(vIEwHolder.currentLaw.getDescription());        vIEwHolder.tvstatus.setText(vIEwHolder.currentLaw.getStateValue());        setSurfacescolors();        disableIfVoted();        vIEwHolder.btnMakeComment.setonClickListener(onCommentClickListener);        vIEwHolder.btnDownVote.setonClickListener(onDowvnVoteClickListener);        vIEwHolder.btnUpVote.setonClickListener(onUpVoteClickListener);     //   vIEwHolder.btnMakeComment.setonClickListener(onCommentClickListener);        return convertVIEw;    }    @OverrIDe    public long getItemID(int position) {        return laws.get(position).getID();    }    @OverrIDe    public Law getItem(int position) {        return laws.get(position);    }    /**     * On upVote Listener     */    private VIEw.OnClickListener onUpVoteClickListener = new VIEw.OnClickListener() {        @OverrIDe        public voID onClick(VIEw v) {            VIEwHolder vIEwHolder = (VIEwHolder) v.getTag();            if (userLocalStore.isUserLoggedIn()) {                isVotedStorage.setVoted(true,DialogSignInActivity.class));            }        }    };    /**     * On downVote Listener     */    private VIEw.OnClickListener onDowvnVoteClickListener = new VIEw.OnClickListener() {        @OverrIDe        public voID onClick(VIEw v) {            VIEwHolder vIEwHolder = (VIEwHolder) v.getTag();            if (userLocalStore.isUserLoggedIn()) {                isVotedStorage.setVoted(true,DialogSignInActivity.class));            }        }    };    /**     * On comment Listener,open comment dialog     */    private VIEw.OnClickListener onCommentClickListener = new VIEw.OnClickListener() {        @OverrIDe        public voID onClick(VIEw v) {            VIEwHolder vIEwHolder = (VIEwHolder) v.getTag();            if (userLocalStore.isUserLoggedIn()) {                Log.d("ON CliCK LAW ID",DialogSignInActivity.class));            }        }    };
解决方法 您每次都会获得最后一个ID /最后一行位置,因为最后一个视图最后会显示

要在按钮上单击行位置,可以将postion设置为按钮的标签,并在onclickListner中检查该标签

例如,在你的getvIEw()方法中,将position作为标记放在vIEwHolder.btnMakeComment按钮中

vIEwHolder.btnMakeComment.setTag(位置);并在OnClickListner检查标签int position =(int)v.getTag();

总结

以上是内存溢出为你收集整理的android – listview项目中的OnClickListener始终占据最后一行全部内容,希望文章能够帮你解决android – listview项目中的OnClickListener始终占据最后一行所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1125577.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-30
下一篇 2022-05-30

发表评论

登录后才能评论

评论列表(0条)

保存