位于ListView行的按钮始终在最后一行中触发

时间:2017-04-22 09:06:03

标签: java android listview custom-adapter

我有一个listview(不是recyclerView),其中每一行都有一个按钮,一对textview和一个EditText。 一旦我点击特定按钮(“editTremp”),我希望EditText进入编辑模式。

我的问题是:每次按下按钮(无论哪一行),它只会在列表视图的最后一行触发,而不是在按钮所在的特定行中触发。我见过很多答案,但没有人适合我。 我该如何解决?

这是listview_row的布局

  <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/listrow_drawable"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:elevation="5dp"
        android:paddingBottom="5dp"  >

        <EditText
            android:enabled="false"
            android:background="@color/transparent"
            style="@android:style/Widget.TextView"
            android:gravity="right"
            android:id="@+id/user_name"
            android:textColor="@color/black"
            android:textStyle="bold"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="90dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="5dp"
            android:layout_alignStart="@+id/user_msg"
            android:layout_toStartOf="@+id/user_image"
            android:layout_alignParentEnd="true" />

        <TextView
            android:id="@+id/user_date_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="8dp"
            android:layout_marginLeft="10dp"
            />

        <TextView
            android:id="@+id/user_phone"
            android:autoLink="phone"
            android:linksClickable="true"
            android:layout_width="wrap_content"
            android:textColor="@color/black"
            android:layout_height="wrap_content"
            android:layout_below="@+id/user_name"
            android:layout_alignParentRight="true"
            android:layout_marginBottom="5dp"
            android:layout_marginRight="10dp"
            android:visibility="gone"
            />

        <TextView
            android:id="@+id/user_msg"
            android:textColor="@color/black"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:layout_marginRight="90dp"
            android:layout_marginLeft="10dp"
            android:layout_marginBottom="2dp"
            android:layout_below="@+id/user_name" />

        <TextView
            android:id="@+id/user_extra"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:gravity="right"
            android:layout_marginRight="90dp"
            android:layout_marginLeft="10dp"
            android:layout_below="@+id/user_msg" />

        <ImageButton
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:background="@mipmap/ic_remove"
            android:id="@+id/remove"
            android:layout_alignParentStart="true"
            android:visibility="gone"
            android:layout_marginLeft="5dp"
            android:layout_below="@+id/user_extra"/>

        <ImageButton
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:id="@+id/edit"
            android:background="@mipmap/ic_edit"
            android:layout_toEndOf="@+id/remove"
            android:visibility="gone"
            android:layout_below="@+id/user_extra"
            android:layout_marginLeft="5dp"/>

        <ImageButton
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:id="@+id/phone_btn"
            android:background="@mipmap/ic_phone"
            android:onClick="makePhoneCall"
            android:layout_marginLeft="5dp"
            android:layout_below="@+id/user_extra"/>

        <ImageButton
            android:background="@mipmap/ic_launcher_submittext"
            android:layout_toEndOf="@+id/edit"
            android:visibility="gone"
            android:layout_below="@+id/user_extra"
            android:layout_marginLeft="5dp"
            android:id="@+id/submitText"
            android:layout_width="30dp"
            android:layout_height="30dp" />

        <TextView
            android:id="@+id/user_uid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/user_date_time"
            android:layout_alignStart="@+id/user_msg"
            android:text="hello"
            android:visibility="gone"/>

        <ImageView
            android:id="@+id/user_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/user_photo_drawable"
            android:src="@drawable/ic_action_car"
            android:layout_marginRight="10dp"
            android:layout_alignTop="@+id/user_name"
            android:layout_alignParentEnd="true"
            android:layout_marginTop="5dp"/>

    </RelativeLayout>

