我正在尝试创建一个测试应用程序,当我按下ImageButton时,会出现一条日志消息。简单。

我希望ImageButton视图可用于一个类。

我这样做是这样的:
用正确的构造器名称更新

public class MainActivity extends Activity {


  MyButtonClass btnOk = null;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

        btnOk = new ButtonClass(this);
        setContentView(R.layout.activity_main);
  }
}


class MyButtonClass extends ImageButton{

        public MyButtonClass(Context context) {
            super(context);

            findViewById(R.id.btButton);

              OnClickListener oclBtnOk = new OnClickListener() {
                  @Override
                  public void onClick(View v) {
                    // change text of the TextView (tvOut)
                   Log.e("Log This:","Yay! I am working!");
                  }
                };

                setOnClickListener(oclBtnOk);
        }



    }


我的布局xml是:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="horizontal" >

    <ImageButton
        android:id="@+id/btButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

</LinearLayout>


当我运行该应用程序时,我在Log cat上没有看到任何错误,并且该应用程序没有退出,但是当我按下它时ImageButton却不执行任何操作:/

最佳答案

为什么会变得如此混乱。您的代码需要大量修剪。你可以试试这个代码

    public class MyAndroidAppActivity extends Activity {

ImageButton imageButton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    addListenerOnButton();

}

public void addListenerOnButton() {

    imageButton = (ImageButton) findViewById(R.id.imageButton1);

    imageButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

           Toast.makeText(MyAndroidAppActivity.this,
            "ImageButton is clicked!", Toast.LENGTH_SHORT).show();

        }

    });

}

    }


祝你好运=)

关于java - ImageButton在类中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18017232/

10-12 00:12
查看更多