Android添加多个Button的正确方法

作为初学者的我们,真的能干出很有意思的事,比如这样一个界面


三八二十四个按钮,然后每一个都有点击事件,我是怎么实现的、看下:

就这样,一个TableLayout,一行三个,一共八行然后每个Buttton手动添加名字,点击事件,就这个xml就有300多行,真佩服!

        <TableRow>
            <Button
                android:id="@+id/beijing_button"
                android:layout_width="0dp"
                android:layout_height="35dp"
                android:layout_weight="1"
                android:background="@drawable/button_add_city_selector"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="8dp"
                android:text="北京"
                android:onClick="click"/>
            <Button
                android:id="@+id/shanghai_button"
                android:layout_width="0dp"
                android:layout_height="35dp"
                android:layout_weight="1"
                android:background="@drawable/button_add_city_selector"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="8dp"
                android:text="上海"
                android:onClick="click"/>
            <Button
                android:id="@+id/guangzhou_button"
                android:layout_width="0dp"
                android:layout_height="35dp"
                android:layout_weight="1"
                android:background="@drawable/button_add_city_selector"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="8dp"
                android:text="广州"
                android:onClick="click"/>
        </TableRow>
        <TableRow>
            <Button
                android:id="@+id/shenzhen_button"
                android:layout_width="0dp"
                android:layout_height="35dp"
                android:layout_weight="1"
                android:background="@drawable/button_add_city_selector"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="8dp"
                android:text="深圳"
                android:onClick="click"/>
            <Button
                android:id="@+id/nanjing_button"
                android:layout_width="0dp"
                android:layout_height="35dp"
                android:layout_weight="1"
                android:background="@drawable/button_add_city_selector"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="8dp"
                android:text="南京"
                android:onClick="click"/>
            <Button
                android:id="@+id/hangzhou_button"
                android:layout_width="0dp"
                android:layout_height="35dp"
                android:layout_weight="1"
                android:background="@drawable/button_add_city_selector"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="8dp"
                android:text="杭州"
                android:onClick="click"/>
        </TableRow> 

再给你们看下Activity中的点击事件,哈哈哈

public void click(View v) {
        // TODO Auto-generated method stub
        //获取组件的资源id
        int id = v.getId();
        switch (id) {
            case R.id.beijing_button:
                city = "北京";
                break;
            case R.id.shanghai_button:
                city = "上海";
                break;
            case R.id.guangzhou_button:
                city = "广州";
                break;
            case R.id.shenzhen_button:
                city = "深圳";
                break;
            case R.id.nanjing_button:
                city = "南京";
                break;
            case R.id.hangzhou_button:
                city = "杭州";
                break;
            case R.id.suzhou_button:
                city = "苏州";
                break;
            case R.id.qingdao_button:
                city = "青岛";
                break;
            case R.id.jinan_button:
                city = "济南";
                break;
            case R.id.zhengzhou_button:
                city = "郑州";
                break;
            case R.id.xian_button:
                city = "西安";
                break;
            case R.id.shenyang_button:
                city = "沈阳";
                break;
            case R.id.changsha_button:
                city = "长沙";
                break;
            case R.id.wuhan_button:
                city = "武汉";
                break;
            case R.id.xiamen_button:
                city = "厦门";
                break;
            case R.id.chengdu_button:
                city = "成都";
                break;
            case R.id.chongqing_button:
                city = "重庆";
                break;
            case R.id.changchun_button:
                city = "长春";
                break;
            case R.id.sanya_button:
                city = "三亚";
                break;
            case R.id.zhuhai_button:
                city = "珠海";
                break;
            case R.id.tianjin_button:
                city = "天津";
                break;
            case R.id.taiyuan_button:
                city = "太原";
                break;
            case R.id.datong_button:
                city = "大同";
                break;
            case R.id.yanggao_button:
                city = "阳高";
                break;
            default:
                break;
        }
都是可以理解的,初学者的执着,那今天有时间了,我把他正常的写一下吧:

首先在项目中添加assets文件夹,新建一个txt文件,里面放好我们写好的JSON数据(这个得自己搞啦)


[
{
"id": "1",
"cityName": "北京"
},
{
"id": "2",
"cityName": "上海"
},
{
"id": "3",
"cityName": "广州"
},
{
"id": "4",
"cityName": "深圳"
},
{
"id": "5",
"cityName": "南京"
},
{
"id": "6",
"cityName": "杭州"
},
{
"id": "7",
"cityName": "苏州"
},
{
"id": "8",
"cityName": "青岛"
},
{
"id": "9",
"cityName": "济南"
},
{
"id": "10",
"cityName": "郑州"
},
{
"id": "11",
"cityName": "西安"
},
{
"id": "12",
"cityName": "沈阳"
},
{
"id": "13",
"cityName": "长沙"
},
{
"id": "14",
"cityName": "武汉"
},
{
"id": "15",
"cityName": "厦门"
},
{
"id": "16",
"cityName": "成都"
},
{
"id": "17",
"cityName": "重庆"
},
{
"id": "18",
"cityName": "长春"
},
{
"id": "19",
"cityName": "三亚"
},
{
"id": "20",
"cityName": "珠海"
},
{
"id": "21",
"cityName": "天津"
},
{
"id": "22",
"cityName": "太原"
},
{
"id": "23",
"cityName": "大同"
},
{
"id": "24",
"cityName": "阳高"
}
]

解析JSON新建的JavaBean类

public class PopularCity {
    /**
     * id : 1
     * cityName : 北京
     */
    private String id;
    private String cityName;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
}

在activity中自定义一个方法,用来获取JSON数据(我们这小Demo,就写activity里吧,正常开发都得放到工具类里面的)

    /**
     * 从assets文件中获得Json串
     */
    private String getAssetsData(String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null) {
                Result += line;
            }
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

布局文件中添加GridView

<GridView
        android:id="@+id/grid_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:numColumns="3"
        android:listSelector="@android:color/transparent">
    </GridView>

GridView的Item

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/small_textview"
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:background="@drawable/button_add_city_selector"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_centerInParent="true"
        android:gravity="center" />
</RelativeLayout>

GridView的适配器

public class GridViewAdapter extends BaseAdapter {
    private Context context;
    private List<PopularCity> popularCityList;

    public GridViewAdapter(Context context, List<PopularCity> popularCity) {
        this.context = context;
        this.popularCityList = popularCity;
    }

    @Override
    public int getCount() {
        return popularCityList.size();
    }
    @Override
    public Object getItem(int position) {
        return popularCityList.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.gridview_list_item, null);
            holder = new ViewHolder();
            holder.textView = (TextView) convertView.findViewById(R.id.small_textview);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.textView.setText(popularCityList.get(position).getCityName());
        return convertView;
    }
    public static class ViewHolder {
       TextView textView;
    }
}

Activity中获取GridView的实例,设置适配器,点击事件

        gridView = (GridView) findViewById(R.id.grid_view);
        popularCityList = new Gson().fromJson(getAssetsData("cities.txt"), new TypeToken<List<PopularCity>>() {
        }.getType());
        GridViewAdapter adapter = new GridViewAdapter(this, popularCityList);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(CityAddActivity.this,popularCityList.get(i).getCityName(),Toast.LENGTH_SHORT).show();
            }
        });

总结

哈哈,不知不觉写了一堆东西,乱七八糟的,就是想告诉像我一样的初级选手,不要傻乎乎的写重复的东西,一点效率都没有,大家都是慢慢成长起来的,希望我的一些东西可以分享给你们,加油吧!

猜你喜欢

转载自blog.csdn.net/pengbo6665631/article/details/80428215
今日推荐