需求:
1.有两个按钮,点击按钮1,显示2*2列表,点击按钮2,显示3*3列表;
2.点击列表中的选项,文字显示相应内容;
效果:
代码:
private TextView mTextView;
private Button mButton1,mButton2;
private GridView mGridView;
private String[] mGames1,mGames2;
private ArrayAdapter<String> mArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGames1 = new String[]
{
"one",
"two",
"three",
"four"
};
mGames2 = new String[]
{
"one",
"two",
"three",
"four",
"one",
"two",
"three",
"four",
"one"
};
mButton1 = (Button)findViewById(R.id.button1);
mButton2 = (Button)findViewById(R.id.button2);
mGridView = (GridView)findViewById(R.id.gridView1);
mTextView = (TextView)findViewById(R.id.textView1);
mButton1.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mGridView.setNumColumns(2);
mArrayAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.simple_text, mGames1);
mGridView.setAdapter(mArrayAdapter);
mGridView.setSelection(2);
mGridView.refreshDrawableState();
}
});
mButton2.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mGridView.setNumColumns(3);
mArrayAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.simple_text, mGames2);
mGridView.setAdapter(mArrayAdapter);
//mGridView.setSelection(2);
//mGridView.refreshDrawableState();
}
});
mGridView.setOnItemClickListener(new GridView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
switch(mArrayAdapter.getCount())
{
case 4:
/*arg2表示是哪个位置的*/
mTextView.setText(mGames1[arg2]);
break;
case 9:
mTextView.setText(mGames2[arg2]);
break;
}
}
});
}
activity_main XML:
<GridView
android:id="@+id/gridView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop ="20dip"
android:layout_marginLeft="5dip"
android:numColumns="3" >
</GridView>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop ="200dip"
android:layout_marginLeft="15dip"
android:text="2lie" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop ="200dip"
android:layout_marginLeft="150dp"
android:text="3lie" />
simple_text.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="@drawable/blue"
/>
重点:
1.控件的绝对位置设置;
2.GridView的是何意思?
mGridView.setSelection(2);
mGridView.refreshDrawableState();
3.数据从string传给ArrayAdapter,gridView和ArrayAdapter之间需要设置绑定
4.simple_text是个xml文件,如果textView标签外面有Layout的话,是有问题的,另外xmlns的属性不知道是什么用处?