如何在 Android Studio 中创建自定义图像按钮?

Posted

技术标签:

【中文标题】如何在 Android Studio 中创建自定义图像按钮?【英文标题】:How to create custom image buttons in Android studio? 【发布时间】:2017-05-20 19:39:56 【问题描述】:

如何在 android studio 中创建像这样的图像按钮?它需要依赖吗?还是有其他方法?

【问题讨论】:

参考***.com/questions/18507351/… 这是带有自定义项目的回收站视图 好的,我会处理的。 【参考方案1】:

可以通过多种方式完成。它仅取决于您如何自定义布局。你可以这样做......

1- 带有白色背景的线性布局,内部有 1 个图像视图和 1 个文本视图...

2- 使用带有图像视图和文本视图的框架布局。

3- 图片中的视图是带有卡片视图的回收站视图。要使用回收器和卡片,您需要支持设计依赖项..

// RecyclerView
compile 'com.android.support:recyclerview-v7:23.3.+'

// CardView
compile 'com.android.support:cardview-v7:23.3.+'

有关更多信息,您可以点击此链接...本教程与您的图片相同

Android working with Card View and Recycler View

Android simple RecyclerView and CardView

ANDROID RECYCLERVIEW AND CARDVIEW IN MATERIAL DESIGN TUTORIAL

【讨论】:

@SovietSenpai 喜欢编码【参考方案2】:

你必须在cardview中使用recycle view。

要在您的应用中使用 CardView,请在 build.gradle 中添加 CardView 依赖项并同步项目。

    dependencies 
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
     // RecyclerView
    compile 'com.android.support:recyclerview-v7:23.3.+'
     // CardView
    compile 'com.android.support:cardview-v7:23.3.+'
     // Glide
    compile 'com.github.bumptech.glide:glide:3.7.0'

之后创建一个 xml 卡片视图

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_
    android:layout_>

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_
        android:layout_
        android:layout_gravity="center"
        android:layout_margin="@dimen/card_margin"
        android:elevation="3dp"
        card_view:cardCornerRadius="@dimen/card_album_radius">

        <RelativeLayout
            android:layout_
            android:layout_>

            <ImageView
                android:id="@+id/thumbnail"
                android:layout_
                android:layout_
                android:background="?attr/selectableItemBackgroundBorderless"
                android:clickable="true"
                android:scaleType="fitXY" />

            <TextView
                android:id="@+id/title"
                android:layout_
                android:layout_
                android:layout_below="@id/thumbnail"
                android:paddingLeft="@dimen/album_title_padding"
                android:paddingRight="@dimen/album_title_padding"
                android:paddingTop="@dimen/album_title_padding"
                android:textColor="@color/album_title"
                android:textSize="@dimen/album_title" />

            <TextView
                android:id="@+id/count"
                android:layout_
                android:layout_
                android:layout_below="@id/title"
                android:paddingBottom="@dimen/songs_count_padding_bottom"
                android:paddingLeft="@dimen/album_title_padding"
                android:paddingRight="@dimen/album_title_padding"
                android:textSize="@dimen/songs_count" />

            <ImageView
                android:id="@+id/overflow"
                android:layout_
                android:layout_
                android:layout_alignParentRight="true"
                android:layout_below="@id/thumbnail"
                android:layout_marginTop="@dimen/ic_album_overflow_margin_top"
                android:scaleType="centerCrop"
                android:src="@drawable/ic_dots" />

        </RelativeLayout>

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

</LinearLayout>

然后您可以为此创建适配器

    public class AlbumsAdapter extends RecyclerView.Adapter<AlbumsAdapter.MyViewHolder> 

    private Context mContext;
    private List<Album> albumList;

    public class MyViewHolder extends RecyclerView.ViewHolder 
        public TextView title, count;
        public ImageView thumbnail, overflow;

        public MyViewHolder(View view) 
            super(view);
            title = (TextView) view.findViewById(R.id.title);
            count = (TextView) view.findViewById(R.id.count);
            thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
            overflow = (ImageView) view.findViewById(R.id.overflow);
        
    


    public AlbumsAdapter(Context mContext, List<Album> albumList) 
        this.mContext = mContext;
        this.albumList = albumList;
    

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) 
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.album_card, parent, false);

        return new MyViewHolder(itemView);
    

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) 
        Album album = albumList.get(position);
        holder.title.setText(album.getName());
        holder.count.setText(album.getNumOfSongs() + " songs");

        // loading album cover using Glide library
        Glide.with(mContext).load(album.getThumbnail()).into(holder.thumbnail);

        holder.overflow.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                showPopupMenu(holder.overflow);
            
        );
    

    /**
     * Showing popup menu when tapping on 3 dots
     */
    private void showPopupMenu(View view) 
        // inflate menu
        PopupMenu popup = new PopupMenu(mContext, view);
        MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.menu_album, popup.getMenu());
        popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
        popup.show();
    

    /**
     * Click listener for popup menu items
     */
    class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener 

        public MyMenuItemClickListener() 
        

        @Override
        public boolean onMenuItemClick(MenuItem menuItem) 
            switch (menuItem.getItemId()) 
                case R.id.action_add_favourite:
                    Toast.makeText(mContext, "Add to favourite", Toast.LENGTH_SHORT).show();
                    return true;
                case R.id.action_play_next:
                    Toast.makeText(mContext, "Play next", Toast.LENGTH_SHORT).show();
                    return true;
                default:
            
            return false;
        
    

    @Override
    public int getItemCount() 
        return albumList.size();
    

