我有一个矩形,我想把它放在里面,一个图像和一个文本。设计类似于图像的设计,但未显示图像和文本。没有必要使用矩形,但是我这样做是因为我想实现它,如果我将不透明度设置为0,矩形将被隐藏或者如果我将不透明度设置为1,它们将出现。 我正在使用SVG元素。我需要将其作为SVG
我该如何调整?
https://jsfiddle.net/gqy67quc/
body = d3.select('body')
svg = body.append('svg').attr('height', 600).attr('width', 200)
rect = svg.append('rect').attr('width', 150)
.attr('height', 100)
.attr('x', 40)
.attr('y', 100)
.style('fill', 'white')
.attr('stroke', 'black')
.append('text').text('This is some information about whatever')
.attr('x', 50)
.attr('y', 150)
.attr('fill', 'black')
.append('image')
.attr('width', 100)
.attr('height', 100)
.attr('xlink:href', 'https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png')
答案 0 :(得分:0)
在SVG中,<rect>
元素不是容器:您无法将文本和图像附加到矩形。
因此,将元素附加为单独的选择,或者,如果要将它们相对于给定坐标放置,请将它们附加到<g>
元素。
这是一个演示:
var body = d3.select('body')
var svg = body.append('svg').attr('height', 200).attr('width', 500);
var group = svg.append("g")
.attr("transform", "translate(40,40)");
var rect = group.append('rect')
.attr('width', 300)
.attr('height', 100)
.style('fill', 'white')
.attr('stroke', 'black');
var text = group.append('text').text('This is some information')
.attr('x', 120)
.attr('y', 30)
.append("tspan")
.attr('x', 120)
.attr('dy', '2em')
.text('about whatever')
var image = group.append('image')
.attr("x", 4)
.attr('width', 100)
.attr('height', 100)
.attr('xlink:href', 'https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png')
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
PS:始终在变量之前使用var
(或let
或const
...),否则它们将是全球。
答案 1 :(得分:-1)
<div class="card">
<div class="cardImg"></div>
<div class="cardContent">
<h2>Card Content</h2>
<p>Something for the content</p>
</div>
</div>
.card
有一个外部div,其中.cardImg
类包含两个较小的div .cardContent
和.cardImg
。 .card
的背景设置为您使用的网址。可以通过设置public class PlacesAutoCompleteAdapter
extends RecyclerView.Adapter<PlacesAutoCompleteAdapter.PredictionHolder> implements Filterable {
private static final String TAG = "PlacesAutoCompleteAdapter";
private ArrayList<PlaceAutocomplete> mResultList;
private GoogleApiClient mGoogleApiClient;
private LatLngBounds mBounds;
private AutocompleteFilter mPlaceFilter;
private Context mContext;
private int layout;
public PlacesAutoCompleteAdapter(Context context, int resource, GoogleApiClient googleApiClient,
LatLngBounds bounds, AutocompleteFilter filter) {
mContext = context;
layout = resource;
mGoogleApiClient = googleApiClient;
mBounds = bounds;
mPlaceFilter = filter;
}
public void setBounds(LatLngBounds bounds) {
mBounds = bounds;
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null) {
mResultList = getAutocomplete(constraint);
if (mResultList != null) {
results.values = mResultList;
results.count = mResultList.size();
}
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
}
}
};
return filter;
}
private ArrayList<PlaceAutocomplete> getAutocomplete(CharSequence constraint) {
if (mGoogleApiClient.isConnected()) {
Log.i("", "Starting autocomplete query for: " + constraint);
PendingResult<AutocompletePredictionBuffer> results =
Places.GeoDataApi
.getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
mBounds, mPlaceFilter);
thread. Block and wait for at most 60s
AutocompletePredictionBuffer autocompletePredictions = results
.await(60, TimeUnit.SECONDS);
final Status status = autocompletePredictions.getStatus();
if (!status.isSuccess()) {
Toast.makeText(mContext, "Error contacting API: " + status.toString(),
Toast.LENGTH_SHORT).show();
Log.e("", "Error getting autocomplete prediction API call: " + status.toString());
autocompletePredictions.release();
return null;
}
Log.i("", "Query completed. Received " + autocompletePredictions.getCount()
+ " predictions.");
Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());
while (iterator.hasNext()) {
AutocompletePrediction prediction = iterator.next();
resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),
prediction.getDescription()));
}
autocompletePredictions.release();
return resultList;
}
Log.e("", "Google API client is not connected for autocomplete query.");
return null;
}
@Override
public PredictionHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View convertView = layoutInflater.inflate(layout, viewGroup, false);
PredictionHolder mPredictionHolder = new PredictionHolder(convertView);
return mPredictionHolder;
}
@Override
public void onBindViewHolder(final PredictionHolder mPredictionHolder, final int i) {
}
@Override
public int getItemCount() {
if(mResultList != null)
return mResultList.size();
else
return 0;
}
public PlaceAutocomplete getItem(int position) {
return mResultList.get(position);
}
public class PredictionHolder extends RecyclerView.ViewHolder {
private TextView mPrediction;
private RelativeLayout mRow;
public PredictionHolder(View itemView) {
super(itemView);
mPrediction = (TextView) itemView.findViewById(R.id.address);
mRow=(RelativeLayout)itemView.findViewById(R.id.predictedRow);
}
}
public void clear() {
mResultList.clear();
notifyDataSetChanged();
}
public class PlaceAutocomplete {
public CharSequence placeId;
public CharSequence description;
PlaceAutocomplete(CharSequence placeId, CharSequence description) {
this.placeId = placeId;
this.description = description;
}
@Override
public String toString() {
return description.toString();
}
}
}
public class PlacesAutoCompleteActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener, OnMapReadyCallback,
LocationListener {
protected GoogleApiClient mGoogleApiClient;
private boolean executeOnStart = false;
LocationRequest mLocationRequest;
MarkerOptions markerOptions;
private static final LatLngBounds BOUNDS_INDIA = new LatLngBounds(
new LatLng(-0, 0), new LatLng(0, 0));
private GoogleMap mMap;
Location mLastLocation;
Marker mCurrLocationMarker;
private String mapAddress = null;
private StringBuilder sb = null;
private EditText mAutocompleteView;
private Geocoder geocoder;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private PlacesAutoCompleteAdapter mAutoCompleteAdapter;
PlacesAutoCompleteAdapter.PlaceAutocomplete item;
String featureName, locality, countryName;
String placeId;
ImageView delete;
private LatLng pos;
static boolean invalidLocation = false; // this value confirms whether we are able to deliver to users location
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
buildGoogleApiClient();
setContentView(R.layout.activity_search);
mAutocompleteView = (EditText) findViewById(R.id.autocomplete_places);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(PlacesAutoCompleteActivity.this);
geocoder = new Geocoder(this, Locale.getDefault());
markerOptions = new MarkerOptions();
buildGoogleApiClient();
delete = (ImageView) findViewById(R.id.cross);
mAutoCompleteAdapter = new PlacesAutoCompleteAdapter(this, R.layout.searchview_adapter,
mGoogleApiClient, BOUNDS_INDIA, null);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mLinearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mRecyclerView.setAdapter(mAutoCompleteAdapter);
delete.setOnClickListener(this);
mAutocompleteView.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (!s.toString().equals("") && mGoogleApiClient.isConnected()) {
mAutoCompleteAdapter.getFilter().filter(s.toString());
} else if (!mGoogleApiClient.isConnected()) {
Toast.makeText(getApplicationContext(), Constants.API_NOT_CONNECTED, Toast.LENGTH_SHORT).show();
Log.e(Constants.PlacesTag, Constants.API_NOT_CONNECTED);
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
item = mAutoCompleteAdapter.getItem(position);
placeId = String.valueOf(item.placeId);
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(PlaceBuffer places) {
if (places.getCount() == 1) {
mAutoCompleteAdapter.clear();
mAutocompleteView.setText("");
String country = "";
try {
List<Address> addresses = geocoder.getFromLocation(places.get(0).getLatLng().latitude,
places.get(0).getLatLng().longitude, 1);
sb = new StringBuilder();
if (addresses.size() > 0) {
android.location.Address address = addresses.get(0);
featureName = address.getFeatureName();
locality = address.getLocality();
countryName = address.getCountryName();
Log.d("featureName ", featureName + "||" +
locality +"||" + countryName);
if (featureName == null) {
mapAddress = address.getLocality() + " " + address.getCountryName();
} else if (locality == null) {
mapAddress = address.getFeatureName() + ", " + address.getCountryName();
} else if (countryName == null) {
mapAddress = address.getFeatureName() + ", " + address.getLocality();
} else {
mapAddress = address.getFeatureName() + ", " + address.getLocality() + " " + address.getCountryName();
country = address.getCountryName();
Log.d("counttryy", "sasa"+country);
}
}
Log.d("mpaddress", "kaka "+mapAddress + "||" + country);
} catch (IOException e) {
e.printStackTrace();
}
//Do the things here on Click.....
Toast.makeText(getApplicationContext(), "Hello {}" +countryName+"{}"+featureName+"{}"+"{}"+ String.valueOf(places.get(0).getLatLng()), Toast.LENGTH_SHORT).show();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(places.get(0).getLatLng()) // Sets the center of the map to Mountain View
.zoom(12) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.addMarker(new MarkerOptions().position(places.get(0).getLatLng())
.title("My Location"));
mMap.setTrafficEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} else {
Toast.makeText(getApplicationContext(), Constants.SOMETHING_WENT_WRONG, Toast.LENGTH_SHORT).show();
}
}
});
Log.i("TAG", "Clicked: " + item.description);
Log.i("TAG", "Called getPlaceById to get Place details for " + item.placeId);
}
})
);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(getApplicationContext(), "YOOOOOO", Toast.LENGTH_SHORT).show();
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
LatLng latLng = null;
final Double lat = location.getLatitude();
final Double lng = location.getLongitude();
Log.d("LATLANG", lat + "|" + lng);
LatLng latLng2 = new LatLng(lat, lng);
MarkerOptions markerOptions2 = new MarkerOptions();
markerOptions2.position(latLng);
markerOptions2.title("Current Positionn");
markerOptions2.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng2));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
sb = new StringBuilder();
if (addresses.size() > 0) {
android.location.Address address = addresses.get(0);
String featureName = address.getFeatureName();
String locality = address.getLocality();
String countryName = address.getCountryName();
System.out.println("featureName " + featureName + "||" + locality +"||" + countryName);
if (featureName == null) {
mapAddress = address.getLocality() + " " + address.getCountryName();
} else if (locality == null) {
mapAddress = address.getFeatureName() + ", " + address.getCountryName();
} else if (countryName == null) {
mapAddress = address.getFeatureName() + ", " + address.getLocality();
} else {
mapAddress = address.getFeatureName() + ", " + address.getLocality() + " " + address.getCountryName();
}
}
System.out.println("mpaddress " + mapAddress + "||" );
} catch (IOException e) {
e.printStackTrace();
}
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latlng) {
}
});
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnectionSuspended(int i) {
Log.v("Google API Callback", "Connection Suspended");
Log.v("Code", String.valueOf(i));
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.v("Google API Callback","Connection Failed");
Log.v("Error Code", String.valueOf(connectionResult.getErrorCode()));
Toast.makeText(this, Constants.API_NOT_CONNECTED, Toast.LENGTH_SHORT).show();
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Log.d("permission","permission");
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
Log.d("permission2","permission2");
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (mGoogleApiClient.isConnected()){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
}
}
的不透明度来更改整张卡片的不透明度。