简体   繁体   English

无法在textview中设置文本

[英]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() . 我有不能在UITextView中设置文本的问题。请参见以下代码,setText()之后TwxtView的值不会更改。 when i press Button "hello word" not change. 当我按下按钮“你好词”不变。 i want to change "hello world" to "How are you" when i press Button. 当我按下Button时,我想将“ hello world”更改为“您好吗”。

MAinActivity.java 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 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 . showPopup删除setContentView 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);
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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