2014-01-30 24 views
-1

大家好,我對Android編程完全陌生,我想學習的其中一件事是如何基於按鈕觸發事件。到目前爲止,我只設法創建一個按鈕,但我不知道如何創建事件,更重要的是我必須修改哪些文件?我如何創建一個改變背景和字體文本的按鈕?

activity_main.xml中:

<Button android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/button_id" 
     android:text="@string/font_color" 
     android:onClick="toggleChange"/> 

我主要是熟悉的文件activity_main.xml中和mainActivity.java,並取得了在主activity.java功能:

public void toggleChange(){ 
     //not sure what goes here 
    } 

我不確定在函數內部放置什麼,我也不完全確定java本身就是最需要的。我是否需要更改其他我不知道的XML文件?謝謝你的幫助。

public boolean onCreateOptionsMenu(Menu menu) { 
     final Button button = (Button) findViewById(R.id.button_id); 
     button.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
       // Perform action on click 
       // Use attributes of View or cast to Button 
       // to change background/text 
       //v.setText ("Hello Blu"); 
     } 
     }); 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 
+0

你應該看這個YouTube上的Android系列,你可以瞭解在Android發展非常基本的從那裏: HTTP:// WWW。 youtube.com/watch?v=CxPh1tgiK2g&list=PL4695D1A275CDEE4A – 2014-01-31 00:07:06

+0

我已經安裝了Eclipse Paulo Paulo – blu

+0

我的意思是系列不是第一個視頻。 – 2014-01-31 00:14:19

回答

0

可能做到這一點的更常見的方式是

final Button button = (Button) findViewById(R.id.button_id); 
     button.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
       // Perform action on click 
       // Use attributes of View or cast to Button 
       // to change background/text 
       v.setText ("Hello Blu"); 
     } 
     }); 
+0

這是在公共無效功能的權利? – blu

+0

通常這是放在onCreate方法。現在也許最安全。 –

+0

我得到一些錯誤:按鈕無法解析爲一個類型,button_id無法解析或不是一個字段,方法setText(字符串)是未定義的類型視圖 – blu

0

在XML實現一個TextView,並在你的java設置。 XML:

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

設置它放在你的java:

private TextView mText; 

     mText = (TextView) findViewById(R.id.text); 
     Button mButton 

= (Button) mRootView.findViewById(R.id. button_id); 

      mButton.setOnClickListener(new View.OnClickListener() { 

       @Override 
       public void onClick(View arg0) { 
       mText.setText("whatever you like"); 

       } 
      }); 
相關問題