【问题标题】:Image in Action bar without AppCompatActivity and with android:Theme.Holo.Light theme没有 AppCompatActivity 和 android:Theme.Holo.Light 主题的操作栏中的图像
【发布时间】:2015-09-02 13:44:35
【问题描述】:

我想在操作栏的右上角放置一个图像(ImageView)。我不想使用 AppCompatActivity 库,所以我的 MainActivity 扩展了 Activity 而不是 AppCompatActivity。 我使用主题:<style name="AppTheme" parent="android:Theme.Holo.Light">

我尝试使用此代码,但它不起作用,因为我没有扩展 AppCompatActivity:

 actionBar = getSupportActionBar();
        actionBar.setDisplayShowCustomEnabled(true);

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

        v1 = inflator.inflate(R.layout.custom_imageview1, null);

        actionBar.setCustomView(v);

编辑:我在运行 Android 4.4.2 的设备上运行此代码

【问题讨论】:

    标签: android android-actionbar


    【解决方案1】:

    由于您使用的是简单的Activity,因此您必须更改此行

    actionBar = getSupportActionBar();
    

    与 (check the doc)

    actionBar = getActionBar();
    

    【讨论】:

    • 现在可以了,但我必须导入 import android.app.ActionBar;
    • @user101 标记答案,如果它解决了问题。它可以帮助其他用户。
    【解决方案2】:

    您可以为此使用工具栏。它是您的最佳选择。Toolbar 是 Android Lollipop 中引入的 ActionBar 的新标准替代品。它支持您希望的全部自定义,并且对 ActionBar 逻辑没有或更少的修改。

    或者你可以使用代码:`

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        ActionBar mActionBar = getActionBar();
        mActionBar.setDisplayShowHomeEnabled(false);
        mActionBar.setDisplayShowTitleEnabled(false);
        LayoutInflater mInflater = LayoutInflater.from(this);
    
        View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);
        TextView mTitleTextView = (TextView) mCustomView.findViewById(R.id.title_text);
        mTitleTextView.setText("Title");
    
        ImageButton imageButton = (ImageButton) mCustomView
                .findViewById(R.id.imageButton);
        imageButton.setOnClickListener(new OnClickListener() {
    
            //if you want..You can set action
            }
        });`
    

    【讨论】:

    • 我在 4.4.2 Android 上开发这个
    • @SanketPrahbu: actionBar = getSupportActionBar(); -> 无法解决方法错误。
    • 我无法使用工具栏,因为我在 Android 4.4.2 上开发,而不是在 Android 5.0 上开发。
    猜你喜欢
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多