15

Я хочу показать кнопку со стрелкой назад в мое приложение, но приложение падает, когда я положил это в моем коде:Android Стрелка назад на панели инструментов (AppCompatActivity)

getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
getSupportActionBar().setDisplayShowHomeEnabled(true); 

style.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> 
    <item name="colorPrimary">@color/PrimaryColor</item> 
    <item name="colorPrimaryDark">@color/PrimaryColorDark</item> 
    <item name="colorAccent">@color/PrimaryColor</item> 
    <item name="colorControlHighlight">@color/ControlHighlight</item> 
    <item name="android:statusBarColor" tools:targetApi="21">@android:color/transparent</item> 
</style> 


<style name="ActionBarPopupThemeOverlay" parent="ThemeOverlay.AppCompat.Light" > 
    <item name="android:textColor">#000000</item> 
</style> 


<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout"> 
    <item name="tabIndicatorColor">#FFFFFF</item> 
    <item name="tabIndicatorHeight">3dp</item> 
    <item name="tabTextAppearance">@style/MyCustomTabTextAppearance</item> 
</style> 


<style name="MyCustomTabTextAppearance" parent="TextAppearance.Design.Tab"> 
    <item name="android:textColor">#FFFFFF</item> 
</style> 

toolbar.xml

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
android:layout_height="@dimen/abc_action_bar_default_height_material" 
android:elevation="0dp" 
android:layout_width="match_parent" 
android:id="@+id/toolbar" 
android:background="@color/PrimaryColor" 
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" 
app:popupTheme="@style/ActionBarPopupThemeOverlay"/> 

Класс (не фрагментировать):

public class WebViewCanale extends AppCompatActivity { 

    Toolbar toolbar; 
    TextView textView; 
    WebView webView; 
    ProgressBar progressBar; 

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

     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
     getSupportActionBar().setDisplayShowHomeEnabled(true); 

     //Toolbar 
     toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 


     //FindViewById 
     webView = (WebView) findViewById(R.id.webview); 
     textView = (TextView) findViewById(R.id.textView); 
     progressBar = (ProgressBar) findViewById(R.id.progressBar); 

     //Impostazioni WebView 
     WebSettings webSettings = webView.getSettings(); 
     webSettings.setJavaScriptEnabled(true); 
     webSettings.setLoadsImagesAutomatically(true); 
     webView.loadUrl(this.getIntent().getDataString()); 
     webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); 
     webView.getSettings().setAppCacheEnabled(false); 

     //Titolo Toolbar 
     webView.setWebChromeClient(new WebChromeClient() { 
      @Override 
      public void onReceivedTitle(WebView view, String title) { 
       super.onReceivedTitle(view, title); 
       if (!TextUtils.isEmpty(title)) { 
        WebViewCanale.this.setTitle(title); 
       } 
      } 
     }); 
    } 
} 
+0

место этот код 'панель инструментов = (панель инструментов) findViewById (R.id.toolbar); setSupportActionBar (панель инструментов); 'перед этим кодом' setSupportActionBar (панель инструментов); getSupportActionBar() setDisplayHomeAsUpEnabled (истина). getSupportActionBar(). SetDisplayShowHomeEnabled (true); ' –

+0

не работает ... тот же сбой –

+0

@SimoneVarletta 'some crash' не является полезным описанием. – FWeigl

ответ

3

добавить эту тему:

<style name="AppTheme2" parent="Theme.AppCompat.Light"> 
    <item name="windowActionBar">false</item> 
    <item name="windowNoTitle">true</item> 
    <item name="colorPrimary">@color/appColor</item> 
    <item name="colorControlNormal">@color/whiteColor</item> 
    <item name="colorControlActivated">@color/appColor</item> 
</style> 

и в вас активность:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
2

Вы должны установить поддержку ActionBar первых, прежде чем ваш может получить Это. поэтому поместите следующий код

toolbar = (Toolbar) findViewById(R.id.toolbar); 
setSupportActionBar(toolbar); 

До настоящего Кодекса

getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
getSupportActionBar().setDisplayShowHomeEnabled(true); 
+0

@Simone Varletta Var Я рад, что это сработало для вас. –

25

Интересно, почему это не полный ответ на это на SO, но в конце концов я решил этот вопрос сам по себе:

Используйте следующий фрагмент, чтобы иметь Назад кнопка на панели инструментов в AppCompatActivity:

 toolbar = (Toolbar) findViewById(R.id.hack_toolbar); 
     setSupportActionBar(toolbar); 

     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
     getSupportActionBar().setDisplayShowHomeEnabled(true); 

     toolbar.setNavigationOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       //do something you want 
      } 
     }); 
+1

Полный ответ [здесь] (http://stackoverflow.com/a/26656285/1911652), но у вас есть точный код для 'Toolbar' – Atul

14

Вы также можете просто объявить в ManifestParentActivity с: <activity android:name=".ThisActivity" android:parentActivityName=".TheActivityThatCalledThisOne"> </activity>

+0

правильное решение. – Joyal

3
@BindView(R.id.toolbar) 
Toolbar toolbar; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_user_events); 
    ButterKnife.bind(this); 

    setSupportActionBar(toolbar); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
} 

@Override 
public boolean onSupportNavigateUp() { 
    onBackPressed(); 
    return true; 
} 

onSupportNavigateUp() Этот метод вызывается всякий раз, когда пользователь выбирает для перемещения вверх в иерархии деятельности вашего приложения из Панель действий.

onBackPressed(); Позаботьтесь о том, чтобы соскоблить стопку фрагмента или закончить деятельность, если это необходимо.