2017-07-17 71 views
1

當我運行該應用程序。按鈕拒絕迴應。我設置了一個Toast和一個logcat來檢查響應。但不是。請幫忙解決我的按鈕沒有在Android工作室響應

這是我的源代碼

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Hello World!" 
    android:id="@+id/textView" /> 

<Button 
    android:text="Button" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/textView" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="14dp" 
    android:id="@+id/button" 
    tools:onClick="topClick" /> 

<Button 
    android:text="Button" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/button" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="14dp" 
    android:id="@+id/button2" 
    tools:onClick="bottomClick" /> 

和我的Java方法;

public class MyActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.my_layout); 

     //Testing the Toast and Log in action 
     Toast.makeText(this, "Can you see me?", Toast.LENGTH_SHORT).show(); 

     Log.i("info", "Done creating the app"); 
    } 


    //creating method topclick 
    public void topClick(View v) { 
     Toast.makeText(this, "Top button clicked", Toast.LENGTH_SHORT).show(); 

     Log.i("info", "The user clicked the top button"); 
    } 

    //creating method bottomclick 
    public void bottomClick(View v) { 
     Toast.makeText(this, "Bottom button clicked", Toast.LENGTH_SHORT).show(); 

     Log.i("info", "the user clicked the bottom button"); 
    } 

} 

回答

0

更換

tools:onClick

兩個按鈕。

欲瞭解更多情況下,這將有助於你理解爲什麼需要這種變化,閱讀了關於該tools namespace

的Android Studio支持多種XML的工具命名空間,使設計時的功能屬性(例如作爲哪個佈局顯示在片段中)或編譯時行爲(例如應用於XML資源的縮小模式)。構建應用程序時,構建工具將刪除這些屬性,以便對APK大小或運行時行爲沒有影響。

0

我極力不推薦使用你的實現,因爲你幾乎不知道哪個按鈕的方法。試試這個。

XML

<Button 
    android:text="Button" 
    android:id="@+id/button1" /> 

<Button 
    android:text="Button" 
    android:id="@+id/button2" /> 

ACTIVITY.JAVA

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.my_layout); 

    Button button01 = (Button)findViewById(R.id.button01); 
    Button button02 = (Button)findViewById(R.id.button02); 

    button01 .setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Toast.makeText(MyActivity.this, "This is button01", Toast.LENGTH_SHORT).show(); 
     } 
    }); 
    button02 .setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Toast.makeText(MyActivity.this, "This is button02", Toast.LENGTH_SHORT).show(); 
     } 
    }); 
}