单击搜索时为什么列表视图不显示?

时间:2014-07-22 18:50:52

标签: java android xml android-activity

我正在尝试实现搜索活动,当从操作栏中单击搜索按钮时,会显示包含可能产品的列表。我正在尝试将我的搜索按钮与列表视图相关联,但一直未成功。

MainActivity.java

   private ListView lv;

// Listview Adapter
ArrayAdapter<String> adapter;

// Search EditText
EditText inputSearch;


// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;

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


    // Listview Data
    String products[] = {"A", "B", "C", "D",
            "fdsafds", "fdsavds",
            "fdsafdsafsd", "greadgfd", "F", "thrgefargra"};

    lv = (ListView) findViewById(R.id.list_view);
    inputSearch = (EditText) findViewById(R.id.inputSearch);

    // Adding items to listview
    // adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
    // lv.setAdapter(adapter);
    return true;
}

menu.xml文件

   <?xml version="1.0" encoding="utf-8"?>
  <menu xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:id="@+id/inputSearch"
    android:title="Search places"
    android:hint="Search places..."
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:icon="@drawable/ic_action_search"
    android:showAsAction="collapseActionView|ifRoom"
    android:actionViewClass="android.widget.SearchView" />


<ListView
    android:id="@+id/list_view"
    android:layout_width="fill_parent"
    android:layout_height="29dp"/>

list_item.xml

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<!-- Single ListItem -->
<ListView android:id="@+id/list_item"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:padding="10dip"
    android:textSize="16dip"
    android:textStyle="bold"/>

<!-- Product Name -->
<TextView android:id="@+id/product_name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10dip"
    android:textSize="16dip"
    android:textStyle="bold"/>    

 </LinearLayout>

2 个答案:

答案 0 :(得分:0)

你应该注册&#39; ListView#39;对于Menu

registerForContextMenu(listview);

答案 1 :(得分:0)

我做过你喜欢的事情。试着看看它是否能帮到你。

public class YourActivity extends Activity {

private ListView l;

public void onCreate(Bundle saveInstanceState) {
     setContentView(R.layout.your_layout);

     l = (ListView) findViewById(R.id.your_list_view_id);

     List<String> your_array_list = new ArrayList<String>();
     your_array_list.add("foo");
     your_array_list.add("bar");

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

     l.setAdapter(arrayAdapter); 
    }
}