我在活动中有一个可点击的列表视图。我想要的是当我从列表中单击时,它将转到片段。有谁知道它是如何完成的?
此外,如果用户点击列表时会有一种方式,它会打开一个新活动。
编辑:这是我的代码。
Activity_list.java
package com.example.beminix.dcar;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class Activity_list extends AppCompatActivity implements AdapterView.OnItemClickListener{
EstablishmentAdapter adapter = null;
ArrayList<Establishments> establishments = null;
ListView myEstListView;
SearchView mySearchView = null ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
establishments = new ArrayList<>();
establishments = populateEstablishmentsData(establishments);
mySearchView = (SearchView) findViewById( R.id.mySearchView ) ;
myEstListView = (ListView) findViewById(R.id.myEstListView);
adapter = new EstablishmentAdapter(this, establishments);
myEstListView.setAdapter(adapter);
mySearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
// Here implement search logic
adapter.getFilter().filter(s);
adapter.notifyDataSetChanged();
return false;
}
});
if(getSupportActionBar() != null)
{
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
ListView your_list_view = (ListView) findViewById(R.id.myEstListView);
}
private ArrayList<Establishments> populateEstablishmentsData(ArrayList<Establishments> establishments) {
establishments.add(new Establishments("Art Gallery", 1, R.drawable.art_gallery_icon));
establishments.add(new Establishments("ATM", 2, R.drawable.atm_icon));
establishments.add(new Establishments("Bakery", 3, R.drawable.bakery_icon));
establishments.add(new Establishments("Bank",4, R.drawable.bank_icon));
establishments.add(new Establishments("Bar",5, R.drawable.bar_icon));
establishments.add(new Establishments("Book Store",6, R.drawable.book_store_icon));
establishments.add(new Establishments("Bus Station/Bus Terminal",7, R.drawable.bus_terminal_icon));
establishments.add(new Establishments("Cafe",8, R.drawable.cafe_icon));
establishments.add(new Establishments("Car Services",9, R.drawable.car_services_icon));
establishments.add(new Establishments("Car Retail Store",10, R.drawable.car_services_icon));
establishments.add(new Establishments("Cemetery",11, R.drawable.cemetery_icon));
establishments.add(new Establishments("Department Store",12, R.drawable.department_store_icon));
establishments.add(new Establishments("Electronics Store",13, R.drawable.electronic_store_icon));
establishments.add(new Establishments("Fast Food Chain",14, R.drawable.fast_food_icon));
establishments.add(new Establishments("Fire Station",15, R.drawable.fire_station_icon));
establishments.add(new Establishments("Flower Shop",16, R.drawable.flowershop_icon));
establishments.add(new Establishments("Gas Station",17, R.drawable.gas_station_icon));
establishments.add(new Establishments("Government Office",18, R.drawable.gov_office_icon));
establishments.add(new Establishments("Gym",19, R.drawable.gym_icon));
establishments.add(new Establishments("Hospital",20, R.drawable.hospital_icon));
establishments.add(new Establishments("Hotel",21, R.drawable.hotel_icon));
establishments.add(new Establishments("Ice Cream Shop",22, R.drawable.ice_cream_icon));
establishments.add(new Establishments("Insurance Agency",23, R.drawable.insurance_icon));
establishments.add(new Establishments("Jewelry Store",24, R.drawable.jewelry_icon));
establishments.add(new Establishments("Laundry Shop Services",25, R.drawable.laundry_icon));
establishments.add(new Establishments("Library",26, R.drawable.library_icon));
establishments.add(new Establishments("Museum",27, R.drawable.museum_icon));
establishments.add(new Establishments("Park",28, R.drawable.park_icon));
establishments.add(new Establishments("Pet Store",29, R.drawable.pet_store_icon));
establishments.add(new Establishments("Pharmacy",30, R.drawable.pharmacy_icon));
establishments.add(new Establishments("Place of Worship",31, R.drawable.place_of_worship_icon));
establishments.add(new Establishments("Police Station",32, R.drawable.police_station_icon));
establishments.add(new Establishments("Restaurant",33, R.drawable.restaurant_icon));
establishments.add(new Establishments("School",34, R.drawable.school_icon));
establishments.add(new Establishments("Shoes Store",35, R.drawable.shoe_store_icon));
establishments.add(new Establishments("Shopping Mall",36, R.drawable.shopping_mall_icon));
establishments.add(new Establishments("Spa",10, R.drawable.spa_icon));
establishments.add(new Establishments("Travel Agency",37, R.drawable.travel_service_icon));
establishments.add(new Establishments("Zoo",38, R.drawable.zoo_icon));
return establishments;
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Establishments c = adapter.getItem(position);
Toast.makeText(Activity_list.this, " " + c.geteName() , Toast.LENGTH_SHORT).show();
//startActivity(new Intent(this, establishments[position].activityClass));
// Intent intent = new Intent(this, SecondFragment.class);
//startActivity(intent);
// android.app.FragmentManager fragmentManager = getFragmentManager();
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(item.getItemId()==android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
@SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
String info = ((TextView) v).getText().toString(); //text of position selected
}
};
}
EstablishmentAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class EstablishmentAdapter extends ArrayAdapter<Establishments> {
ArrayList<Establishments> establishments, tempEstablishment, suggestions;
public EstablishmentAdapter(Context context, ArrayList<Establishments> objects) {
super(context, R.layout.customer_row, R.id.tvCustomer, objects);
this.establishments = objects;
this.tempEstablishment = new ArrayList<Establishments>(objects);
this.suggestions = new ArrayList<Establishments>(objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return initView(position, convertView, parent);
}
private View initView(int position, View convertView, ViewGroup parent) {
Establishments establish = getItem(position);
if (convertView == null) {
if (parent == null)
convertView = LayoutInflater.from(getContext()).inflate(R.layout.customer_row, null);
else
convertView = LayoutInflater.from(getContext()).inflate(R.layout.customer_row, parent, false);
}
TextView txtCustomer = (TextView) convertView.findViewById(R.id.tvCustomer);
ImageView ivCustomerImage = (ImageView) convertView.findViewById(R.id.ivCustomerImage);
if (txtCustomer != null)
txtCustomer.setText(establish.geteName() + " " );
if (ivCustomerImage != null)
ivCustomerImage.setImageResource(establish.getEstPhoto());
return convertView;
}
@Override
public Filter getFilter() {
return myFilter;
}
Filter myFilter =new Filter() {
@Override
public CharSequence convertResultToString(Object resultValue) {
Establishments customer =(Establishments)resultValue ;
return customer.geteName() + " ";
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
suggestions.clear();
for (Establishments cust : tempEstablishment) {
if (cust.geteName().toLowerCase().startsWith(constraint.toString().toLowerCase())) {
suggestions.add(cust);
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = suggestions;
filterResults.count = suggestions.size();
return filterResults;
} else {
return new FilterResults();
}
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ArrayList<Establishments> c = (ArrayList<Establishments> )results.values ;
if (results != null && results.count > 0) {
clear();
for (Establishments cust : c) {
add(cust);
notifyDataSetChanged();
}
}
else{
clear();
notifyDataSetChanged();
}
}
};
}
Establishments.java
package com.example.beminix.dcar;
/**
* Created by Beminix on 09/02/2017.
*/
public class Establishments {
private String estName = "";
private int id = 0;
private int estPhoto = -1;
public Establishments(String ename, int id, int pic) {
this.estName = ename;
this.id = id;
this.estPhoto = pic;
}
public String geteName() {
return estName;
}
public void seteName(String esName) {
this.estName = esName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getEstPhoto() {
return estPhoto;
}
public void setEstPhoto(int estPhoto) {
this.estPhoto = estPhoto;
}
@Override
public String toString() {
return this.estName + " ";
}
}
搜索视图和列表视图显示并且可以单击。但我不知道用户何时从列表中点击并加载到片段或活动。 :(
答案 0 :(得分:0)
首先,您需要在代码中为ListView定义clickListener:
[your_list_view].setOnItemClickListener(mDeviceClickListener);
然后定义方法:
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
@SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
String info = ((TextView) v).getText().toString(); //text of position selected
} };
在您的activity_main.xml中,您需要创建一个FrameLayout,以便加载Fragment:
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
在为ListView创建的方法中,您需要像下面这样夸大Fragment:
Fragment newFragment = new YourFragmentClass();
FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
请注意“YouFragmentClass()”是处理Fragment时的类,这个类是这样的:
public class FragmentMain extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
final View view = inflater.inflate(R.layout.yourlayoutfilename, container, false);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Main");
}
}
如果您想更改活动,只需将此代码放在ListView的onClickListener中:
startActivity(new Intent(CurrentActivity.this,DestinationActivity.class));
希望有所帮助:)
编辑: 我设法改变活动和片段OnItemClick,该类应该如下所示:
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class Activity_list extends AppCompatActivity implements AdapterView.OnItemClickListener{
EstablishmentAdapter adapter = null;
ArrayList<Establishments> establishments = null;
ListView myEstListView;
SearchView mySearchView = null ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
establishments = new ArrayList<>();
establishments = populateEstablishmentsData(establishments);
mySearchView = (SearchView) findViewById(R.id.mySearchView ) ;
myEstListView = (ListView) findViewById(R.id.myEstListView);
adapter = new EstablishmentAdapter(this, establishments);
myEstListView.setAdapter(adapter);
myEstListView.setOnItemClickListener(mDeviceClickListener);
mySearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
adapter.getFilter().filter(s);
adapter.notifyDataSetChanged();
return false;
}
});
if(getSupportActionBar() != null)
{
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
private ArrayList<Establishments> populateEstablishmentsData(ArrayList<Establishments> establishments) {
establishments.add(new Establishments("Art Gallery", 1, R.drawable.art_gallery_icon));
establishments.add(new Establishments("ATM", 2, R.drawable.atm_icon));
establishments.add(new Establishments("Bakery", 3, R.drawable.bakery_icon));
establishments.add(new Establishments("Bank",4, R.drawable.bank_icon));
establishments.add(new Establishments("Bar",5, R.drawable.bar_icon));
establishments.add(new Establishments("Book Store",6, R.drawable.book_store_icon));
establishments.add(new Establishments("Bus Station/Bus Terminal",7, R.drawable.bus_terminal_icon));
establishments.add(new Establishments("Cafe",8, R.drawable.cafe_icon));
establishments.add(new Establishments("Car Services",9, R.drawable.car_services_icon));
establishments.add(new Establishments("Car Retail Store",10, R.drawable.car_services_icon));
establishments.add(new Establishments("Cemetery",11, R.drawable.cemetery_icon));
establishments.add(new Establishments("Department Store",12, R.drawable.department_store_icon));
establishments.add(new Establishments("Electronics Store",13, R.drawable.electronic_store_icon));
establishments.add(new Establishments("Fast Food Chain",14, R.drawable.fast_food_icon));
establishments.add(new Establishments("Fire Station",15, R.drawable.fire_station_icon));
establishments.add(new Establishments("Flower Shop",16, R.drawable.flowershop_icon));
establishments.add(new Establishments("Gas Station",17, R.drawable.gas_station_icon));
establishments.add(new Establishments("Government Office",18, R.drawable.gov_office_icon));
establishments.add(new Establishments("Gym",19, R.drawable.gym_icon));
establishments.add(new Establishments("Hospital",20, R.drawable.hospital_icon));
establishments.add(new Establishments("Hotel",21, R.drawable.hotel_icon));
establishments.add(new Establishments("Ice Cream Shop",22, R.drawable.ice_cream_icon));
establishments.add(new Establishments("Insurance Agency",23, R.drawable.insurance_icon));
establishments.add(new Establishments("Jewelry Store",24, R.drawable.jewelry_icon));
establishments.add(new Establishments("Laundry Shop Services",25, R.drawable.laundry_icon));
establishments.add(new Establishments("Library",26, R.drawable.library_icon));
establishments.add(new Establishments("Museum",27, R.drawable.museum_icon));
establishments.add(new Establishments("Park",28, R.drawable.park_icon));
establishments.add(new Establishments("Pet Store",29, R.drawable.pet_store_icon));
establishments.add(new Establishments("Pharmacy",30, R.drawable.pharmacy_icon));
establishments.add(new Establishments("Place of Worship",31, R.drawable.place_of_worship_icon));
establishments.add(new Establishments("Police Station",32, R.drawable.police_station_icon));
establishments.add(new Establishments("Restaurant",33, R.drawable.restaurant_icon));
establishments.add(new Establishments("School",34, R.drawable.school_icon));
establishments.add(new Establishments("Shoes Store",35, R.drawable.shoe_store_icon));
establishments.add(new Establishments("Shopping Mall",36, R.drawable.shopping_mall_icon));
establishments.add(new Establishments("Spa",10, R.drawable.spa_icon));
establishments.add(new Establishments("Travel Agency",37, R.drawable.travel_service_icon));
establishments.add(new Establishments("Zoo",38, R.drawable.zoo_icon));
return establishments;
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Establishments c = adapter.getItem(position);
Toast.makeText(Activity_list.this, " " + c.geteName() , Toast.LENGTH_SHORT).show();
//for some reason, it never enters this method when onItemClick :c
//startActivity(new Intent(this, establishments[position].activityClass));
// Intent intent = new Intent(this, SecondFragment.class);
//startActivity(intent);
// android.app.FragmentManager fragmentManager = getFragmentManager();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(item.getItemId()==android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
private void loadFragment(){
Fragment fragment = new SecondFragment();
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
}
private void changeActivity(){
startActivity(new Intent(this,SecondActivity.class));
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
@SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
Establishments c = adapter.getItem(arg2);
Toast.makeText(Activity_list.this, " " + c.geteName() , Toast.LENGTH_SHORT).show();
//you decide if you want to change activity
changeActivity();
//or load a fragment
loadFragment();
}
};
}
试一试:)