这是我的自定义适配器,点击此处的“editTremp”按钮

 public class personalZoneAdapter extends ArrayAdapter<TrempData>  {

    private TextView  msg , extra,phone ,date_time ,uid ;
    private EditText name ;
    private ImageButton deleteTremp , editTremp , phoneBtn , submitText ;
    private ImageView sideview;
    private int layoutResource;
    private FirebaseAuth firebaseAuth;
    private DatabaseReference mDatabase;

    public personalZoneAdapter(Context context, int layoutResource, ArrayList<TrempData> list) {
        super(context, layoutResource, list);
        this.layoutResource = layoutResource;
        firebaseAuth = FirebaseAuth.getInstance();
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Posts");
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view = convertView;

        if (view == null) {
            final LayoutInflater Inflater = LayoutInflater.from(getContext());
            view = Inflater.inflate(layoutResource, null);
        }

        final TrempData data = getItem(position);

        //data.setPos(position);
        //int[] androidColors = getContext().getResources().getIntArray(R.array.androidcolors);
        //int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];

        if (data != null) {
            name = (EditText) view.findViewById(R.id.user_name);
            phone = (TextView) view.findViewById(R.id.user_phone);
            date_time = (TextView) view.findViewById(R.id.user_date_time);
            msg = (TextView) view.findViewById(R.id.user_msg);
            extra = (TextView) view.findViewById(R.id.user_extra);
            uid = (TextView) view.findViewById(R.id.user_uid);
            deleteTremp = (ImageButton)view.findViewById(R.id.remove);
            editTremp = (ImageButton)view.findViewById(R.id.edit);
            phoneBtn = (ImageButton)view.findViewById(R.id.phone_btn);
            submitText = (ImageButton)view.findViewById(R.id.submitText);
            sideview = (ImageView)view.findViewById(R.id.user_image);

            if (name != null & phone != null & msg != null & date_time != null & uid != null) {
                name.setText(data.get_name());
                //name.setTextColor(randomAndroidColor);
                phone.setText(data.get_phone());
                date_time.setText(data.get_timestamp());
                msg.setText(data.get_from() + "--> " + data.get_to() + ", " + data.get_date() + ", " + data.get_time());
                uid.setText(data.get_uid());

                editTremp.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        submitText.setVisibility(View.VISIBLE);
                        name.setBackground(new ColorDrawable(WHITE));
                        name.setEnabled(true);
                        name.setCursorVisible(true);
                        name.setFocusableInTouchMode(true);
                        name.setInputType(InputType.TYPE_CLASS_TEXT);
                        name.requestFocus();

                    }
                });

                submitText.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDatabase.child("Posts").addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                                    TrempData tremp = getItem(position);
                                    if (ds.getKey().toString().equals(tremp.get_key())) {
                                        name.setEnabled(false);
                                        String new_name = name.getText().toString();
                                        name.setBackground(new ColorDrawable(TRANSPARENT));
                                        submitText.setVisibility(View.GONE);
                                        data.set_name(new_name);
                                        mDatabase.child(ds.getKey().toString()).child("_name").setValue(new_name);
                                        notifyDataSetChanged();
                                        //Toast.makeText(getContext(),"הטרמפ עודכן בהצלחה" + position,Toast.LENGTH_SHORT).show();
                                        break;
                                    }
                                }
                            }
                            @Override
                            public void onCancelled(DatabaseError databaseError) {

                            }
                        });
                    }
                });


                phoneBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + data.get_phone()));
                        getContext().startActivity(i);
                    }
                });




                deleteTremp.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        mDatabase.addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                                    TrempData tremp = getItem(position);
                                    if (ds.getKey().toString().equals(tremp.get_key())) {
                                        mDatabase.child(ds.getKey().toString()).removeValue();
                                        notifyDataSetChanged();
                                        //Toast.makeText(getContext(),"הטרמפ נמחק בהצלחה",Toast.LENGTH_SHORT).show();
                                        break;
                                    }
                                }
                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {
                                Toast.makeText(getContext(),"ישנה בעיה. אנא נסה שוב",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });


                if(data.get_extras().length() == 0) extra.setVisibility(View.GONE);
                extra.setText("הערות:" + " " + data.get_extras());

                if(firebaseAuth.getCurrentUser().getUid().equals(uid.getText())){
                    deleteTremp.setVisibility(View.VISIBLE);
                    editTremp.setVisibility(View.VISIBLE);
                    phoneBtn.setVisibility(View.GONE);
                    sideview.setColorFilter(Color.rgb(255,164,30));
                }
                else{

                    submitText.setVisibility(View.GONE);
                    deleteTremp.setVisibility(View.GONE);
                    editTremp.setVisibility(View.GONE);
                    phoneBtn.setVisibility(View.VISIBLE);
                    sideview.setColorFilter(Color.rgb(176,176,176));
                }
            }
        }
        return view;
    }
}

