Android初学者(添加按钮)

时间:2012-01-12 10:16:46

标签: android android-layout android-widget android-manifest

我是android的初学者并制作了我的第一个应用程序,即我已经使用了3个textViews和1个名为Add的按钮。当我点击这个按钮时,应该添加2个textViews的值并显示在第三个textView中。我使用了eventListener和buttonClick事件,但它不起作用。请引导我使用添加按钮的代码。

1 个答案:

答案 0 :(得分:1)

好的,我帮你。 首先按如下所示创建xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent" android:layout_width="fill_parent"
    android:layout_gravity="center_horizontal" android:orientation="horizontal"
    android:layout_weight="1" android:id="@+id/singleEmployee"
    android:background="#ffffff">
    <TextView android:text="TextView" android:id="@+id/textView1"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    <TextView android:text="TextView" android:id="@+id/textView2"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    <TextView android:text="TextView" android:id="@+id/textView3"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    <Button android:text="Button" android:id="@+id/button1"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

然后使用此Java代码完成您的愿望:

public class HelperStackOverflowActivity extends Activity {
/** Called when the activity is first created. */
TextView tv1,tv2,tv3;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.testing);
    tv1 = (TextView)findViewById(R.id.textView1);
    tv2 = (TextView)findViewById(R.id.textView2);
    tv3 = (TextView)findViewById(R.id.textView3);
    tv1.setText("Hello");
    tv2.setText("World");
    Button add = (Button)findViewById(R.id.button1);
    add.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            tv3.setText("");
            String tvValue1 = tv1.getText().toString();
            String tvValue2 = tv2.getText().toString();
            tv3.setText("Value of First Text is: "+tvValue1+".And the value of second TextView is: "+tvValue2);
        }
    });
}

}

希望它会对你有所帮助。 请享用。 :)