1

我想在 AppCompatActivity 的操作栏中添加一个 autocompletetextview 组件。我的代码是:

样式.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread.setDefaultUncaughtExceptionHandler(new GlobalException());

        Toolbar tb = (Toolbar) findViewById(R.id.toolbar_search);
        setSupportActionBar(tb);
}

布局/action_bar_search.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar_search"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:layout_scrollFlags="scroll|enterAlways"
    app:layout_collapseMode="pin">

    <AutoCompleteTextView
        android:id="@+id/theSearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/search_the"
        android:imeOptions="actionSearch"
        android:inputType="textAutoComplete|textAutoCorrect"
        android:textColor="#FFFFFF" >

        <requestFocus />
    </AutoCompleteTextView>

</android.support.v7.widget.Toolbar>

当我的应用程序打开时,我看到一个空白的白屏,几秒钟后,它变成了一个永远保持这种状态的空白黑屏,直到我手动停止它。任何的想法?

显然,在Toolbar tb = (Toolbar) findViewById(R.id.toolbar_search);tb 为空之后

4

2 回答 2

2

您的ToolbarXML 未包含在您的文件中R.layout.activity_main,因此findById将无法正常工作。这会导致Toolbar保持为空并使您的应用程序崩溃。您可以包含带有<include>标签的布局资源。在你的情况下:<include layout="@layout/action_bar_search"/>

于 2016-03-05T23:05:12.027 回答
0

下面是 AutocompleteTextView 的示例代码:

AutoCompleteTextView text;
String[] languages={"Android ","java","IOS","SQL","JDBC","Web services"};

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  text=(AutoCompleteTextView)findViewById(R.id.theSearch);
  ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,languages);
  text.setAdapter(adapter);
  text.setThreshold(1);    
  }

我希望这会对你有所帮助......

于 2016-03-05T18:18:53.803 回答