【问题标题】:How to call a condition on a view?如何在视图上调用条件?
【发布时间】:2016-04-01 11:33:03
【问题描述】:

我在第一个活动中有两个活动,我有两个来自Location 和toLocation 的文本视图。单击 from 和 to 文本视图时,我正在调用下一个活动,其中我有一张地图,我选择了一个存储在字符串中并显示在文本视图中的位置。这个选择位置我想在第一个活动的位置文本视图 onClick 上显示第二个活动中的 useLocation 布局,基于选择哪个文本视图。如果 fromLocation 的 onClick 地址应显示在 fromLocation 文本视图上,而 toLocation 地址的 onClick 应显示在 toLocation 上。这将是第一个活动的 onResume 方法。

现在,当我第一次在 fromLocation 文本视图上单击地址时,我在两个文本视图中都获得了地址。

如何做到这一点..?

GoSendActivity(FirstActivity)

 public class GoSend extends AppCompatActivity implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {
    private LocationRequest mLocationRequest;

    private GoogleApiClient mGoogleApiClient;
    boolean mUpdatesRequested = false;
    private GoogleMap mGoogleMap;
    private MarkerOptions markerOptions;
    private LinearLayout ll;
    private TextView additionalContactFrom,additionalContactTo,txt_from,txt_to;

    private LinearLayout linearLayoutFrom,linearLayoutTo;
    private ImageView next;
    private Toolbar toolbar;
    private EditText locdetailsFrom,locdetailsTo,itemDetails;
    private Intent i;
    private LatLng currentLocation,curentpoint,center;
    private GPSTracker gps;
    double latitude,longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gosendlayout);

        setUI();

        int status = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(getBaseContext());

        if (status != ConnectionResult.SUCCESS) { // Google Play Services are
            // not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
                    requestCode);
            dialog.show();

        } else { // Google Play Services are available

            // Getting reference to the SupportMapFragment
            // Create a new global location parameters object
            mLocationRequest = LocationRequest.create();

            /*
             * Set the update interval
             */
            mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);

            // Use high accuracy
            mLocationRequest
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

            // Set the interval ceiling to one minute
            mLocationRequest
                    .setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);

            // Note that location updates are off until the user turns them on
            mUpdatesRequested = false;

            /*
             * Create a new location client, using the enclosing class to handle
             * callbacks.
             */
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API).addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();

            mGoogleApiClient.connect();

        }
    }

    public void setUI() {

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("COURIER");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        locdetailsFrom = (EditText) findViewById(R.id.editText_from_details);
        locdetailsFrom.setText(GoSendData.instance.getmFromLocationDetails());

        locdetailsTo = (EditText) findViewById(R.id.editText_to_details);
        locdetailsTo.setText(GoSendData.instance.getmToLocationDetails());

        itemDetails = (EditText) findViewById(R.id.editText_ItemDetail);

        txt_from = (TextView) findViewById(R.id.Text_from);
        txt_to = (TextView) findViewById(R.id.Text_to);
        additionalContactFrom = (TextView) findViewById(R.id.contactDetailsFrom);
        additionalContactTo = (TextView) findViewById(R.id.contactDetailsTo);
        linearLayoutFrom = (LinearLayout) findViewById(R.id.LinearLayoutFrom);
        linearLayoutTo = (LinearLayout) findViewById(R.id.LinearLayoutTo);
        next = (ImageView) findViewById(R.id.imageView_next);


        txt_from.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                i = new Intent(getApplicationContext(), PickLocationActivity.class);
             ///   GoSendData.instance.addressType=0;
                startActivity(i);
            }
        });

        txt_to.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                i = new Intent(getApplicationContext(), PickLocationActivity.class);
                //GoSendData.instance.addressType=1;
                startActivity(i);
            }
        });


        additionalContactFrom.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (linearLayoutFrom.getVisibility() == View.GONE) {

                    linearLayoutFrom.setVisibility(View.VISIBLE);

                } else {
                    linearLayoutFrom.setVisibility(View.GONE);

                }
            }
        });


        additionalContactTo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (linearLayoutTo.getVisibility() == View.GONE) {

                    linearLayoutTo.setVisibility(View.VISIBLE);

                } else {
                    linearLayoutTo.setVisibility(View.GONE);

                }
            }
        });

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                i = new Intent(getApplicationContext(), GoSendDetailsActivity.class);
                startActivity(i);
            }
        });



    }

    @Override
    public void onResume() {
        int LocationClick;
        super.onResume();  // Always call the superclass method first

            txt_from.setText(GoSendData.instance.mFromLocation);
            txt_to.setText(GoSendData.instance.mToLocation);

        }


    private void setupMap() {
        try {

            mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();

            // Enabling MyLocation in Google Map
            mGoogleMap.setMyLocationEnabled(true);
            mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
            mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
            mGoogleMap.getUiSettings().setCompassEnabled(true);
            mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
            mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);

            gps = new GPSTracker(this);

            gps.canGetLocation();

            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
            curentpoint = new LatLng(latitude, longitude);

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(curentpoint).zoom(19f).tilt(70).build();

            mGoogleMap.setMyLocationEnabled(true);
            mGoogleMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));


            mGoogleMap.addMarker(markerOptions);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnected(Bundle arg0) {
        // TODO Auto-generated method stub
        setupMap();

    }

          @Override
          public void onConnectionSuspended(int arg0) {
              // TODO Auto-generated method stub

          }

}

ChooseFromMapActivity(第二个活动)

