繁体   English   中英

如何从适配器向列表视图添加两个按钮?

[英]How can i add two buttons to the listview from the adapter?

1.我对编程很陌生,这个项目要求我有两个按钮来初始化地图并在此列表视图中拨打电话

2.我正在尝试一个 if 但我不太了解,请帮忙

public class ListViewAdapter extends BaseAdapter{

    //variables
    Context mContext;
    LayoutInflater inflater;
    List<Modeldoc> modellist;
    ArrayList<Modeldoc> arrayList;

    //constructor
    public ListViewAdapter(Context context, List<Modeldoc> modellist) {
        mContext = context;
        this.modellist = modellist;
        inflater = LayoutInflater.from(mContext);
        this.arrayList = new ArrayList<Modeldoc>();
        this.arrayList.addAll(modellist);
    }

    public class ViewHolder{
        TextView mTitleTv, mDescTv, mDirTv, mNumTv, mZonTv;
        ImageView mIconIv;
    }

    @Override
    public int getCount() {
        return modellist.size();
    }

    @Override
    public Object getItem(int i) {
        return modellist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int postition, View view, final ViewGroup parent) {
        final ViewHolder holder;
        if (view==null){
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.rowdoct, null);

            //locate the views in rowdoct.xml
            holder.mTitleTv = view.findViewById(R.id.mainTitle);
            holder.mDescTv = view.findViewById(R.id.mainDesc);
            holder.mDirTv = view.findViewById(R.id.mainDir);
            holder.mNumTv = view.findViewById(R.id.mainNum);
            holder.mZonTv = view.findViewById(R.id.mainZon);
            holder.mIconIv = view.findViewById(R.id.mainIcon);

            view.setTag(holder);

        }
        else {
            holder = (ViewHolder)view.getTag();
        }
        //set the results into textviews
        holder.mTitleTv.setText(modellist.get(postition).getTitle());
        holder.mDescTv.setText(modellist.get(postition).getDesc());
        holder.mDirTv.setText(modellist.get(postition).getDir());
        holder.mNumTv.setText(modellist.get(postition).getNum());
        holder.mZonTv.setText(modellist.get(postition).getZon());
        //set the result in imageview
        holder.mIconIv.setImageResource(modellist.get(postition).getIcon());

        //listview item clicks
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //code later
                if (modellist.get(postition).getTitle().equals("Dr. Lorgio Rivera Calvo")){
                    //1

                    if (view.getId() == R.id.mainZon) {
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse("tel:69777300"));
                        mContext.startActivity(intent);
                    } else if (view.getId() == R.id.mainTitle) {
                        Uri gmmIntentUri = Uri.parse("google.navigation:q=-16.5418275,-68.0795961&avoid=tf");
                        Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
                        mapIntent.setPackage("com.google.android.apps.maps");
                        mContext.startActivity(mapIntent);
                    }

                }
                if (modellist.get(postition).getTitle().equals("Dr. Jorge Salazar")){
                    //2
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse("tel:69777300"));
                    mContext.startActivity(intent);
                }
                if (modellist.get(postition).getTitle().equals("Dr. Kurt Gonzalo Paulsen Sandi")){
                    //3
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse("tel:22114333"));
                    mContext.startActivity(intent);
                }
            }
        });


        return view;
    }

    //filter
    public void filter(String charText){
        charText = charText.toLowerCase(Locale.getDefault());
        modellist.clear();
        if (charText.length()==0){
            modellist.addAll(arrayList);
        }
        else {
            for (Modeldoc modeldoc : arrayList){
                if (modeldoc.getTitle().toLowerCase(Locale.getDefault())
                        .contains(charText)){
                    modellist.add(modeldoc);
                }
            }
        }
        notifyDataSetChanged();
    }
}

  1. 这是我的 xml 模型,它转到我在不同活动中的列表视图

    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:gravity="center" android:layout_margin="16dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center_vertical"> <ImageView android:id="@+id/mainIcon" android:src="@drawable/ic_launcher_background" android:layout_width="60dp" android:layout_height="60dp" android:layout_marginEnd="16dp" android:clickable="true" android:onClick="onClick"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:gravity="center" android:layout_marginLeft="5dp" android:layout_marginStart="5dp"> <TextView android:id="@+id/mainTitle" android:text="Title" android:textStyle="bold" android:textSize="20sp" android:textAppearance="@style/TextAppearance.AppCompat.Title" android:layout_width="match_parent" android:layout_height="wrap_content"/> <TextView android:id="@+id/mainDesc" android:textAppearance="@style/TextAppearance.AppCompat.Headline" android:text="Description" android:textSize="16sp" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout> <TextView android:id="@+id/mainDir" android:text="Dirección" android:textSize="16sp" android:textAppearance="@style/TextAppearance.AppCompat.Body1" android:layout_marginTop="16dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/mainNum" android:text="0000000" android:textStyle="bold" android:textSize="12sp" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="4dp" android:paddingBottom="8dp"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:paddingTop="10dp" android:id="@+id/mainZon" android:text="SUR · Calacoto" android:textSize="12sp" android:textStyle="bold" android:textAppearance="@style/TextAppearance.AppCompat.Display1" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:layout_alignEnd="@id/mainZon" android:layout_width="80dp" android:layout_height="40dp" android:text="LLAMAR" android:textStyle="bold" android:background="#E9E9E9" android:textColor="#E91E63" android:gravity="center" android:layout_marginRight="16dp" android:clickable="true" android:onClick="onClick"/> </RelativeLayout> </LinearLayout>

  2. 我试过使用 If 和 Cases,但我不知道我是否以正确的方式实施

对于 ListViews,使用了两个布局文件。 一个指定整个列表的布局,另一个指定 list_item 的布局。

列表项布局:list_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="wrap_content" 
        android:baselineAligned="false"
        android:orientation="horizontal">

    <TextView
        android:id="@+id/contact_phone"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginBottom="2dp"
        android:layout_marginLeft="5dp"
        android:layout_marginStart="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginEnd="5dp"
        android:layout_weight="0.73"
        android:background="#00000000"
        android:gravity="start|center_vertical"
        android:text=""
        android:textColor="#FFFFFFFF"
        android:textSize="16sp" 
        />

    <Button
        android:id="@+id/do_phone"
        android:layout_width="100dp"
        android:layout_height="match_parent"
        android:text="@string/call"
        android:textSize="16sp"
        android:textColor="#FFFFFFFF"
        android:background="@android:color/holo_red_dark"
        />
   <Button
        android:id="@+id/do_map"
        android:layout_width="100dp"
        android:layout_height="match_parent"
        android:text="@string/map"
        android:textSize="16sp"
        android:textColor="#FFFFFFFF"
        android:background="@android:color/holo_red_dark"
        />
    </LinearLayout>

然后,适配器中的适用代码是这样的:

列表适配器

@Override
public View getView(int position, View convertView, ViewGroup parent) {

if (convertView == null) {
    LayoutInflater mInflater = (LayoutInflater)
            context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    convertView = mInflater.inflate(R.layout.list_item, null);
}

Button btnCall = (Button) convertView.findViewById(R.id.do_phone);
btnCall.setTag(position);
btnCall.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        Integer position = (Integer)v.getTag();
        // This calls a method back in the fragment or activity that owns the adapter
        fragment.callItemList(position);
    }
});

Button btnMap = (Button) convertView.findViewById(R.id.do_map);
btnMap.setTag(position);
btnMap.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        Integer position = (Integer)v.getTag();
        // This calls a method back in the fragment or activity that owns the adapter
        fragment.mapItemList(position);
    }
});

TextView txtContactPhone = (TextView) convertView.findViewById(R.id.contact_phone); 

return convertView;
}

这是代码的其余部分,我正在实现这个的活动

class Medico extends AppCompatActivity {

private Spinner spinner;

ListView listView;
ListViewAdapter adapter;
String[] title;
String[] description;
String[] direccion;
String[] numero;
String[] zona;
int[] icon;
ArrayList<Modeldoc> arrayList = new ArrayList<Modeldoc>();

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

    spinner = findViewById(R.id.spinner);

