#java #android
#java #Android
Вопрос:
1.Im очень новичок в программировании, и этот проект просит меня иметь две кнопки для инициализации карт и совершения телефонного звонка в этом listview
2.Im пытаюсь с помощью 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.0795961amp;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();
}
}
-
Это моя 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>
-
Я пытался использовать If и Cases, но я не знаю, правильно ли я реализую
Ответ №1:
Для 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>
Тогда применимый код в адаптере выглядит следующим образом:
ListAdapter.java
@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;
}
Комментарии:
1. Извините, но я не мог понять, где реализовать этот код, я могу поделиться остальным, и не могли бы вы направить меня, пожалуйста
2. я не знаю, как решить фрагментную часть, остальное работает нормально
3. В моем примере я хочу вызвать общедоступную функцию в коде, который объявил адаптер при нажатии кнопки. Для этого мне нужна была ссылка на этот код, который в моем случае был во фрагменте. В вашем случае это может быть ваше действие, создавшее адаптер. Итак, может быть, у вас был бы такой код: ArrayList<Modeldoc> ArrayList; Действие MyAction; //конструктор public ListViewAdapter(контекст context, список<Modeldoc> список моделей, действие theAction) { mContext = контекст; MyAction = Действие;
Ответ №2:
Это остальная часть кода, действие, в котором я это реализую
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>