如何在 GridView 中动态创建 ImageButtons

How to dynamically create ImageButtons inside of GridView

我正在尝试在 GridView 中动态创建 ImageButtons,但由于某种原因,它们显示为字符串(如下所示)。我看过几个帖子,但仍然不确定问题所在。除了 xml 文件之外,我还附上了我的代码。

完整 activity:

package com.example.myname.myproject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import static com.example.myname.myproject.R.id.templateGrid;

//import com.example.myname.myproject.R;

public class AdminControlTabbed extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;
    List<String> options = new ArrayList<String>();
    String message;
    Spinner s;
    static String [] templateIcons = {"followfacebook", "followtwitter"};
    static int [] templateResources = {R.drawable.facebookblock, R.drawable.twitterblock};
    String [] defaultIcons = {"sendtext", "sendlink", "sendphone"};
    int [] defaultResources = {R.drawable.textblock, R.drawable.linkblock, R.drawable.callblock};
    static List <ImageButton> templateIButtons = new ArrayList<ImageButton>();
    List <ImageButton> defaultIButtons = new ArrayList<ImageButton>();

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("My Project");
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);


        List<String> channels = new ArrayList<String>();
        channels.add("Channel 1");
        channels.add("Channel 2");
        channels.add("Channel 3");
        s = (Spinner) findViewById(R.id.channelselector);
        ArrayAdapter a = new ArrayAdapter(this, android.R.layout.simple_spinner_item, channels);
        s.setAdapter(a);
        /*ImageButton linkButton = (ImageButton) findViewById(R.id.sendLink);
        linkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMessageInput(2);
            }
        });
        ImageButton textButton = (ImageButton) findViewById(R.id.sendText);
        textButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMessageInput(1);
            }
        });
        ImageButton callButton = (ImageButton) findViewById(R.id.sendCall);
        callButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMessageInput(0);
            }
        });*/
    }


    public void sendMessage(int position, String message){
        StringTokenizer t = new StringTokenizer(s.getSelectedItem().toString());
        t.nextToken();
        String channel = (t.nextToken());
        if (position == 0){
            try{new FirebaseSendMessage().execute(channel, "Phone | " + message + "&" + channel);}
            catch (Exception e) {
                Log.d("Exception", e.toString());
            }
        }
        if (position == 1){
            try{new FirebaseSendMessage().execute(channel, "Banner | " + message + "&" + channel);}
            catch (Exception e) {
                Log.d("Exception", e.toString());
            }
        }
        if (position == 2){
            try{new FirebaseSendMessage().execute(channel, "Link | " + message + "&" + channel);}
            catch (Exception e) {
                Log.d("Exception", e.toString());
            }
        }
    }

    public void showMessageInput(final int position){
        AlertDialog.Builder builder = new AlertDialog.Builder(AdminControlTabbed.this);
        builder.setTitle("Message Information");

        final EditText input = new EditText(AdminControlTabbed.this);
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        builder.setView(input);

        builder.setPositiveButton("Send", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                message = input.getText().toString();
                sendMessage(position, message);
            }
        });
        builder.show();
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
    }


    /*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_admin_control_tabbed, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }*/

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);

            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            int vNum = (int) getArguments().get(ARG_SECTION_NUMBER);
            View rootView = null;

            switch (vNum) {
                case 1:
                    rootView = inflater.inflate(R.layout.fragmenttemplate_admin_control_tabbed, container, false);

                    GridView templateGrid = (GridView) rootView.findViewById(R.id.templateGrid);
                    templateGrid.setAdapter(new ArrayAdapter<ImageButton>(getContext(),android.R.layout.simple_list_item_1, templateIButtons));

                    for (int i = 0; i < templateIcons.length; i++){
                        templateIButtons.add(new ImageButton(getContext()));
                        templateIButtons.get(i).setImageResource(templateResources[i]);
                        templateIButtons.get(i).setBackgroundColor(Color.TRANSPARENT);
                        templateIButtons.get(i).setId(i);
                    }
                    break;
                case 2:
                    rootView = inflater.inflate(R.layout.fragmentdefault_admin_control_tabbed, container, false);
                    break;

                default: //
            }
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Template";
                case 1:
                    return "Default";
            }
            return null;
        }
    }
}


rootView = inflater.inflate(R.layout.fragmenttemplate_admin_control_tabbed, container, false);

                GridView templateGrid = (GridView) rootView.findViewById(R.id.templateGrid);
                templateGrid.setAdapter(new ArrayAdapter<ImageButton>(getContext(),android.R.layout.simple_list_item_1, templateIButtons));

                for (int i = 0; i < templateIcons.length; i++){
                    templateIButtons.add(new ImageButton(getContext()));
                    templateIButtons.get(i).setImageResource(templateResources[i]);
                    templateIButtons.get(i).setBackgroundColor(Color.TRANSPARENT);
                    templateIButtons.get(i).setId(i);
                }

XML 文件中的 GridView

<GridView
    android:id="@+id/templateGrid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    />

尝试按如下方式更新您的 switch case 1 语句:

case 1:
    rootView = inflater.inflate(R.layout.fragmenttemplate_admin_control_tabbed, container, false);

    GridView templateGrid = (GridView) rootView.findViewById(R.id.templateGrid);

    for (int i = 0; i < templateIcons.length; i++){
        templateIButtons.add(new ImageButton(getContext()));
        templateIButtons.get(i).setImageResource(templateResources[i]);
        templateIButtons.get(i).setBackgroundColor(Color.TRANSPARENT);
        templateIButtons.get(i).setId(i);
    }

    templateGrid.setAdapter(new ArrayAdapter<ImageButton>(getContext(),android.R.layout.simple_list_item_1, templateIButtons));

    break;