剛學Android遇到的相關問題,findViewById值為null(新版本),老鳥歡迎你的指正

來源:互聯網
上載者:User

環境交代:

    剛學Android,在官網下載的新版的ADT

  以及新版的SDK

    在新版的IDE(ADT)建立項目時如果你的最小版本(minimum required SDK)要支援4.0以下版,並且目標版本為(4.0+).那麼此時IDE會為你建立一個相容包    (appcompat_v7)如,

 

    建立發簡訊項目後就會有如下的項目目錄結構

 

 

  這個時候在產生的項目主Activity不是以前的那種繼承的Activity,而是繼承的ActionBarActivity,我把發簡訊的介面建立起。介面效果如下。點此時我用      this.findViewById(R.id.but_send);來得到發簡訊介面的Button按鈕。但是沒得到我想要的button,輸出button為null。

 

這讓我一個初學android的這咋整??百度一哈沒有可用的答案,於是自己解決。

解決辦法

搗鼓很久後搗鼓成功碼如下,原因是因為在新的layout檔案不是存放在預設的(res/layout/activity_main.xml)檔案中,而是存放在(res/layout/fragment_main.xml)檔案中。所以要在fragment_main.xml去早對應的ID才會找到,而新的IDE產生的程式碼中載入(fragment_main.xml)檔案是在一個內部載入的,所以我們可以在內部類載入處來得到Button:

package com.shuqi.cms;import android.support.v7.app.ActionBarActivity;import android.support.v4.app.Fragment;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends ActionBarActivity{    private static EditText edt_num = null;    private static EditText edt_content = null;    private static Button button = null;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                if (savedInstanceState == null) {            getSupportFragmentManager().beginTransaction()                    .add(R.id.container, new PlaceholderFragment())                    .commit();        }            }    @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);    }    /**     * A placeholder fragment containing a simple view.     */    public static class PlaceholderFragment extends Fragment {                View rootView = null;        public PlaceholderFragment() {        }        @Override        public View onCreateView(LayoutInflater inflater, ViewGroup container,                Bundle savedInstanceState) {            rootView = inflater.inflate(R.layout.fragment_main, container, false);                        edt_num =  (EditText) rootView.findViewById(R.id.edt_cms_num);            edt_content = (EditText) rootView.findViewById(R.id.edt_cms_content);            button = (Button) rootView.findViewById(R.id.but_send);          //            System.out.println(button);                        return rootView;        }            }        public void onClick(View arg0) {                if(edt_num.getText().toString().trim().equals("")||edt_content.getText().toString().trim().equals("")){                        Context context = getApplicationContext();            CharSequence text = "電話號碼或者簡訊內容不可為空!!";            int duration = Toast.LENGTH_SHORT;            Toast toast = Toast.makeText(context, text, duration);            toast.show();                    }else{                        System.out.println("發簡訊");                                }    }}

如下:

其他解決findViewById的值為空白的方法:

原文地址:http://blog.sina.com.cn/s/blog_5e58565701012q2d.html

錯誤:findViewById返回Null,報nullpointer錯誤

網上搜了下,拾人牙慧,總結原因,一般為3種:


1.在另一個view的元素應該用baseView.findViewById()來拿

findViewById()是要指定view的,如果在該view下找不到,自然報null。平時注意養成寫view.findViewById()的習慣就不容易錯了。

 

2.findViewById在setContentView(R.layout.main);之前.

即在setContentView調用之前,調用了findViewById去找main布局中的介面元素lv_contactbook,那麼所得到的lv一定是null。正確的做法是將上面代碼中加粗的哪一行,挪至setContentView方法調用之後即可。


3.clean一下工程,讓ID重建

這種情況是調用LayoutInflater.inflate將布局xml規定的內容轉化為相應的對象。比如有rowview.xml布局檔案(比如在自訂Adapter的時候,用作ListView中的一行的內容的布局),假定在自定的Adapter的getView方法中有類似如下的代碼:
View rowview = (View)inflater.inflate(R.layout.rowview, parent, false);
TextView tv_contact_id =(TextView)rowview.findViewById(R.id.tv_contact_id);
TextView tv_contactname =(TextView)rowview.findViewById(R.id.tv_contactname);

有時候居然也會發現rowview非空,但tv_contact_id和tv_contactname都是null!仔細看代碼,怎麼也看不出錯誤來。到底是什麼原因造成的呢?答案是Eclipse造成的,要解決這個問題,需要這個項目clean一次(Project菜單 -> Clean子功能表),這樣就OK了。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.