程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程解疑 >> 編程-android,剛點debug就崩潰了

編程-android,剛點debug就崩潰了

編輯:編程解疑
android,剛點debug就崩潰了

圖片說明
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裡面都可以

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved