Cómo mostrar la vista personalizada en ActionBar?


Quiero mostrar la búsqueda personalizada en actionbar (estoy usando ActionBarSherlock para eso).

Tengo que:

introduzca la descripción de la imagen aquí

Pero quiero hacer un diseño personalizado (campo edittext) para ocupar todo el ancho disponible.

He implementado el diseño personalizado como se sugiere aquí.

Ahí está mi diseño personalizado search.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="?attr/actionButtonStyle"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:layout_gravity="fill_horizontal"
    android:focusable="true" >

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|fill_horizontal" >

        <EditText
            android:id="@+id/search_query"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="left|center"
            android:background="@drawable/bg_search_edit_text"
            android:imeOptions="actionSearch"
            android:inputType="text" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right|center_vertical"
            android:src="@drawable/ic_search_arrow" />

    </FrameLayout>

</LinearLayout>

Y en MyActivity:

ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setIcon(R.drawable.ic_action_search);

LayoutInflater inflator = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.search, null);

actionBar.setCustomView(v);

¿Cómo puedo hacer un diseño personalizado para ocupar todo el ancho disponible de actionBar?

Ayuda, favor.

Author: Community, 2012-10-14

6 answers

Hay un truco para esto. Todo lo que tiene que hacer es usar RelativeLayout en lugar de LinearLayout como contenedor principal. Es importante tener android:layout_gravity="fill_horizontal" configurado para ello. Eso debería bastar.

 94
Author: Tomik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-14 16:41:05

Luché con esto yo mismo, y probé la respuesta de Tomik. Sin embargo, esto no hizo que el diseño tuviera el ancho disponible completo al inicio, solo cuando agrega algo a la vista.

Tendrá que establecer el LayoutParams.FILL_PARENT al agregar la vista:

//I'm using actionbarsherlock, but it's the same.
LayoutParams layout = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
getSupportActionBar().setCustomView(overlay, layout); 

De esta manera llena completamente el espacio disponible. (Puede que tenga que usar la solución de Tomik también).

 34
Author: Peterdk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-20 15:05:32

Las respuestas de Tomik y Peterdk funcionan cuando desea que su vista personalizada ocupe toda la barra de acciones, incluso ocultando el título nativo.

Pero si desea que su vista personalizada viva lado a lado con el título (y llene todo el espacio restante después de que se muestre el título), entonces puedo remitirle a la excelente respuesta del usuario Android-Developer aquí:

Https://stackoverflow.com/a/16517395/614880

Su código en el fondo funcionó perfectamente para mí.

 6
Author: Mike Repass,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:19

Así es como funcionó para mí (de arriba responde que estaba mostrando tanto el título predeterminado como mi vista personalizada también).

ActionBar.LayoutParams layout = new ActionBar.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
// actionBar.setCustomView(view); //last view item must set to android:layout_alignParentRight="true" if few views are there 
actionBar.setCustomView(view, layout); // layout param width=fill/match parent
actionBar.setDisplayShowCustomEnabled(true);//must other wise its not showing custom view.

Lo que noté es que tanto setCustomView(view) como setCustomView(view,params) la vista width=match/fill parent. setDisplayShowCustomEnabled (boolean showCustom)

 5
Author: Bharatesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-08 09:14:14

Por ejemplo, puede definir un archivo de diseño que contenga un elemento EditText.

<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/searchfield"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:inputType="textFilter" >

</EditText> 

Puedes hacer

public class MainActivity extends Activity {

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

    ActionBar actionBar = getActionBar();
    // add the custom view to the action bar
    actionBar.setCustomView(R.layout.actionbar_view);
    EditText search = (EditText) actionBar.getCustomView().findViewById(R.id.searchfield);
    search.setOnEditorActionListener(new OnEditorActionListener() {

      @Override
      public boolean onEditorAction(TextView v, int actionId,
          KeyEvent event) {
        Toast.makeText(MainActivity.this, "Search triggered",
            Toast.LENGTH_LONG).show();
        return false;
      }
    });
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
        | ActionBar.DISPLAY_SHOW_HOME);


    }
 3
Author: BoldHD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-03 07:47:31

Hay un ejemplo en la aplicación launcher de Android (que he hecho una biblioteca de ella, aquí), dentro de la clase que maneja fondos de pantalla-picking ("WallpaperPickerActivity") .

El ejemplo muestra que necesita establecer un tema personalizado para que esto funcione. Lamentablemente, esto funcionó para mí solo usando el marco normal, y no el de la biblioteca de soporte.

Aquí está el temas:

Styles.xml

 <style name="Theme.WallpaperPicker" parent="Theme.WallpaperCropper">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowShowWallpaper">true</item>
  </style>

  <style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
    <item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowActionBarOverlay">true</item>
  </style>

  <style name="WallpaperCropperActionBar" parent="@android:style/Widget.DeviceDefault.ActionBar">
    <item name="android:displayOptions">showCustom</item>
    <item name="android:background">#88000000</item>
  </style>

Valor-v19 / estilos.xml

 <style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
    <item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowActionBarOverlay">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
  </style>

  <style name="Theme" parent="@android:style/Theme.DeviceDefault.Wallpaper.NoTitleBar">
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
  </style>

EDITAR: hay una mejor manera de hacerlo, que funciona en la biblioteca de soporte también. Simplemente agregue esta línea de código en lugar de lo que he escrito anteriormente:

getSupportActionBar().setDisplayShowCustomEnabled(true);
 1
Author: android developer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-07 22:45:57