0

I am trying to dynamically create ImageButtons inside of a GridView but for some reason, they are showing up as strings (as shown below). I have looked at several posts but am still unsure of the problem. I have attached my code in addition to the xml file.

Full 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);
                }

GridView inside XML File

<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"
    />

App screenshot

2
  • Can you post the rest of your activity? I'm not sure what type templateIButtons is. Commented Mar 31, 2017 at 19:30
  • Sure. Doing that right now. Commented Mar 31, 2017 at 19:32

1 Answer 1

1

Try updating your switch case 1 statement as follows:

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;
Sign up to request clarification or add additional context in comments.

5 Comments

Unfortunately this didn't work, but could the issue be that 'android.R.layout.simple_list_item_1' converts the imagebutton to a string?
@kmindspark Yeah that looks like the value of a resource string GUID or whatever.
Do you know of a possible fix to this? Would I need to create a custom array adapter?
Yes, you need a custom array adapter and your own layout (android.R.layout.simple_list_item_1 is TextView based (think it has two, hence the output).
@kmindspark Hi, I've just been updating my buttons to use "newer" vector / 2d / flat / material.io graphics and they work much better in an ImageView as opposed to an ImageButton. ImageButton is just a direct child of an ImageView that adds some pre-baked formatting (centering with padding), which constrains the vectors to scale too small usually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.