2012-01-12 66 views
0

我是Android的初學者,正在製作我的第一個應用程序,即我已經拍攝了3個textViews和1個名爲Add的按鈕。當我點擊這個按鈕時,應該添加2個textViews的值並顯示爲第三個textView。我曾使用eventListener和buttonClick事件,但它不起作用。請引導我與添加按鈕的代碼。Android初學者(添加按鈕)

+0

喲有多少嘗試?請輸入一些代碼,我們會幫助你。 – 2012-01-12 12:06:08

回答

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

}

希望它會幫助你。 享受。 :)