这是活动 main.xml

    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_
    android:layout_
    android:background="@android:color/white"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_
        android:layout_
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_
            android:layout_
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleTextAppearance="@android:color/transparent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <RelativeLayout
                android:layout_
                android:layout_>

                <ImageView
                    android:id="@+id/backdrop"
                    android:layout_
                    android:layout_
                    android:fitsSystemWindows="true"
                    android:scaleType="centerCrop"
                    app:layout_collapseMode="parallax" />

                <LinearLayout
                    android:layout_
                    android:layout_
                    android:layout_centerInParent="true"
                    android:gravity="center_horizontal"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/love_music"
                        android:layout_
                        android:layout_
                        android:text="@string/backdrop_title"
                        android:textColor="@android:color/white"
                        android:textSize="@dimen/backdrop_title" />

                    <TextView
                        android:layout_
                        android:layout_
                        android:text="@string/backdrop_subtitle"
                        android:textColor="@android:color/white"
                        android:textSize="@dimen/backdrop_subtitle" />

                </LinearLayout>
            </RelativeLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_
                android:layout_
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

这是 content_main.xml

   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    android:background="@color/viewBg"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="info.androidhive.cardview.MainActivity"
    tools:showIn="@layout/activity_main">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_
        android:layout_
        android:clipToPadding="false"
        android:scrollbars="vertical" />

</RelativeLayout>

最后写MainActivity

    public class MainActivity extends AppCompatActivity 

    private RecyclerView recyclerView;
    private AlbumsAdapter adapter;
    private List<Album> albumList;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initCollapsingToolbar();

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        albumList = new ArrayList<>();
        adapter = new AlbumsAdapter(this, albumList);

        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        prepareAlbums();

        try 
            Glide.with(this).load(R.drawable.cover).into((ImageView) findViewById(R.id.backdrop));
         catch (Exception e) 
            e.printStackTrace();
        
    

    /**
     * Initializing collapsing toolbar
     * Will show and hide the toolbar title on scroll
     */
    private void initCollapsingToolbar() 
        final CollapsingToolbarLayout collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        collapsingToolbar.setTitle(" ");
        AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
        appBarLayout.setExpanded(true);

        // hiding & showing the title when toolbar expanded & collapsed
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() 
            boolean isShow = false;
            int scrollRange = -1;

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) 
                if (scrollRange == -1) 
                    scrollRange = appBarLayout.getTotalScrollRange();
                
                if (scrollRange + verticalOffset == 0) 
                    collapsingToolbar.setTitle(getString(R.string.app_name));
                    isShow = true;
                 else if (isShow) 
                    collapsingToolbar.setTitle(" ");
                    isShow = false;
                
            
        );
    

    /**
     * Adding few albums for testing
     */
    private void prepareAlbums() 
        int[] covers = new int[]
                R.drawable.album1,
                R.drawable.album2,
                R.drawable.album3,
                R.drawable.album4,
                R.drawable.album5,
                R.drawable.album6,
                R.drawable.album7,
                R.drawable.album8,
                R.drawable.album9,
                R.drawable.album10,
                R.drawable.album11;

        Album a = new Album("True Romance", 13, covers[0]);
        albumList.add(a);

        a = new Album("Xscpae", 8, covers[1]);
        albumList.add(a);

        a = new Album("Maroon 5", 11, covers[2]);
        albumList.add(a);

        a = new Album("Born to Die", 12, covers[3]);
        albumList.add(a);

        a = new Album("Honeymoon", 14, covers[4]);
        albumList.add(a);

        a = new Album("I Need a Doctor", 1, covers[5]);
        albumList.add(a);

        a = new Album("Loud", 11, covers[6]);
        albumList.add(a);

        a = new Album("Legend", 14, covers[7]);
        albumList.add(a);

        a = new Album("Hello", 11, covers[8]);
        albumList.add(a);

        a = new Album("Greatest Hits", 17, covers[9]);
        albumList.add(a);

        adapter.notifyDataSetChanged();
    

    /**
     * RecyclerView item decoration - give equal margin around grid item
     */
    public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration 

        private int spanCount;
        private int spacing;
        private boolean includeEdge;

        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) 
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) 
            int position = parent.getChildAdapterPosition(view); // item position
            int column = position % spanCount; // item column

            if (includeEdge) 
                outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
                outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

                if (position < spanCount)  // top edge
                    outRect.top = spacing;
                
                outRect.bottom = spacing; // item bottom
             else 
                outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
                outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
                if (position >= spanCount) 
                    outRect.top = spacing; // item top
                
            
        
    

    /**
     * Converting dp to pixel
     */
    private int dpToPx(int dp) 
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    

你也可以参考这个link。

【讨论】:

以上是关于如何在 Android Studio 中创建自定义图像按钮?的主要内容,如果未能解决你的问题,请参考以下文章

在 Visual Studio Code 中创建自定义语言

如何在android中创建自定义导航抽屉

在 Android 中创建自定义视图

有没有办法在 android 中创建自定义应答机?

在 Android 中创建自定义标题栏

是否可以在使用内置字典的android中创建自定义键盘[关闭]