0

活动:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_cool); //layout with button and custom view

    myNewView myView = new myNewView(this); // create custom view

     button = (Button) findViewById(R.id.btn_1);         
     button.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            String t = myView.do_smth(); ///HERE is NOT working

        }
     });
}

自定义视图:

public class myNewView extends View {
    public myNewView(Context context) {
     super(context);
     initialize();
    }
    public String do_smth() {
    String t = "";
        t = "34";

    return t;
    }
}

所以 t 变量为空。这段代码有什么问题?如果您想了解更多详细信息,请告诉我。

4

2 回答 2

0
    // try this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dp">

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

</LinearLayout>

    public class MyActivity extends Activity {

        Button button;
        myNewView myView;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.my);

             myView = new myNewView(this); // create custom view

            button = (Button) findViewById(R.id.btn_1);
            button.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    String t = myView.do_smth();
                    Toast.makeText(MyActivity.this,t,Toast.LENGTH_SHORT).show();
                }
            });

        }

    }

    public class myNewView extends View {
        public myNewView(Context context) {
            super(context);
        }
        public String do_smth() {
            String t ="34";
            return t;
        }
    }
于 2013-11-07T05:55:49.680 回答
0

我认为问题在于 myView 应该可以final在 下面访问onClickListener它:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_cool); //layout with button and custom view

    final myNewView myView = new myNewView(this); // create custom view 
    // (must be final, for it to be accessed inside the onClickListener

    button = (Button) findViewById(R.id.btn_1);
    button.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            String t = myView.do_smth(); ///HERE should NOW work :)

        }
    });
}
于 2013-11-07T06:33:02.303 回答