【问题标题】:Accessing TextView from other class in android从android中的其他类访问TextView
【发布时间】:2016-01-15 20:01:52
【问题描述】:

您好,我是 android 新手。我正在使用端点创建一个简单的谷歌云 appengine 应用程序。我正在使用本教程 https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/HelloEndpoints。但问题是我想在 textview 中显示结果而不是在 toast 中。


布局.xml

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical"
       android:id="@+id/lay1">

    <EditText
        android:id="@+id/edt1"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:hint="Enter Number"
        android:inputType="number"
        android:textSize="24sp" />

    <EditText
        android:id="@+id/edt2"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:hint="Enter Number"
        android:inputType="number"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/tv1"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:hint="Result Will be Here"
        android:textSize="24sp" />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="Add" />

    </LinearLayout>

GoogleAppEngActivity.java(主要活动)


        package com.ontech.googleappengine;

        import android.content.Context;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.util.Pair;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.TextView;

        public class GoogleAppEngActivity extends AppCompatActivity {

            Button btnAdd;
            TextView tv1;
            //String val1,val2;
            EditText edt1,edt2;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_google_app_eng);


                edt1=(EditText)findViewById(R.id.edt1);
                edt2=(EditText)findViewById(R.id.edt2);
                tv1=(TextView)findViewById(R.id.tv1);
                btnAdd =(Button)findViewById(R.id.btnAdd);
                btnAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        String temp = "";
                        temp = edt1.getText().toString();
                        temp += "+";
                        temp += edt2.getText().toString();

                        new EndpointsAsyncTask().execute(new Pair<Context, String>(GoogleAppEngActivity.this, temp));
                      //  tv1.setText( new EndpointsAsyncTask().);
                    }
                });

               // new EndpointsAsyncTask().execute(new Pair<Context, String>(this, "Manfred"));
            }

            public TextView getTextView(){

                TextView txtView=(TextView)findViewById(R.id.tv1);
                return txtView;
            }


        }

