Add an array of buttons to a GridView in an Android application

℡╲_俬逩灬. 提交于 2019-11-27 04:38:35
cibercitizen1

In the following code, you should change the upper limits of the for to a variable.

public class MainActivity
        extends Activity
        implements View.OnClickListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TableLayout layout = new TableLayout (this);
        layout.setLayoutParams( new TableLayout.LayoutParams(4,5) );

        layout.setPadding(1,1,1,1);

        for (int f=0; f<=13; f++) {
            TableRow tr = new TableRow(this);
            for (int c=0; c<=9; c++) {
                Button b = new Button (this);
                b.setText(""+f+c);
                b.setTextSize(10.0f);
                b.setTextColor(Color.rgb( 100, 200, 200));
                b.setOnClickListener(this);
                tr.addView(b, 30,30);
            } // for
            layout.addView(tr);
        } // for

        super.setContentView(layout);
    } // ()

    public void onClick(View view) {
        ((Button) view).setText("*");
        ((Button) view).setEnabled(false);
    }
} // class
Fedor

Here's a nice sample for you:

https://developer.android.com/guide/topics/ui/layout/gridview.html

You should just create buttons instead of imageviews in getView adapter method.

alienjazzcat

If you are using a GridView, or a ListView (etc), and are producing Views to populate them via the adapter getView(pos, convertView, viewGroup), you might encounter confusion (i did once).

If you decide to re-use the convertView parameter, you must reset everything inside of it. It is an old view being passed to you by the framework, in order to save the cost of inflating the layout. It is almost never associated with the position it was in the layout before.

class GridAdapter extends BaseAdapter // assigned to your GridView
{
    public View getView(int position, View convertView, ViewGroup arg2) {
        View view;
        if (convertView==null)
        {
            view = getLayoutInflater().inflate(R.layout.gd_grid_cell, null);
        }
        else
        {
             // reusing this view saves inflate cost
             // but you really have to restore everything within it to the state you want
            view = convertView;
        }


        return view;
    }
    //  other methods omitted (e.g. getCount, etc) 
}

I think this represents one of those Android things where the concept is a little difficult to grasp at first, until you realize there's a significant optimization available within it (have to be nice to CPU on a little mobile device)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!