    List<String> categories = new ArrayList<>();
    categories.add(0,"Filtrar por especialidad");
    categories.add("Alergología");
    categories.add("Cardiología");

    ArrayAdapter<String> dataAdapter;
    dataAdapter = new ArrayAdapter<>( this, android.R.layout.simple_list_item_1, categories);

    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner.setAdapter(dataAdapter);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
            if (parent.getItemAtPosition(position).equals("Filtrar por especialidad"))
            {

            } else
            {
                String item = parent.getItemAtPosition(position).toString();

                Toast.makeText(parent.getContext(),"Ver:"+item, Toast.LENGTH_SHORT).show();

                if (parent.getItemAtPosition(position).equals("Alergología"))
                {
                    Intent intent = new Intent( Medico.this, Alergologia.class);
                    startActivity(intent);
                }

                if (parent.getItemAtPosition(position).equals("Cardiología"))
                {
                    Intent intent = new Intent( Medico.this, Cardiologia.class);
                    startActivity(intent);
                }
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });



    ActionBar actionBar = getSupportActionBar();
    actionBar.setTitle("Médicos");

    title = new String[]{
            "Dr. Jorge Salazar",
            "Dr. Kurt Gonzalo Paulsen Sandi",
            "Dr. Oswaldo Camberos B."};
    description = new String[]{
            " Pediatra - Terapia Intensiva",
            " Pediatra",
            " Pediatra - Neonatólogo - Terapia Intensiva"};
    direccion = new String[]{" Av. 6 de Agosto esq. Cordero, Edif. Mercurio - mezzanine Of. 2 ",
            "Calle Clavijo entre Av.Arce y Av. 6 de Agosto. Edificio San Patricio # 2896. Primer piso consultorio 111.",
            "Calle Clavijo entre Av.Arce y Av. 6 de Agosto. Edificio San Patricio # 2896. Primer piso consultorio 111."};
    numero = new String[]{
            "69777300",
            "22114333",
            "22792635"};
    zona = new String[]{
            "SUR · Calacoto",
            "SUR . Calacoto ",
            "SUR · Calacoto"};
    icon = new int[]{R.drawable.ic_doctora, R.drawable.ic_vacio, R.drawable.ic_doctora};

    listView = findViewById(R.id.listView);

    for (int i =0; i<title.length; i++){
        Modeldoc modeldoc = new Modeldoc(title[i], description[i], direccion[i], numero[i], zona[i], icon[i]);
        //bind all strings in an array
        arrayList.add(modeldoc);
    }

    //pass results to listViewAdapter class
    adapter = new ListViewAdapter(this, arrayList);

    //bind the adapter to the listview
    listView.setAdapter(adapter);

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);

    MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
    SearchView searchView = (SearchView)myActionMenuItem.getActionView ();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String s) {
            if (TextUtils.isEmpty(s)){
                adapter.filter("");
                listView.clearTextFilter();
            }
            else {
                adapter.filter(s);
            }
            return true;
        }
    });
    return true;
}
}

这是实现列表的模型activity_medico

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:theme="@style/Base.Theme.AppCompat.Light.DarkActionBar"
    tools:context=".Medico">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="160dp"
        android:scaleType="centerCrop"
        android:src="@drawable/covertop"/>

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            app:cardCornerRadius="10dp"
            app:cardBackgroundColor="#B3FFFFFF">

    <SearchView
        android:id="@+id/searchbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

        </androidx.cardview.widget.CardView>

    </RelativeLayout>

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            app:cardCornerRadius="40dp"
            app:cardBackgroundColor="@color/design_default_color_background">

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_centerVertical="true"
            android:textAlignment="viewStart"/>

        </androidx.cardview.widget.CardView>

    <Space
        android:id="@+id/spacer"
        android:layout_width="match_parent"
        android:layout_height="0.8dp"
        android:background="#7A7A7A"
        android:layout_marginBottom="8dp"/>

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@android:color/transparent"
        android:dividerHeight="10.0sp"
        android:paddingStart="8dp"
        android:paddingEnd="8dp">

    </ListView>

</LinearLayout>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM