【问题标题】:Android cannot access textView component from activityAndroid 无法从 Activity 访问 textView 组件
【发布时间】:2011-11-27 13:55:51
【问题描述】:

我有以下活动。

package org.dewsworld.ui;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class DetailList extends Activity {

    TextView title = (TextView) findViewById(R.id.title) ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.detail_list);

        title.setText("hello world"); 
    }

}

其中操作detail_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent" android:weightSum="1">
    <TextView android:id="@+id/title" android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_height="wrap_content" android:layout_width="match_parent"
        android:text="@string/headline" />
    <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="match_parent"></ListView>

</LinearLayout>

但是,当我运行它时,我得到一个运行时错误。 LogCat 是,

【问题讨论】:

    标签: android android-layout exception-handling textview


    【解决方案1】:
    package org.dewsworld.ui;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.TextView;
    
    public class DetailList extends Activity {
    
        TextView title;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.detail_list);
            title = (TextView) findViewById(R.id.title) ;;
            title.setText("hello world"); 
        }
    
    }
    

    它抱怨是因为您试图使用尚未创建的 Activity 方法获取 textView 的值(因为它的 Oncreate() 尚未运行)

    【讨论】:

      【解决方案2】:

      这样试试

      public class DetailList extends Activity {
      TextView title;
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          // TODO Auto-generated method stub
          super.onCreate(savedInstanceState);
          setContentView(R.layout.detail_list);
      
          title = (TextView) findViewById(R.id.title) ;
          title.setText("hello world"); 
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多