getFilter()和自定义列表视图 - Android

时间:2014-01-27 10:09:00

标签: android android-listview android-adapter android-search

我有两个问题。他们是相关的,因此我在一起问他们。

Q1:自定义BaseAdapter类中的 getFilter()方法无法正常工作
我在我的应用中使用自定义BaseAdapter class来在自定义listview中实现搜索功能。搜索栏中有一个edittext,它会过滤listview。但getFilter() method无效,因为当我在edittext中输入文字时,列表视图不会被过滤。代码如下。

Q2:自定义列表视图无法正常工作
我使用自定义listview布局将两个textviews放入一个列表项中。但结果并不像预期的那样。 This就是我所做的,This就是我想要做的。


Q1代码:
MainActivity.java

//this is the MainActivity where I have my navigation drawer.

public class MainActivity extends Activity {
final String[] elename ={"Hydrogen","Helium","Lithium","Beryllium","Boron","Carbon","Nitrogen","Oxygen","Flourine","Noen","Sodium","Magnesium","Aluminium","Silicon","Phosphorous","Sulphur","Chlorine","Argon","Potassium","Calcium","Scandium","Titanium","Vanadium","Chromium","Manganese","Iron","Cobalt","Nickel","Copper","Zinc","Gallium","Germanium","Arsenic","Selenium","Bromine","Krypton","Rubidium","Strontium","Yttrium","Zirconium","Niobium","Molybdenum","Technetium","Ruthenium","Rhodium","Palladium","Silver","Cadmium","Indium","Tin","Antimony","Tellurium","Iodine","Xenon","Caesium","Barium","Lanthanum","Cerium","Praseodymium","Neodymium","Promethium","Samarium","Europium","gadoliium","Terbium","Dysprosium","Holmium","Erbium","Thulium","Ytterbium","Lutetium","Hafnium","Tantalum","Tungsten","Rhenium","Osmium","Iridium","Platinum","Gold","Mercury","Thallium","Lead","Bismuth","Polonium","Astatine","Radon","Francium","Radium","Actinium","Thorium","Protactinium","Uranium","Neptunium","Plutonium","Americium","Curium","Berkelium","Californium","Einstenium","Fermium","Mendelevium","Nobelium","Lawrencium","Rutherfordium","Dubnium","Seaborgium","Bohrium","Hassium","Meitnerium","Darmstadtium","Roentgenium","Copernicium","Ununtrium","Ununquadium","Ununpentium","Ununhexium","Ununseptium","Ununoctium"};
final String[] nos = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59","60","61","62","63","64","65","66","67","68","69","70","71","72","73","74","75","76","77","78","79","80","81","82","83","84","85","86","87","88","89","90","91","92","93","94","95","96","97","98","99","100","101","102","103","104","105","106","107","108","109","110","111","112","113","114","115","116","117","118"};
ListViewAdapter adapter;

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

    adapter = new ListViewAdapter(this, elename, nos);
    final EditText searchBar = (EditText) findViewById(R.id.searchbar);
    final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
    final ListView navList = (ListView) findViewById(R.id.left_drawer);
    final LinearLayout linearLayout = (LinearLayout)findViewById(R.id.left_drawer_layout);
    navList.setAdapter(adapter);


    navList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
            //Change view according to numbers

            drawer.closeDrawer(linearLayout);
        }
    });

    //filter list view after search instantly
    searchBar.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            // When user changed the Text
            MainActivity.this.adapter.getFilter().filter(cs);
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {

        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

    //hide the keyboard after search on touch list view
    navList.setOnScrollListener(new AbsListView.OnScrollListener() {
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            //hide keyboard
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(navList.getWindowToken(), 0);
        }

        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }
    });
    navList.setEmptyView(findViewById(R.id.empty));
  }
}

ListViewAdapter.java

