简体   繁体   中英

can't set text in textview

I have problem with can't set text in UITextView .see below code , TwxtView value not change after setText() . when i press Button "hello word" not change. i want to change "hello world" to "How are you" when i press Button.

MAinActivity.java

public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     }
    public void showPopup(View view){

            final TextView hello = (TextView)findViewById(R.id.textView1);
            System.out.println(hello.getText().toString());
            String how = "how are you";
            hello.setText(how);
            System.out.println(hello.getText().toString());
            setContentView(R.layout.activity_main);
    }

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_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"
    tools:context="com.example.popup.MainActivity" >

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

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:onClick="showPopup"
        android:text="Button" />

</RelativeLayout>

Remove setContentView from showPopup . This is resetting your layout and text view to the original text.

You don't need to set the view twice. Use the following code.

public class MainActivity extends ActionBarActivity {

TextView hello;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    hello = (TextView)findViewById(R.id.textView1);
 }

public void showPopup(View view){
        String how = "How are you";
        hello.setText(how);
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM