android.support.v7.widget.Toolbar中带有后退按钮的图标

时间:2016-06-07 12:15:20

标签: android android-toolbar android-menu

我有一个带后退按钮的工具栏。我试图通过膨胀toolbar_menu.xml在工具栏中放置一个附件按钮,但它没有显示。我在下面附上了我的代码。

具有工具栏的活动:

activity_set_database.xml

        <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:card_view="http://schemas.android.com/tools"
        android:background="#383838"
        android:fitsSystemWindows="true"
        android:layout_height="match_parent">


        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:id="@+id/appBarLayout"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="#383838"
                app:popupTheme="@style/AppTheme.PopupOverlay" >

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.AppBarLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/message"
            android:layout_marginBottom="4dp"
            android:orientation="vertical"
            android:weightSum="1"
            android:layout_below="@+id/appBarLayout">

            <android.support.v7.widget.RecyclerView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/recyclerView"
                android:background="#ffffff"
                android:layout_above="@+id/buttonSendMessage"
                android:layout_weight="0.84" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_alignParentBottom="true"
            android:layout_marginLeft="6dp"
            android:layout_marginBottom="4dp"
            android:layout_weight="2">
        <android.support.v7.widget.CardView
            android:id="@+id/card_view"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_marginBottom="4dp"
            android:layout_weight="0.5"
            card_view:cardCornerRadius="2dp">

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="horizontal"
                android:weightSum="1">

                <EditText
                    android:id="@+id/editTextMessage"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="0.96" />

                <ImageView
                    android:id="@+id/cameraAttachmentButton"
                    android:layout_width="40dp"
                    android:layout_height="wrap_content"
                    android:background="@mipmap/compact"
                    android:layout_marginLeft="10dp"
                    android:clickable="true"
                    android:layout_centerVertical="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignParentEnd="true" />
            </LinearLayout>
        </android.support.v7.widget.CardView>

            <ImageView
                android:id="@+id/buttonSendMessage"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:textStyle="bold"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_gravity="center_vertical"
                android:textColor="#ffffff"
                android:background="@mipmap/send_button"
                android:text="Send" />

    </LinearLayout>


    </RelativeLayout>

SetDataBase.java

        package com.houssup.houssupchat;
    import android.app.Activity;
    import android.content.Intent;
    import android.provider.Settings;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.Toolbar;
    import android.util.Log;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.Toast;

    import com.firebase.client.ChildEventListener;
    import com.firebase.client.DataSnapshot;
    import com.firebase.client.Firebase;
    import com.firebase.client.FirebaseError;

    import com.firebase.client.Firebase;
    import com.firebase.client.ValueEventListener;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;

    public class SetDatabase extends AppCompatActivity {
        private static final String TAG = MainActivity.class.getName();
        private ImageView imageView;
        private EditText metText;
        private ImageView mbtSent;
        private Firebase mFirebaseRef;
        private List<Chat> mChats;
        private RecyclerView mRecyclerView;
        private ChatAdapter mAdapter;
        private String mId;

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

            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            toolbar.inflateMenu(R.menu.toolbar_menu);
            setSupportActionBar(toolbar);

            toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {

                    switch (menuItem.getItemId()){


                    }

                    return false;
                }
            });
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);

            metText = (EditText) findViewById(R.id.editTextMessage);
            mbtSent = (ImageView) findViewById(R.id.buttonSendMessage);
            mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
            mChats = new ArrayList<>();

            mId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
            mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            //mRecyclerView.setItemAnimator(new SlideInOutLeftItemAnimator(mRecyclerView));
            mAdapter = new ChatAdapter(mChats, mId);
            mRecyclerView.setAdapter(mAdapter);


            /**
             * Firebase - Inicialize
             */
            Firebase.setAndroidContext(this);
            mFirebaseRef = new Firebase("https://testchat-264db.firebaseio.com/").child("chat");


            mbtSent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String message = metText.getText().toString();

                    if (!message.isEmpty()) {
                        /**
                         * Firebase - Send message
                         */
                       mFirebaseRef.push().setValue(new Chat(message, mId,"sender","time","hasAttachment","attachmentLink"));
                    }

                    metText.setText("");
                }
            });


            /**
             * Firebase - Receives message
             */
            mFirebaseRef.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    if (dataSnapshot != null && dataSnapshot.getValue() != null) {
                        try{

                            Chat model = dataSnapshot.getValue(Chat.class);

                            mChats.add(model);
                            mRecyclerView.scrollToPosition(mChats.size() - 1);
                            mAdapter.notifyItemInserted(mChats.size() - 1);
                        } catch (Exception ex) {
                            Log.e(TAG, ex.getMessage());
                        }
                    }
                }

                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(FirebaseError firebaseError) {

                }
            });
        }
    }

toolbar_menu.xml

        <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        tools:context="example.gmariotti.it.test21.ToolbarActivity" >



        <item android:id="@+id/gallery"
            android:icon="@drawable/attach"
            android:title=""
            android:showAsAction="ifRoom" />
    </menu>

2 个答案:

答案 0 :(得分:0)

使用支持操作栏时更正菜单的方法

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

并覆盖

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.toolbar_menu, menu);
    return true;
}

答案 1 :(得分:0)

据我所知,您想在工具栏中设置一些可点击图标。所以,让我们开始吧:

1)尝试在 activity_set_database.xml CoordinatorLayout中使用而不是RelativeLayout(您可以在RelativeLayout中使用CoordinatorLayout),并且避免,在需要的地方,无效的params(我的意思是android:layout_above中的LinearLayout。例如,Android Studio会显示那些无效的参数。

2)导入 res - &gt;带有图标包Drawbale导入程序的拉动框文件夹(在Android Studio中)您认为是表示您的应用用户的附件的图标。

3)制作自定义菜单(让它保留 toolbar_menu.xml ),类似:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/gallery"
        android:title="@null"
     <!-- in this xml file set null, but in AndroidManifest.xml for proper
        activity you can set android:label="@string/proper_title"-->
        android:orderInCategory="100"
        app:showAsAction="ifRoom"
        android:icon="@drawable/ic_your_proper_icon"
     <!-- or leave your android:icon="@drawable/attach" if you wish and
       already have your own icon -->            
    />

</menu>

4)在你的 SetDataBase.java 而不是(我的意思是删除它):

toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {

                    switch (menuItem.getItemId()){


                    }

                    return false;
                }
            });

onCreate()之后输入:

@Override
public boolean onCreateOptionsMenu(Menu menu) {      
        getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        //as @user3024215 suggested
        return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
         int id = item.getItemId();

        if (id == android.R.id.home) {
            //here you can simply set onBackPressed();
            return true;
        }

        if (id == R.id.gallery) { // it's item id in your toolbar_menu.xml
        //here your code that activates proper actions for user 

        }
        return super.onOptionsItemSelected(item);
}

我认为,从某种程度上说,它对你有所帮助。