这是活动

    public class PersonalZone extends AppCompatActivity {
    private ListView personalzone_lv;
    private personalZoneAdapter adapter;
    private ArrayList<TrempData> personaldataArrayList = new ArrayList<>();
    private FirebaseAuth mAuth;
    private DatabaseReference mDatabase;
    private FloatingActionButton logoutbtn , addbtn , userprofileBtn;


    public PersonalZone(){}

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

        mAuth = FirebaseAuth.getInstance();
        mDatabase = FirebaseDatabase.getInstance().getReference();
        logoutbtn = (FloatingActionButton) findViewById(R.id.logout);
        addbtn = (FloatingActionButton) findViewById(R.id.floatingAdd);
        userprofileBtn = (FloatingActionButton) findViewById(R.id.profile);
        personalzone_lv = (ListView)findViewById(R.id.myzone_listview);
        adapter = new personalZoneAdapter(this,R.layout.personal_zone_listview_row,personaldataArrayList);
        personalzone_lv.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        updateMyZone();
        personalzone_lv.setEmptyView(findViewById(R.id.emptylist));

        logoutbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAuth.signOut();
            }
        });

        addbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager manager = getFragmentManager();
                Addtremp trempDialog = new Addtremp();
                trempDialog.show(manager, "Addtremp");
            }
        });

        userprofileBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(PersonalZone.this, UserProfile.class));
            }
        });

    }

    public void updateMyZone(){

        mDatabase.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                personaldataArrayList.clear();
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    TrempData trempData2 = ds.getValue(TrempData.class);
                    if (mAuth.getCurrentUser().getUid().toString().equals((ds.getValue(TrempData.class).get_uid()))) {
                        personaldataArrayList.add(0, trempData2);
                        personalzone_lv.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                personaldataArrayList.clear();
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    TrempData trempData2 = ds.getValue(TrempData.class);
                    if (mAuth.getCurrentUser().getUid().toString().equals((ds.getValue(TrempData.class).get_uid()))) {
                        personaldataArrayList.add(0, trempData2);
                        personalzone_lv.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

    /*@Override
    public void onBackPressed() {

        this.finish();
        overridePendingTransition  (R.anim.slide_out, R.anim.slide_out);
    }*/
}

更新 ViewHolder的解决方案效果很好 !! 这是ViewHolder的新适配器代码。如果你对改进有任何建议,那就太棒了!

    public class personalZoneAdapter extends ArrayAdapter<TrempData>  {

    static class ViewHolderItem{
        private TextView  msg , extra,phone ,date_time ,uid ;
        private EditText name ;
        private ImageButton deleteTremp , editTremp , phoneBtn , submitText ;
        private ImageView sideview;
    }


    private int layoutResource;
    private FirebaseAuth firebaseAuth;
    private DatabaseReference mDatabase;

    public personalZoneAdapter(Context context, int layoutResource, ArrayList<TrempData> list) {
        super(context, layoutResource, list);
        this.layoutResource = layoutResource;
        firebaseAuth = FirebaseAuth.getInstance();
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Posts");
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view = convertView;
        final ViewHolderItem viewHolder;

        if (view == null) {
            final LayoutInflater Inflater = LayoutInflater.from(getContext());
            view = Inflater.inflate(layoutResource, null);

            viewHolder = new ViewHolderItem();
            viewHolder.name = (EditText) view.findViewById(R.id.user_name);
            viewHolder.phone = (TextView) view.findViewById(R.id.user_phone);
            viewHolder.date_time = (TextView) view.findViewById(R.id.user_date_time);
            viewHolder.msg = (TextView) view.findViewById(R.id.user_msg);
            viewHolder.extra = (TextView) view.findViewById(R.id.user_extra);
            viewHolder.uid = (TextView) view.findViewById(R.id.user_uid);
            viewHolder.deleteTremp = (ImageButton)view.findViewById(R.id.remove);
            viewHolder.editTremp = (ImageButton)view.findViewById(R.id.edit);
            viewHolder.phoneBtn = (ImageButton)view.findViewById(R.id.phone_btn);
            viewHolder.submitText = (ImageButton)view.findViewById(R.id.submitText);
            viewHolder.sideview = (ImageView)view.findViewById(R.id.user_image);

            view.setTag(viewHolder);
        }
        else{
            viewHolder = (ViewHolderItem) convertView.getTag();
        }

        final TrempData data = getItem(position);

        //data.setPos(position);
        //int[] androidColors = getContext().getResources().getIntArray(R.array.androidcolors);
        //int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];

        if (data != null) {

            if (viewHolder.name != null & viewHolder.phone != null & viewHolder.msg != null & viewHolder.date_time != null & viewHolder.uid != null) {
                viewHolder.name.setText(data.get_name());
                viewHolder.name.setTag(data._name);
                //name.setTextColor(randomAndroidColor);
                viewHolder.phone.setText(data.get_phone());
                viewHolder.name.setTag(data._phone);
                viewHolder.date_time.setText(data.get_timestamp());
                viewHolder.name.setTag(data._timestamp);
                viewHolder.msg.setText(data.get_from() + "--> " + data.get_to() + ", " + data.get_date() + ", " + data.get_time());
                viewHolder.uid.setText(data.get_uid());
                viewHolder.name.setTag(data._uid);

                viewHolder.editTremp.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        viewHolder.submitText.setVisibility(View.VISIBLE);
                        viewHolder.name.setBackground(new ColorDrawable(WHITE));
                        viewHolder.name.setEnabled(true);
                        viewHolder.name.setCursorVisible(true);
                        viewHolder.name.setFocusableInTouchMode(true);
                        viewHolder.name.setInputType(InputType.TYPE_CLASS_TEXT);
                        viewHolder.name.requestFocus();

                    }
                });

                viewHolder.submitText.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDatabase.addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                                    TrempData tremp = getItem(position);
                                    if (ds.getKey().toString().equals(tremp.get_key())) {
                                        viewHolder.name.setEnabled(false);
                                        String new_name = viewHolder.name.getText().toString();
                                        viewHolder.name.setBackground(new ColorDrawable(TRANSPARENT));
                                        viewHolder.submitText.setVisibility(View.GONE);
                                        data.set_name(new_name);
                                        mDatabase.child(ds.getKey().toString()).child("_name").setValue(new_name);
                                        notifyDataSetChanged();
                                        //Toast.makeText(getContext(),"הטרמפ עודכן בהצלחה" + position,Toast.LENGTH_SHORT).show();
                                        break;
                                    }
                                }
                            }
                            @Override
                            public void onCancelled(DatabaseError databaseError) {

                            }
                        });
                    }
                });


                viewHolder.phoneBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + data.get_phone()));
                        getContext().startActivity(i);
                    }
                });

                viewHolder.deleteTremp.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        mDatabase.addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                                    TrempData tremp = getItem(position);
                                    if (ds.getKey().toString().equals(tremp.get_key())) {
                                        mDatabase.child(ds.getKey().toString()).removeValue();
                                        notifyDataSetChanged();
                                        //Toast.makeText(getContext(),"הטרמפ נמחק בהצלחה",Toast.LENGTH_SHORT).show();
                                        break;
                                    }
                                }
                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {
                                Toast.makeText(getContext(),"ישנה בעיה. אנא נסה שוב",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });


                if(data.get_extras().length() == 0) viewHolder.extra.setVisibility(View.GONE);
                viewHolder.extra.setText("הערות:" + " " + data.get_extras());

                if(firebaseAuth.getCurrentUser().getUid().equals(viewHolder.uid.getText())){
                    viewHolder.deleteTremp.setVisibility(View.VISIBLE);
                    viewHolder.editTremp.setVisibility(View.VISIBLE);
                    viewHolder.phoneBtn.setVisibility(View.GONE);
                    viewHolder.sideview.setColorFilter(Color.rgb(255,164,30));
                }
                else{

                    viewHolder.submitText.setVisibility(View.GONE);
                    viewHolder.deleteTremp.setVisibility(View.GONE);
                    viewHolder.editTremp.setVisibility(View.GONE);
                    viewHolder.phoneBtn.setVisibility(View.VISIBLE);
                    viewHolder. sideview.setColorFilter(Color.rgb(176,176,176));
                }
            }
        }
        return view;
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用Recycleview并设置自定义适配器:

适配器:

<=

}

片段/活动中的Recyclerview:

UPDATE microsat_table
JOIN 
   (
   SELECT
       m.id,
       AVG(p.Coverage) AS avg -- MySQL has it's own average function
   FROM
       microsat_table m  
       INNER JOIN coverage_table p ON -- Change to INNER JOIN, your old WHERE clause had this effect anyway
           m.Seq_Name = p.Seq_Name -- Use '=' not 'Like' when looking for an exact match
   WHERE
        p.Start >= m.SSR_Start -- This WHERE clause is the most important change 
        AND p.End <= m.SSR_End -- You omitted it in your version
   GROUP BY
       m.id) AS qt 
ON microsat_table.id = qt.id 
SET microsat_table.avg = qt.avg;