#android #android-layout #android-recyclerview #android-xml #recyclerview-layout
#Android #android-layout #android-recyclerview #android-xml #recyclerview-макет
Вопрос:
Я хотел создать представление, как показано ниже. это представление в горизонтальном режиме рециркуляции:
- у представления прозрачный фон.
- С помощью приведенного ниже кода я смог добиться вида, показанного на изображении.
- Созданный вид имеет белый фон
Ниже приведен исходный код для сгенерированного изображения, здесь я использовал макет координатора в качестве родительского макета и относительного макета, который содержит текст и значок плюса. Просмотр изображения для отображения значка человека. Заранее спасибо.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="280dp"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/sixteen_dp"
android:layout_marginEnd="@dimen/sixteen_dp"
android:background="@null">
<RelativeLayout
android:id="@ id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:background="@drawable/dotted_corner"
android:paddingBottom="16dp">
<TextView
android:id="@ id/add_user_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="68dp"
android:layout_marginBottom="8dp"
android:fontFamily="sans-serif"
android:text="@string/add_user_txt"
android:textColor="@android:color/black"
android:textSize="24sp" />
<ImageView
android:id="@ id/add_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/add_user_tv"
android:layout_centerHorizontal="true"
android:layout_marginBottom="@dimen/eight_dp"
android:gravity="center"
android:src="@drawable/icon_add_new_user"
tools:ignore="ContentDescription" />/>
</RelativeLayout>
<ImageView
android:id="@ id/civProfilePic"
android:layout_width="90dp"
android:layout_height="90dp"
android:background="@drawable/dotted_circle"
android:scaleType="centerInside"
android:src="@drawable/icon_user_profile_silhoutte_big"
app:layout_anchor="@id/relativeLayout"
app:layout_anchorGravity="top|center"
tools:ignore="ContentDescription" />
Комментарии:
1. И в чем вопрос / проблема?
2. В чем заключаются вопросы???
3. Вопрос не ясен
4. Приложите свои скриншоты макета. Добавьте оба скриншота того, что у вас есть, и того, что вы хотите. Это поможет вам получить более быстрый ответ. Если вы не проясните свой вопрос, он будет отклонен или закрыт без ответа. Кроме того, нет необходимости в относительном макете внутри макета координатора.
Ответ №1:
Я хотел создать представление, как показано ниже. это представление в горизонтальном режиме рециркуляции
я не вижу никакого образца RecyclerView
для вашего изображения, похоже, только ImageView
для выбора фотографии в хранилище Android.
.. который содержит текст и значок плюса. Вид изображения, отображающий значок человека.
Если вы хотите Horizontal RecyclerView
с двумя изображениями и одним текстом:
"@ id/civProfilePic"
"@ id/add_user"
"@ id/add_user_tv"
вы должны создать класс MyAdapter.class
и MyContain.class
и, пожалуйста, переименуйте ваш XML выше в my_content.xml
вот код, который вам нужен:
пожалуйста, обратите внимание, что этот код использует FirebaseFirestore
пожалуйста, добавьте это в свой build.gradle
dependencies {
// Firestore
implementation 'com.google.firebase:firebase-firestore:18.1.0'
implementation 'com.google.firebase:firebase-storage:16.1.0'
// Other Firebase
// don't forget add this in your Manifest.xml , <uses-permission android:name="android.permission.INTERNET" />
implementation 'com.google.firebase:firebase-auth:16.1.0'
implementation 'com.google.android.gms:play-services-auth:16.0.1'
// Third-party libraries
// circle image
implementation 'de.hdodenhof:circleimageview:2.2.0'
// cropper if you need cropper when pick image from android storage don't forget this in your Manifest <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> and <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
implementation 'com.theartofdev.edmodo:android-image-cropper:2.6.0'
// reducing size image
implementation 'com.github.bumptech.glide:glide:4.6.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1'
}
MyContain.class
public class MyContain {
private String civProfilePic;
private String add_user;
// need Empty contructor
public MyContain(){}
public MyContain(String civProfilePic, String add_user){
this.civProfilePic = civProfilePic;
this.add_user = add_user;
// don't enter add_user_tv because the Text should not has any getter method,
}
// get your image using this getter
public String getCivProfilePic() {return civProfilePic;}
public String getAddUserIcon() {return add_user;}
}
MyAdapter.class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public List<MyContent> contentList;
public Context context;
public MyContain(List<MyContent> contentList){
this.contentList = contentList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_profile_seen_dashboard, parent, false);
context = parent.getContext();
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.setIsRecyclable(false);
// get position of RecyclerView Items and getImage from MyContain class
String civProfilePic = contentList.get(position).getImage();
// set photo using String which contain http taken using getImage and load from firestore
holder.setProfilePhoto(civProfilePic);
// get position of RecyclerView Items and getAddUserIcon from MyContain class
String icon_add = contentList.get(position).getAddUserIcon();
// set icon using String which contain http taken using getAddUserIcon and load from firestore
holder.setIconAdd(icon_add);
}
@Override
public int getItemCount() {
return contentList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View mView;
private ImageView civProfilePic;
private ImageView add_user;
public ViewHolder(View itemView){
super(itemView);
mView = itemView;
}
public void setProfilePhoto(String image) {
civProfilePic = mView.findViewById(R.id.civProfilePic);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.icon_user_profile_silhoutte_big);
Glide.with(context).applyDefaultRequestOptions(requestOptions).load(image).into(civProfilePic);
}
public void setIcon(String icon) {
add_user = mView.findViewById(R.id.add_user);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.icon_add_new_user);
Glide.with(context).applyDefaultRequestOptions(requestOptions).load(icon).into(add_user);
}
}
где вы хотите отобразить представление recycler? Фрагмент или действие?
например, когда ваш RecyclerView находится внутри MainActivity.
MainActivity.class
public class MainActivity extends AppCompatActivity {
private RecyclerView myRecycler;
private List<MyContent> contentList;
private MyAdapter myAdapter;
private Boolean isFirstPageFirstLoad = true;
private MyContent myContent;
private FirebaseFirestore firestore;
private FirebaseAuth mAuth;
private DocumentSnapshot lastVisible;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
contentList = new ArrayList<>();
myRecycler = view.findViewById(R.id.my_recycler);
myAdapter = new MyAdapter(contentList);
//horizontal recycler
myRecycler.setLayoutManager(new LinearLayoutManager(container.getContext(), LinearLayoutManager.HORIZONTAL, false));
myRecycler.setAdapter(myAdapter);
}
@Override
public void onStart() {
super.onStart();
loadFirstQuery();
}
public void loadFirstQuery() {
contentList.clear();
if (firebaseAuth.getCurrentUser() != null) {
myRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// horizontal
Boolean reachRightSide = !recyclerView.canScrollHorizontally(-1);
// when recycler reach last right side
if (reachRightSide) {
loadMorePost();
}
}
});
// RETRIEVING PROFILE PHOTOS AND ICONS
Query firstQuery = firestore
.collection("ProfilePhoto")
.orderBy("timestamp", Query.Direction.DESCENDING)
.limit(5);
firstQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (isFirstPageFirstLoad) {
lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);
}
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
myContent = doc.getDocument().toObject(MyContent.class);
if (isFirstPageFirstLoad) {
contentList.add(myContent);
} else {
contentList.add(0, myContent);
}
// fire the event adapterSeen.notifyDataSetChanged();
}
}
isFirstPageFirstLoad = false;
}
});
}
}
public void loadMorePost() {
Query nextQuery = firestore
.collection("ProfilePhoto")
.orderBy("timestamp", Query.Direction.DESCENDING)
.startAfter(lastVisible)
.limit(5);
nextQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (!documentSnapshots.isEmpty()) {
lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
myContent = doc.getDocument().toObject(MyContent.class);
contentList.add(myContent);
adapterSeen.notifyDataSetChanged();
}
}
}
}
});
}
не забудьте об этом, пожалуйста, используйте ограничение, с ним легко справиться
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="0dp"
android:layout_height="85dp"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="@drawable/line"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@ id/constraint">
<android.support.v7.widget.RecyclerView
android:id="@ id/my_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
app:layoutManager="android.support.v7.widget.LinearLayoutManager" />
</FrameLayout>
</android.support.constraint.ConstraintLayout>
еще раз
создать line.xml в drawable
это очень маленькая строка
<item>
<shape android:shape="rectangle">
<stroke
android:color="@color/line"
android:width="0.5dp" />
</shape>
</item>
в colors.xml
<color name="line">#f1ecec</color>
есть вопросы?