从另一个类访问方法

时间:2013-06-14 14:51:14

标签: java class methods

我按照你的推荐做了第三节!!

public class WebSocket_Connector {

private static final String TAG = "ECHOCLIENT";
public final WebSocketConnection mConnection = new WebSocketConnection();

public void connect(final String wsuri) {

      Log.d(TAG, "Connecting to: " + wsuri); 

      try {
         mConnection.connect(wsuri, new WebSocketHandler() {

            @Override
            public void onOpen() {
               Log.d(TAG, "Status: Connected to " + wsuri ); 
               Log.d(TAG, "Connection successful!\n");
            }

            @Override
            public void onTextMessage(String payload) {
               Log.d(TAG, "Got echo: " + payload);
            }

            @Override
            public void onClose(int code, String reason) {
               Log.d(TAG, "Connection closed.");
            }
         });
      } catch (WebSocketException e) {

         Log.d(TAG, e.toString());
      }
   }

}

从另一个类,我试图访问传递字符串类型“id”的连接

public class Myoffers_Fragment extends Fragment {

private static final String TAG = "ECHOCLIENT";
public String id;

public static Fragment newInstance(Myoffers context, int pos, 
        float scale)
{
    Bundle b = new Bundle();
    b.putInt("pos", pos);
    b.putFloat("scale", scale);
    return Fragment.instantiate(context, Myoffers_Fragment.class.getName(), b);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    if (container == null) {
        return null;
    }
    WebSocket_Connector A = new WebSocket_Connector();

    LinearLayout l = (LinearLayout) 
            inflater.inflate(R.layout.mf, container, false);

    int pos = this.getArguments().getInt("pos");
    TextView tv = (TextView) l.findViewById(R.id.text);
    tv.setText("Position = " + pos);

    ImageView product_photo = (ImageView) l.findViewById(R.id.myoffer_image);

    switch(pos){
    case 0:
        product_photo.setImageResource(R.drawable.myoffers_0);
        Log.d(TAG, "Current pos" + pos);
        Toast.makeText(this.getActivity(), "Product" + pos + " is selected.", Toast.LENGTH_LONG).show();
        id = "product 0";
        A.mConnection.sendTextMessage(id);
        break;

你能看到“A.mConnection.sendTextMessage(id);” ?? 这是正确的方法吗?

2 个答案:

答案 0 :(得分:2)

您需要创建类的实例才能访问其公共方法。考虑到你的连接方法在你的主类中,你必须声明:Main main = new Main();(另外注意,你应该总是大写你的类名)。然后拨打main.connect();

答案 1 :(得分:0)

代码应该是自我解释的

 class A {
    public void someMethod(){
       System.out.println("in someMethod");
    }
 }

 public class B {

    public static void main(String [] args){
        A a = new A(); // first create the object of class A
        a.someMethod();// call its method in class B
    }

 }