我的MainActivity上的textView中的setText

时间:2014-04-29 12:12:01

标签: java android textview

我可能会问一个非常愚蠢的问题。实际上我是.net开发人员,现在转而使用 Android开发。 我有一个文本视图,我想使用setText()将文本放入其中。

我的MainActivity.java:

public class MainActivity extends ActionBarActivity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }

        TextView txView = (TextView) findViewById(R.id.lblStatus);
        txView.setText("Status Test");
    }

和XML代码是:

<TextView
            android:id="@+id/lblStatus"
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/tvStatusTag"
            android:layout_below="@id/lblImei" />

当我运行此应用程序时,它会自动停止。

logcat的: -

04-29 08:27:02.560 1649-1649/com.example.app 
E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.app, PID: 1649 
java.lang.RuntimeException: Unable to start activity 
ComponentInfo{com.example.app/com.example.app.MainActivity}: 
java.lang.NullPointerException at 
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5017) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NullPointerException 
at com.example.app.MainActivity.onCreate(MainActivity.java:27) 
at android.app.Activity.performCreate(Activity.java:5231) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515)

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.app" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.app.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

5 个答案:

答案 0 :(得分:2)

试试这个

  1. 您应声明初始化片段中的TextView
  2. 因为您的Activity实例状态必须为null,因为您没有使用onSaveInstanceState()方法保存Activity实例。
  3. 您应该在fragment_main.xml中添加TextView组件。
  4. <强> fragment_main.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="#e5e5e5"
    tools:context="com.example.app.MainActivity$PlaceholderFragment" >
    
    <TextView
        android:id="@+id/textView"
        android:textColor="#FF0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    

    <强> activity_main.xml中

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.app.MainActivity"
    tools:ignore="MergeRootFrame" />
    

    <强>的AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.app.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    

    <强> MainActivity.java

    package com.example.app;
    
    import android.app.Activity;
    import android.app.Fragment;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    
    public class MainActivity extends Activity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        if (savedInstanceState == null) {
            getFragmentManager().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 {
    
        /**
         * Declare TextView.
         */
        private TextView myText; 
        public PlaceholderFragment() {
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
    
            /**
             * Inititlize.
             */
            myText = (TextView)rootView.findViewById(R.id.textView);
            return rootView;
        }
    
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
    
            /**
             * Set Value for TextView.
             */
            myText.setText("I'm a TextView");
        }
    
    
    }
    
    }
    

    结果

    result

答案 1 :(得分:1)

代码

     public class MainActivity extends ActionBarActivity
{
    TextView txView;
      @Override

      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
         txView = (TextView) findViewById(R.id.lblStatus);
  check();
    }

     public void check()
     {
            if (savedInstanceState == null) {
              getSupportFragmentManager().beginTransaction()
                      .add(R.id.container, new PlaceholderFragment())
                      .commit();

               txView.setText("Status Test");
             }
            else
          {

          txView.setText("Status Test1");
         }
     }
      }

<强> XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
      android:background="#FFE7DB"  >
<TextView
            android:id="@+id/lblStatus"
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/tvStatusTag"
            android:layout_below="@id/lblImei" />

</RelativeLayout>

答案 2 :(得分:1)

我只是从 fragment_main.xml 中删除了 TextView 组件(lblStatus),并在 MainActivity.java 中进行了一些更改。代码如下

public class MainActivity extends ActionBarActivity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       /* if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        } */


        TextView txView = new TextView(this);
        txView.setText("Status Text");
        setContentView(txView);
    }

它比其他答案更有效..因为它非常简单:)

答案 3 :(得分:0)

Ravi我认为你正在使用appcompat库和4.4 api级别,所以如果我是对的那么你在布局文件夹中有两个布局文件,一个是简单的活动xml,另一个是用于fragment.xml。

我认为你在activity.xml中声明这个TextView不在Fragment xml文件中,所以在运行时你得到null异常所以在Fragment.xml中声明它。

答案 4 :(得分:0)

我在下面编辑了这个编辑代码,它正好适用于Set textview ... (如果您尝试扩展ActionBarActivity,则必须正确导入app_compact_v7和android.support jar) 如果仍然显示错误,请从eclipse中的项目属性刷新项目构建...

MainActivity.java:

 public class MainActivity extends Activity {       
 @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView txView = (TextView) findViewById(R.id.lblStatus);
    txView.setText("Status Test");
}

}

activity_main.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:gravity="center"
      android:orientation="vertical" >

<TextView
    android:id="@+id/lblStatus"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello" />

  </LinearLayout>