//This is the cutom BaseAdapter that has the getFilter() method
public class ListViewAdapter extends BaseAdapter  implements Filterable
{
Activity context;
String title[];
String description[];

public ListViewAdapter(Activity context, String[] title, String[] description) {
    super();
    this.context = context;
    this.title = title;
    this.description = description;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return title.length;
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

private class ViewHolder {
    TextView txtViewTitle;
    TextView txtViewDescription;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    // TODO Auto-generated method stub
    ViewHolder holder;
    LayoutInflater inflater =  context.getLayoutInflater();

    if (convertView == null)
    {
        convertView = inflater.inflate(R.layout.listitem_row, null);
        holder = new ViewHolder();
        holder.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
        holder.txtViewDescription = (TextView) convertView.findViewById(R.id.textView2);
        convertView.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.txtViewTitle.setText(title[position]);
    holder.txtViewDescription.setText(description[position]);

return convertView;
}
@Override
public Filter getFilter() {//method not working!

    Filter filter = new Filter() {

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {

            List<String> arrayListNames;
            arrayListNames = (List<String>) results.values;
            notifyDataSetChanged();
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            Filter.FilterResults results = new FilterResults();
            ArrayList<String> FilteredArrayNames = new ArrayList<String>();
            List<String> mDatabaseOfNames = null;
            // perform your search here using the searchConstraint String.

            constraint = constraint.toString().toLowerCase();
            for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                String dataNames = mDatabaseOfNames.get(i);
                if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                    FilteredArrayNames.add(dataNames);
                }
            }

            results.count = FilteredArrayNames.size();
            results.values = FilteredArrayNames;
            Log.e("VALUES", results.values.toString());
            return results;
        }
    };
    return filter;
  }
}


Q2代码:
main_activity.xml

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:background="#000000"
    android:layout_height="match_parent" >
</FrameLayout>

<LinearLayout
    android:id="@+id/left_drawer_layout"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:layout_marginLeft="-65dp"
    android:background="#111"
    android:orientation="vertical"
    android:layout_gravity="start" >

    <EditText
        android:id="@+id/searchbar"
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:textColor="#bfc2d1"
        android:singleLine="true"
        android:drawableLeft="@drawable/search"
        android:padding="10dp"
        android:background="@drawable/search_bar"
        android:layout_marginLeft="3dp"
        android:layout_marginRight="3dp"
        android:imeOptions="flagNoExtractUi"
        android:hint="Search" >
    </EditText>

<RelativeLayout
    android:id="@+id/empty"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:layout_marginLeft="-65dp"
    android:background="#111"
    android:orientation="vertical"
    android:layout_gravity="start" >
    <TextView
        android:id="@+id/empty_text"
        android:text="@string/notfound"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:textColor="#ffababab"
        android:textSize="15dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:gravity="center">
    </TextView>
    </RelativeLayout>

    <ListView android:id="@+id/left_drawer"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#111"/>
</LinearLayout>

</android.support.v4.widget.DrawerLayout>

listitem_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="60dp"
  android:weightSum="1.0">

<TextView
    android:id="@+id/textView1"
    android:text="TextView"
    android:layout_weight="0.8"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:textAppearance="?android:attr/textAppearanceLarge">
</TextView>

<TextView
    android:text="TextView"
    android:id="@+id/textView2"
    android:layout_weight="0.2" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
</TextView>

</LinearLayout>

请帮帮我!提前谢谢。

2 个答案:

答案 0 :(得分:0)

对于第一个问题,我不知道为什么它不会抛出NULL指针,请检查

      @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            Filter.FilterResults results = new FilterResults();
            ArrayList<String> FilteredArrayNames = new ArrayList<String>();
            List<String> mDatabaseOfNames = new ArrayList<String>();

for(int i = 0; i < title.size; i++){
     mDatabaseOfNames.add(title.get(i));
}
            // perform your search here using the searchConstraint String.

            constraint = constraint.toString().toLowerCase();
//OVER HERE IT SHOULD BE NULL POINTER for mDatabaseOfNames
            for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                String dataNames = mDatabaseOfNames.get(i);
                if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                    FilteredArrayNames.add(dataNames);
                }
            }

            results.count = FilteredArrayNames.size();
            results.values = FilteredArrayNames;
            Log.e("VALUES", results.values.toString());
            return results;
        }

对于Q2,我认为这应该有效

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="60dp"
    android:orientation="horizontal"
    android:padding="20dp"
    android:gravity="center_vertical"
    android:weightSum="1.0" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.2"
        android:text="TextView"
        android:textAppearance="?android:attr/textAppearanceLarge" >
    </TextView>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.8"
        android:text="TextView" >
    </TextView>

</LinearLayout>

答案 1 :(得分:0)

for Q1)列出mDatabaseOfNames = null;那你怎么能在你的for循环中使用它

  // MainActivity

 public static ArrayList al = new ArrayList()
  for(i=0 ;i< elename.length ;i++)
    { 
       al.add(elename[i] +" "+nos[i])
      }     

    // Adapter class
   List<String> mDatabaseOfNames = MainActivity.al;