Подтвердить что ты не робот

Удалите прописку вокруг значка действия слева на Android 4.0+

Я хочу удалить прокладку вокруг значка слева в стандартной панели действий android 4.0+. Я устанавливаю значок с помощью:

getActionBar().setIcon(getResources().getDrawable(R.drawable.ic_action_myapp));

И я бы хотел, чтобы значок заполнил вертикально пространство, касаясь обоих верхних и нижних, подобно тому, что делает приложение soundcloud:

inynO.png

4b9b3361

Ответ 1

Копаясь в источниках AOSP, кажется, что этот код связан с com.android.internal.widget.ActionBarView.java. В частности, соответствующей частью является метод onLayout() внутреннего класса ActionBarView$HomeView, частично описанный ниже (строки 1433-1478):

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        ...
        final LayoutParams iconLp = (LayoutParams) mIconView.getLayoutParams();
        final int iconHeight = mIconView.getMeasuredHeight();
        final int iconWidth = mIconView.getMeasuredWidth();
        final int hCenter = (r - l) / 2;
        final int iconTop = Math.max(iconLp.topMargin, vCenter - iconHeight / 2);
        final int iconBottom = iconTop + iconHeight;
        final int iconLeft;
        final int iconRight;
        int marginStart = iconLp.getMarginStart();
        final int delta = Math.max(marginStart, hCenter - iconWidth / 2);
        if (isLayoutRtl) {
            iconRight = width - upOffset - delta;
            iconLeft = iconRight - iconWidth;
        } else {
            iconLeft = upOffset + delta;
            iconRight = iconLeft + iconWidth;
        }
        mIconView.layout(iconLeft, iconTop, iconRight, iconBottom);
    }

тот же виджет использует этот макет, определенный в res/layout/action_bar_home.xml:

<view xmlns:android="http://schemas.android.com/apk/res/android"
  class="com.android.internal.widget.ActionBarView$HomeView"
  android:layout_width="wrap_content"
  android:layout_height="match_parent">
<ImageView android:id="@android:id/up"
           android:src="?android:attr/homeAsUpIndicator"
           android:layout_gravity="center_vertical|start"
           android:visibility="gone"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginEnd="-8dip" />
<ImageView android:id="@android:id/home"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginEnd="8dip"
           android:layout_marginTop="@android:dimen/action_bar_icon_vertical_padding"
           android:layout_marginBottom="@android:dimen/action_bar_icon_vertical_padding"
           android:layout_gravity="center"
           android:adjustViewBounds="true"
           android:scaleType="fitCenter" />
</view>

Согласно источникам, значок отображается в Imageview с id = android.R.id.home. Приведенный выше метод onLayout() учитывает поля Imageview, определенные в макете, которые нельзя установить с помощью переопределения темы/стиля, поскольку они используют значение @android:dimen/action_bar_icon_vertical_padding.

Все, что вы можете сделать, это избавиться от этих значений во время выполнения и установить их в соответствии с вашими потребностями: просто загрузите Imageview и установите его верхнее и нижнее поля на 0. Что-то вроде этого:

ImageView icon = (ImageView) findViewById(android.R.id.home);
FrameLayout.LayoutParams iconLp = (FrameLayout.LayoutParams) icon.getLayoutParams();
iconLp.topMargin = iconLp.bottomMargin = 0;
icon.setLayoutParams( iconLp );

РЕДАКТИРОВАТЬ: Я только что понял, что я не рассказывал, как избавиться от левой прокладки. Решение ниже.

Левое заполнение на панели действий зависит от "Навигация по вверх" , отображаемого значком панели действий. Когда это отключено (через ActionBar.setDisplayHomeAsUpEnabled(false)), индикатор слева/вверх исчез, но также используется левое дополнение. Простое решение:

  • активировать навигацию с помощью ActionBar.setDisplayHomeAsUpEnabled(true), чтобы рассмотреть представление индикатора в процессе компоновки
  • принудительно используйте drawable в качестве индикатора вверх в res/values-v14/styles.xml до null

например:

<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <!-- API 14 theme customizations can go here. -->
    <item name="android:homeAsUpIndicator">@null</item>
</style>

Ответ 2

Я нашел другое разрешение (ссылка appcompat-v7), которые изменяют toolbarStyle, следующий код:

<item name="toolbarStyle">@style/Widget.Toolbar</item>


