2016-05-15 84 views
0

我想在Android的活动标题栏的右侧添加一个ImageButton,但是当我执行应用程序时,它会给出错误Unfortunately app stopped。请帮助:如何在标题栏中添加ImageButton

custom_title.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.example.abc.myapplication.MainActivity"> 

    <ImageButton 
     android:id="@+id/button" 
     android:layout_width="50dp" 
     android:layout_height="50dp" 
     android:layout_alignParentRight="true" 
     android:focusable="true" 
     android:focusableInTouchMode="false" 
     android:src="@android:drawable/star_big_on" 
     android:background="@null" /> 

</RelativeLayout> 

MainActivity.java

package com.example.abc.myapplication; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.Window; 

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     this.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title); 
    } 
} 
+0

你在日志中看到什么? –

+0

使用LogCat检查与您的崩溃相关的Java堆栈跟踪:https://stackoverflow.com/questions/23353173/uncomfort-myapp-has-stopped-how-can-i-solve-this – CommonsWare

+0

该按钮不显示在标题栏。没有错误 –

回答

0

更换机器人:layout_height中的RelativeLayout:

android:layout_height="wrap_content" 
+0

按钮不显示 –

+0

嗯......只是一个疯狂的猜测......如果你添加到你的theme.xml如下: true IPat

0

按照以下来自Android开发者网站的指南,你将成为主人! Adding the App Bar

+0

我随之而来。但问题是为什么这段代码不工作? –

+0

不,你没有,你已经尝试执行巫术重新发明轮子先生: 'this.getWindow()setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title);' 使用,而不是: '工具栏myToolbar =(工具栏)findViewById(R.id.my_toolbar); setSupportActionBar(myToolbar);' – apelsoczi