从活动中的自定义视图中读取数据

时间:2013-11-07 05:49:17

标签: android view

的活动:

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变量是空的。这段代码有什么问题?如果您想了解更多详情,请告诉我。

2 个答案:

答案 0 :(得分: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;
        }
    }

答案 1 :(得分: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 :)

        }
    });
}