<style name="Widget.Toolbar" parent="@style/Widget.AppCompat.Toolbar">
    <item name="contentInsetStart">0dp</item>
</style>

Ответ 3

использовать пользовательский макет для ActionBar

enter image description here

public class TestActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final ActionBar actionBar = getActionBar();
        actionBar.setCustomView(R.layout.actionbar_custom_view_home);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setDisplayUseLogoEnabled(false);
        actionBar.setDisplayShowHomeEnabled(false);

        setContentView(R.layout.main);

    }

    public void Click(View v) {
        if (v.getId() == R.id.imageIcon) {
            Log.e("click on-->  ", "Action icon");
        }
    }
}

actionbar_custom_view_home.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center" >

    <ImageView
        android:id="@+id/imageIcon"
        android:onClick="Click"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Large Icon With Title"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

Ответ 4

Усовершенствованный parrzhang ответ в удалите дополнение вокруг значка действия слева на Android 4.0+

 private void adjustHomeButtonLayout(){
        ImageView view = (ImageView)findViewById(android.R.id.home);
        if(view.getParent() instanceof ViewGroup){
            ViewGroup viewGroup = (ViewGroup)view.getParent();
            View upView = viewGroup.getChildAt(0);
            if(upView != null && upView.getLayoutParams() instanceof FrameLayout.LayoutParams){
                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) upView.getLayoutParams();
                layoutParams.width = 20;// **can give your own width**
                upView.setLayoutParams(layoutParams);
            }
        }
    }

Ответ 5

Чтобы установить высоту ActionBar, вы можете создать новую тему, подобную этой:

<?xml version="1.0" encoding="utf-8"?>
<resources>   
    <style name="Theme.BarSize" parent="Theme.Sherlock.Light.DarkActionBar">
        <item name="actionBarSize">48dip</item>
        <item name="android:actionBarSize">48dip</item> 
    </style> 
 </resources>

и установите эту тему в свою деятельность:

Android: тема = "@стиль/Theme.BarSize"

Теперь установите высоту значков на "match_parent".

Это позволит удалить верхнее и нижнее дополнение.

Теперь стрелка слева встроена в фреймворк, поэтому у вас есть два варианта обхода:

  • Используйте ActionBarSherlock. Он использует его собственные drwables и ресурсы, поэтому вы можете изменить значок стрелки на emty png, чтобы ваш значок вверх переместился в крайнее левое положение.

  • Значок "вверх/назад" возникает из:

public boolean onOptionsItemSelected(MenuItem item) 
               {
          switch (item.getItemId()) 
                {
                case android.R.id.home:
                            NavUtils.navigateUpFromSameTask(this);
              return true;
                }      
               }

Итак, вместо того, чтобы использовать эту опцию для кнопки "вверх", вы можете сделать другую опцию панели действий, которая имеет намерение для предыдущего действия, а затем поместить этот значок в панель действий.

Это будет более сложное решение.

Надеюсь, что поможет..:)

Ответ 6

вы можете найти homeview в actionbarview, например:

<view xmlns:android="http://schemas.android.com/apk/res/android"
  class="com.android.internal.widget.ActionBarView$HomeView"
  android:layout_width="wrap_content"
  android:layout_height="match_parent">
<ImageView android:id="@android:id/up"
           android:src="?android:attr/homeAsUpIndicator"
           android:layout_gravity="center_vertical|start"
           android:visibility="gone"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginEnd="-8dip" />
<ImageView android:id="@android:id/home"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginEnd="8dip"
           android:layout_marginTop="@android:dimen/action_bar_icon_vertical_padding"
           android:layout_marginBottom="@android:dimen/action_bar_icon_vertical_padding"
           android:layout_gravity="center"
           android:adjustViewBounds="true"
           android:scaleType="fitCenter" />

но вы не можете получить upView с помощью findViewById(android.R.id.up).

чтобы вы могли получить homeView и получить его родительское представление, установите ширину обзора 0

    ImageView view = (ImageView)findViewById(android.R.id.home);
    if(view.getParent() instanceof ViewGroup){
        ViewGroup viewGroup = (ViewGroup)view.getParent();
        View upView = viewGroup.getChildAt(0);
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) upView.getLayoutParams();
        layoutParams.width = 0;
        upView.setLayoutParams(layoutParams);
    }