public class ChooseFromMapActivity extends AppCompatActivity implements
        LocationListener, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private LocationRequest mLocationRequest;
    GoogleMap mGoogleMap;

    private GoogleApiClient mGoogleApiClient;
    boolean mUpdatesRequested = false;
    private LatLng center,curentpoint;
    private LinearLayout markerLayout,useLocation;
    private Geocoder geocoder;
    private List<Address> addresses;
    private TextView Address;
    double latitude,longitude;
    private GPSTracker gps;

    Intent intent;
    double x, y;
    StringBuilder str;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_from_map);


        SetUpUI();

        int status = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(getBaseContext());

        if (status != ConnectionResult.SUCCESS) { // Google Play Services are
            // not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
                    requestCode);
            dialog.show();

        } else { // Google Play Services are available

            // Getting reference to the SupportMapFragment
            // Create a new global location parameters object
            mLocationRequest = LocationRequest.create();

            /*
             * Set the update interval
             */
            mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);

            // Use high accuracy
            mLocationRequest
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

            // Set the interval ceiling to one minute
            mLocationRequest
                    .setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);

            // Note that location updates are off until the user turns them on
            mUpdatesRequested = false;

            /*
             * Create a new location client, using the enclosing class to handle
             * callbacks.
             */
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API).addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();

            mGoogleApiClient.connect();
        }

        useLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                intent = new Intent(ChooseFromMapActivity.this,GoSend.class);

                startActivity(intent);

            }
        });
    }

        private void SetUpUI(){


            Address = (TextView) findViewById(R.id.textShowAddress);
            markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
            useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);

            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            toolbar.setTitle("CHOOSE FROM MAP");
            setSupportActionBar(toolbar);

            toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);

            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });


            if (Build.VERSION.SDK_INT >= 21) {
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
            }


}
    private void stupMap() {
        try {

            mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();

            // Enabling MyLocation in Google Map
            mGoogleMap.setMyLocationEnabled(true);
            mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
            mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
            mGoogleMap.getUiSettings().setCompassEnabled(true);
            mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
            mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);

            gps = new GPSTracker(this);

            gps.canGetLocation();

            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
            curentpoint = new LatLng(latitude, longitude);

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(curentpoint).zoom(19f).tilt(70).build();

            mGoogleMap.setMyLocationEnabled(true);
            mGoogleMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));


            mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {

                @Override
                public void onCameraChange(CameraPosition arg0) {
                    // TODO Auto-generated method stub
                    center = mGoogleMap.getCameraPosition().target;

                    mGoogleMap.clear();
                    markerLayout.setVisibility(View.VISIBLE);

                    try {
                        new GetLocationAsync(center.latitude, center.longitude)
                                .execute();

                    } catch (Exception e) {
                    }
                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnected(Bundle arg0) {
        // TODO Auto-generated method stub
        stupMap();

    }

    private class GetLocationAsync extends AsyncTask<String, Void, String> {

        // boolean duplicateResponse;


        public GetLocationAsync(double latitude, double longitude) {
            // TODO Auto-generated constructor stub

            x = latitude;
            y = longitude;
        }

        @Override
        protected String doInBackground(String... params) {

            try {
                geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
                addresses = geocoder.getFromLocation(x, y, 1);
                str = new StringBuilder();
                if (Geocoder.isPresent()) {

                    if ((addresses != null) && (addresses.size() > 0)) {
                        Address returnAddress = addresses.get(0);

                        String localityString = returnAddress.getLocality();
                        String city = returnAddress.getCountryName();
                        String region_code = returnAddress.getCountryCode();
                        String zipcode = returnAddress.getPostalCode();

                        str.append(localityString + "");
                        str.append(city + "" + region_code + "");
                        str.append(zipcode + "");



                    }
                } else {
                }
            } catch (IOException e) {
                Log.e("tag", e.getMessage());
            }
            return null;

        }

        @Override
        protected void onPostExecute(String result) {
            try {
                Address.setText(addresses.get(0).getAddressLine(0)
                        + addresses.get(0).getAddressLine(1) + " ");
                GoSendData.instance.mFromLocation=addresses.get(0).getAddressLine(0)
                        + addresses.get(0).getAddressLine(1) + " ";
                GoSendData.instance.mToLocation=addresses.get(0).getAddressLine(0)+addresses.get(0).getAddressLine(1)+"";

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        // TODO Auto-generated method stub

    }
}

【问题讨论】:

    标签: java android view onclick conditional-statements


    【解决方案1】:

    如果我理解正确..您应该以startActivityForResult 启动第二个活动,并在地图上选择位置后将其返回。 第一个活动现在应该来自方法onActivityResult

    http://developer.android.com/training/basics/intents/result.html

    1. 点击第一个 textview 使用 requestcode 启动第二个活动
    2. 选择位置后的第二个活动以 setResult 结束,您存储所选位置的位置
    3. 在第一个活动的onActivityResult 中获取结果并将其设置为textView

    第二个文本视图相同。对不同的 textview 使用不同的请求代码,您应该检查 onActivityResult 以确定在第二个活动中选择了哪些 textView 数据

    【讨论】:

    • 感谢您的回复.. 我已经阅读并尝试这样做.. 这是我在第一个活动中所做的 :::: @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // 检查请求代码是否与此处传递的相同 2 if(requestCode==1) { txt_from.setText(GoSendData.instance.mFromLocation); } else if(requestCode==2){ txt_to.setText(GoSendData.instance.mToLocation); } }
    • 我对如何从第二个活动返回结果感到困惑。因为我必须根据单击的文本视图传递两个结果。怎么办? @aelimill
    • 使用 setResult(some_data) 并完成第二个活动。不是 GoSendData 上的静态字段。正如我所理解的,第二个活动只是获取坐标,您不需要知道按下了哪个文本视图。您只需将选定的坐标传递给数据并完成此活动。
    • 实际上我之间还有另一个活动。你能通过代码解释一下吗?@aelimill
    猜你喜欢
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    • 2014-05-30
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多