0

我需要能够在“Hello world!”的两个文本值之间切换。和“你好!!!”。我知道这将非常简单,但是由于我对编程很陌生,所以请耐心等待。提前致谢。

package edu.purdue.cnit355_lab1;

public class MainActivity extends Activity { 

    private Button HelloButton;
    private TextView Message;
    private OnClickListener HelloButtonListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                Message.setText("Hello!!!");
            }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        HelloButton = (Button) findViewById(R.id.HelloButton);
        Message = (TextView) findViewById(R.id.MessageText); 
        HelloButton.setOnClickListener(HelloButtonListener);

    }


    @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;
    }
}

我的layout.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"
    tools:context=".MainActivity" >

    <Button
            android:id="@+id/HelloButton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/hello_button_label"
            />

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

</RelativeLayout>

我的strings.xml

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

<string name="app_name">Hello Button</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="hello_button_label">Say &quot;Hello!&quot;.</string>

4

2 回答 2

1
    @Override
    public void onClick(View v) {
        if (Message.getText().equals("Hello World")) {
          Message.setText("Hello!!!");
        } else {
          Message.setText("Hello World");
        }
   }

getResources().getString(R.string.hello_world)您还应该考虑使用而不是使用硬编码来获取字符串值 。

并尽量避免使用大写的命名变量,Message因为它们可能会被误认为是对象。

于 2013-08-28T23:23:41.260 回答
0

你的代码看起来不错。您可以在字符串之间添加一些标志来切换。像这样的东西:

private Strig[] hello = new String[]{"Hello World", "Hello!"}; 
private int toggleFlag = 0;

在您的 onClick 方法中:

Message.setTex(hello[toogleFlag]);
toggleFlag ^= 1;   // exclusive OR
于 2013-08-28T23:22:56.127 回答