MainActivity.java
package com.emple.divide;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
public class MainActivity extends Activity {
private String[] str=new String[]{"one","two","three","four"};
private GridView gv;
private TextView tv;
private Button bt;
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,str);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gv=(GridView)findViewById(R.id.gv);
tv=(TextView)findViewById(R.id.tv);
bt=(Button)findViewById(R.id.bt);
bt.setOnClickListener(new bt_click());
gv.setOnItemClickListener(new gv_click());
}
class bt_click implements OnClickListener
{
public void onClick(View v)
{
gv.setNumColumns(2);
gv.setAdapter(arrayAdapter);
}
}
class gv_click implements OnItemClickListener
{
public void onItemClick(AdapterView<?> parent,View v,int position,long arg3)
{
switch (arrayAdapter.getCount())
{
case 4:
tv.setText(str[position]);
break;
default:break;
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
arrayadapter初始化過早,arrayadapter在activity類實例化的話的時候就初始化了,arrayadapter初始化的時候傳入的this是一個context,這個時候context還是無效的,需要在oncreate調用之後才對arrayadapter進行初始化,放在supo.oncreate之後,或者放在onresume裡面都可以