activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<GridView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/gridView"
android:numColumns="2"
android:horizontalSpacing="1dp"
android:verticalSpacing="5dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="146dp" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 热门城市 -->
<string-array name="hot_city">
<item>北京</item>
<item>上海</item>
<item>广州</item>
<item>深圳</item>
<item>杭州</item>
<item>成都</item>
</string-array>
</resources>
MainActivity.java:
package com.example.gridview;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.GridView;
public class MainActivity extends ActionBarActivity {
private ArrayAdapter<String> mAdapterHot;
private GridView gv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gv = (GridView) findViewById(R.id.gridView);
//第一个参数是context,第二个参数是GridView中item的布局文件,第三个参数是数据源
mAdapterHot = new ArrayAdapter<String>(MainActivity.this, R.layout.text_item, getResources().getStringArray(R.array.hot_city));
gv.setAdapter(mAdapterHot);
}
}
text_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myCheckedTextView1"
android:layout_width="80dp"
android:layout_height="35dp"
android:textColor="#a99a8a"
android:textSize="16dp"
android:text="aaaaa"
android:background="#88aa99"
android:gravity="center"
android:paddingLeft="6dip"
/>
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u010778159/article/details/46893769