EndpointsAsyncTask.java


    package com.ontech.googleappengine;

    //package com.ontech.googleappengine;

    import android.content.Context;
    import android.os.AsyncTask;
    import android.text.Layout;
    import android.util.Pair;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.google.api.client.extensions.android.http.AndroidHttp;
    import com.google.api.client.extensions.android.json.AndroidJsonFactory;
    import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
    import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
    import com.ontech.myapplication.backend.myApi.MyApi;

    import java.io.IOException;

    /**
     * Created by on 05-11-2015.
     */
    public class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
        private static MyApi myApiService = null;
        private Context context;

        @Override
        protected String doInBackground(Pair<Context, String>... params) {
            if (myApiService == null) {  // Only do this once
              /*  MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
                        new AndroidJsonFactory(), null)
                        // options for running against local devappserver
                        // - 10.0.2.2 is localhost's IP address in Android emulator
                        // - turn off compression when running against local devappserver
                        .setRootUrl("http://10.0.2.2:8080/_ah/api/")
                        .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                            @Override
                            public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
                                abstractGoogleClientRequest.setDisableGZipContent(true);
                            }
                        });*/

                MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
                        .setRootUrl("https://leafy-display-112017.appspot.com/_ah/api/");
                // end options for devappserver

                myApiService = builder.build();
            }

            context = params[0].first;
            String name = params[0].second;

            try {
                return myApiService.sayHi(name).execute().getData();
            } catch (IOException e) {
                return e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {

            Toast.makeText(context, result, Toast.LENGTH_LONG).show();
        }
    }

我的端点.java


package com.ontech.myapplication.backend;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;

import javax.inject.Named;

/**
 * An endpoint class we are exposing
 */
@Api(
        name = "myApi",
        version = "v1",
        namespace = @ApiNamespace(
                ownerDomain = "backend.myapplication.ontech.com",
                ownerName = "backend.myapplication.ontech.com",
                packagePath = ""
        )
)
public class MyEndpoint {

    /**
     * A simple endpoint method that takes a name and says Hi back
     */
    @ApiMethod(name = "sayHi")
    public MyBean sayHi(@Named("name") String name) {
        MyBean response = new MyBean();

        String val1, val2;
        val1 = name.substring(0, name.indexOf("+"));
        val2 = name.substring(name.indexOf("+") + 1);
        int res = Integer.parseInt(val1) + Integer.parseInt(val2);

       // response.setData("Hi, " + name);
        response.setData(Integer.toString(res));
        return response;
    }

}

MyBean.java


package com.ontech.myapplication.backend;

/**
 * The object model for the data we are sending through endpoints
 */
public class MyBean {

    private String myData;
        public String getData() {
        return myData;
    }

    public void setData(String data) {
        myData = data;
    }
}

【问题讨论】:

    标签: android textview google-cloud-endpoints


    【解决方案1】:

    TextView 作为参数传递给 EndpointsAsyncTask 的构造函数,您希望在其中显示结果,如下所示。

    public class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
            private static MyApi myApiService = null;
            private Context context;
            private TextView textView
    
    public EndpointsAsyncTask(Context context,TextView mtextView) {
        // TODO Auto-generated constructor stub
                this.context=context;
                this.textView=mtextView;
    }
    
            @Override
            protected String doInBackground(Pair<Context, String>... params) {
                if (myApiService == null) {  // Only do this once
                  /*  MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
                            new AndroidJsonFactory(), null)
                            // options for running against local devappserver
                            // - 10.0.2.2 is localhost's IP address in Android emulator
                            // - turn off compression when running against local devappserver
                            .setRootUrl("http://10.0.2.2:8080/_ah/api/")
                            .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                                @Override
                                public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
                                    abstractGoogleClientRequest.setDisableGZipContent(true);
                                }
                            });*/
    
                    MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
                            .setRootUrl("https://leafy-display-112017.appspot.com/_ah/api/");
                    // end options for devappserver
    
                    myApiService = builder.build();
                }
    
                context = params[0].first;
                String name = params[0].second;
    
                try {
                    return myApiService.sayHi(name).execute().getData();
                } catch (IOException e) {
                    return e.getMessage();
                }
            }
    
            @Override
            protected void onPostExecute(String result) {
    
                Toast.makeText(context, result, Toast.LENGTH_LONG).show();
                textView.setText(result);
            }
        }
    

    从你的 Activity 或 Fragment 调用 AsyncTask

    new EndpointsAsyncTask(context,yourTextView).execute(yourParams);
    

    【讨论】:

    • 乐于助人。快乐编码@Mrin
    【解决方案2】:

    在 EndpointsAsyncTask.java 中替换

     @Override
        protected void onPostExecute(String result) {
    
            Toast.makeText(context, result, Toast.LENGTH_LONG).show();
        }
    

     @Override
        protected void onPostExecute(String result) {
    
            GoogleAppEngActivity.getTextView().setText(result);
        }
    

    【讨论】:

      【解决方案3】:

      在 GoogleAppEngActivity 类中更改为:new EndpointsAsyncTask(tv1)

      并将下一个代码添加到EndpointsAsyncTask

      TextView view;
      public EndpointsAsyncTask(TextView tv) {
          view = tv;
      }
      

      并替换Toast.makeText(context, result, Toast.LENGTH_LONG).show();view.setText(result);

      【讨论】:

        【解决方案4】:

        我建议将 EndpointsAsyncTask 设置为您的活动的内部类。在 postExecute 中获取对 textView 的引用并在那里更新它。类似this

        【讨论】:

          【解决方案5】:

          理想情况下,属于 Activity 的 UI 元素应该在 Activity 本身中更改,其他任何地方都不能更改。尝试遵循演示模式。

          一个小例子: 1. 创建一个接口 - ActivityPresenter,其方法表示带有参数的事件作为视图更改所需的输入数据。一个例子是:

          void onServerResponse(ServerResponse resp);
          
          1. 让活动实现这个接口。也就是说,您可以定义当服务器响应到达时要在 Activity 中进行哪些 UI 更改。

          2. 当您从 Activity 调用服务/asynctask 为您异步执行某些任务时,请发送 Activity Presenter 引用。从您的服务/异步任务中调用presenter.onServerResponse(response)

          【讨论】:

            【解决方案6】:

            为此你可以使用回调接口:

            创建一个公共接口:

            public interface AsyncTaskResponse {
            
            void asyncTaskFinish(String output);
            }
            

            现在重写回调接口的方法并定义需要执行的操作,即设置 TextView 值。之后将其传递给异步任务类:

            package com.ontech.googleappengine;
            
                import android.content.Context;
                import android.support.v7.app.AppCompatActivity;
                import android.os.Bundle;
                import android.util.Pair;
                import android.view.Menu;
                import android.view.MenuItem;
                import android.view.View;
                import android.widget.Button;
                import android.widget.EditText;
                import android.widget.TextView;
            
                public class GoogleAppEngActivity extends AppCompatActivity {
            
                    Button btnAdd;
                    final TextView tv1;
                    //String val1,val2;
                    EditText edt1,edt2;
                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_google_app_eng);
            
            
                        edt1=(EditText)findViewById(R.id.edt1);
                        edt2=(EditText)findViewById(R.id.edt2);
                        tv1=(TextView)findViewById(R.id.tv1);
                        btnAdd =(Button)findViewById(R.id.btnAdd);
                        btnAdd.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
            
                                String temp = "";
                                temp = edt1.getText().toString();
                                temp += "+";
                                temp += edt2.getText().toString();
            
                                new EndpointsAsyncTask(new AsyncTaskResponse() {
                    @Override
                    public void asyncTaskFinish(String response) {
                        tv1.setText(response);
                    }
                };).execute(new Pair<Context, String>(GoogleAppEngActivity.this, temp));
                              //  tv1.setText( new EndpointsAsyncTask().);
                            }
                        });
            
                       // new EndpointsAsyncTask(new AsyncTaskResponse().execute(new Pair<Context, String>(this, "Manfred"));
                    }
            
                    public TextView getTextView(){
            
                        TextView txtView=(TextView)findViewById(R.id.tv1);
                        return txtView;
                    }
            
            
                }
            

            现在在异步任务类中调用回调接口方法并传递响应字符串来设置编辑文本值:

            package com.ontech.googleappengine;
            
            //package com.ontech.googleappengine;
            
            import android.content.Context;
            import android.os.AsyncTask;
            import android.text.Layout;
            import android.util.Pair;
            import android.view.LayoutInflater;
            import android.view.View;
            import android.widget.LinearLayout;
            import android.widget.TextView;
            import android.widget.Toast;
            
            import com.google.api.client.extensions.android.http.AndroidHttp;
            import com.google.api.client.extensions.android.json.AndroidJsonFactory;
            import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
            import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
            import com.ontech.myapplication.backend.myApi.MyApi;
            
            import java.io.IOException;
            
            /**
             * Created by on 05-11-2015.
             */
            public class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
                private static MyApi myApiService = null;
                private Context context;
                private AsyncTaskResponse asyncCallback;
                public EndpointsAsyncTask(AsyncTaskResponse asyncTaskResponse){
                      asyncCallback = asyncTaskResponse;
                }
                @Override
                protected String doInBackground(Pair<Context, String>... params) {
                    if (myApiService == null) {  // Only do this once
                      /*  MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
                                new AndroidJsonFactory(), null)
                                // options for running against local devappserver
                                // - 10.0.2.2 is localhost's IP address in Android emulator
                                // - turn off compression when running against local devappserver
                                .setRootUrl("http://10.0.2.2:8080/_ah/api/")
                                .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                                    @Override
                                    public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
                                        abstractGoogleClientRequest.setDisableGZipContent(true);
                                    }
                                });*/
            
                        MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
                                .setRootUrl("https://leafy-display-112017.appspot.com/_ah/api/");
                        // end options for devappserver
            
                        myApiService = builder.build();
                    }
            
                    context = params[0].first;
                    String name = params[0].second;
            
                    try {
                        return myApiService.sayHi(name).execute().getData();
                    } catch (IOException e) {
                        return e.getMessage();
                    }
                }
            
                @Override
                protected void onPostExecute(String result) {
            
                    //Toast.makeText(context, result, Toast.LENGTH_LONG).show();
                       asyncCallback.asyncTaskFinish(result); // call the method of callback interface
                }
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-09-09
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多