I'm trying to show all the card views using recycler view in main activity. Although I did not set a huge margin between card views, my recycler view shows a huge space to print the next card view. please see my attached image, you'll understand what I'm trying to say. I've attached all the code here. Can you please advise how to solve this problem? Thank you.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
tools:listitem="#layout/note_card" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="50dp"
android:layout_marginRight="50dp"
android:layout_marginBottom="50dp"
android:clickable="true"
app:layout_constraintBottom_toBottomOf="#+id/recyclerView"
app:layout_constraintEnd_toEndOf="parent"
app:srcCompat="#drawable/add" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.cardview.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_margin="7dp"
app:cardBackgroundColor="#color/green"
app:cardCornerRadius="5dp"
app:cardElevation="5dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textViewTitleCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="TextView"
android:textSize="20sp" />
<TextView
android:id="#+id/textViewDescriptionCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_marginTop="16dp"
android:text="TextView"
android:textSize="16sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
package com.destructivepaul.quicknote;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.NoteHolder>{
private List<MyNote> myNoteList = new ArrayList<>();
// private Context context;
public void setMyNoteList(List<MyNote> myNoteList) {
this.myNoteList = myNoteList;
notifyDataSetChanged();
Log.i("info","note updated on adapter. note list size: "+myNoteList.size());
}
//public void setContext(Context context) {
// this.context = context;
// notifyDataSetChanged();
// Log.i("info","context updated on adapter");
// }
#NonNull
#Override
public NoteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.note_card
,parent,false);
return new NoteHolder(view);
}
#Override
public void onBindViewHolder(#NonNull NoteHolder holder, int position) {
MyNote myNote=myNoteList.get(position);
holder.textViewTitle.setText(myNote.getNote_title());
holder.textViewDescription.setText(myNote.getNote_description());
}
#Override
public int getItemCount() {
return myNoteList.size();
}
public class NoteHolder extends RecyclerView.ViewHolder{
private TextView textViewTitle, textViewDescription;
private CardView cardView;
public NoteHolder(#NonNull View itemView) {
super(itemView);
textViewTitle=itemView.findViewById(R.id.textViewTitleCard);
textViewDescription=itemView.findViewById(R.id.textViewDescriptionCard);
cardView=itemView.findViewById(R.id.cardView);
Log.i("info","card design found on adapter");
}
}
}
package com.destructivepaul.quicknote;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private FloatingActionButton fab;
private RecyclerView recyclerView;
private MyNoteViewModel myNoteViewModel;
private ActivityResultLauncher<Intent> activityResultLauncherForAddNote;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//resisterActivity
resisterActivityForAddNote();
fab=findViewById(R.id.fab);
recyclerView=findViewById(R.id.recyclerView);
NoteAdapter adapter=new NoteAdapter();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
Log.i("info","set the adapter");
myNoteViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication())
.create(MyNoteViewModel.class);
myNoteViewModel.getAllNotes().observe(MainActivity.this, new Observer<List<MyNote>>() {
#Override
public void onChanged(List<MyNote> myNotes) {
adapter.setMyNoteList(myNotes);
Log.i("info","adapter is called to update data");
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent =new Intent(MainActivity.this,CreateNoteActivity.class);
//resister activity launcher
activityResultLauncherForAddNote.launch(intent);
Log.i("info","called resister activity launcher on fab");
}
});
}
public void resisterActivityForAddNote(){
activityResultLauncherForAddNote=registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
, new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
int resultCode=result.getResultCode();
Intent data = result.getData();
if (resultCode==RESULT_OK && data !=null) {
String title = data.getStringExtra("title");
String description = data.getStringExtra("description");
String colorName = data.getStringExtra("color");
MyNote myNote = new MyNote(title, description, colorName);
Log.i("info", "new note created on activity result");
myNoteViewModel.insert(myNote);
Log.i("info", "note saved to database");
}
}
});
}
}
I've solved my problem by myself. The problem was on card layout design(parent layout height should be wrap content instead of match parent).
Related
fragment_leaderboard.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
android:orientation="vertical"
tools:context=".LeaderboardsFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
row_leaderboard.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"?
android:layout_height="wrap_content"
android:background="#color/cream">
<TextView
android:id="#+id/index"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:fontFamily="#font/gotham_bold"
android:text="#1"
android:textColor="#color/brown"
android:textSize="15sp"
app:layout_constraintBottom_toBottomOf="#+id/imageView7"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/imageView7" />
<ImageView
android:id="#+id/imageView7"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/index"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/menu_profile2" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:fontFamily="#font/gotham_bold"
android:text="Name of Winner"
android:textColor="#color/brown"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/imageView7"
app:layout_constraintStart_toEndOf="#+id/imageView7"
app:layout_constraintTop_toTopOf="#+id/imageView7" />
<TextView
android:id="#+id/coins"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:fontFamily="#font/gotham_bold"
android:text="1230"
android:textColor="#color/brown"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#+id/name" />
</android.constraintlayout.widget.ConstraintLayout>
LeaderBoardAdapter.java
package com.android.myquiz;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.myquiz.databinding.RowLeaderboardBinding;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
public class LeaderBoardAdapter extends
RecyclerView.Adapter<LeaderBoardAdapter.LeaderboardViewHolder> {
Context context;
ArrayList<User> users;
public LeaderBoardAdapter(Context context, ArrayList<User> users){
this.context = context;
this.users = users;
}
#NonNull
#NotNull
#Override
public LeaderboardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(context).inflate(R.layout.row_leaderboard, parent,
false);
return new LeaderboardViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull LeaderboardViewHolder holder, int position) {
User user = users.get(position);
holder.binding.name.setText(user.getName1());
holder.binding.coins.setText(String.valueOf(user.getCoins()));
holder.binding.index.setText(String.format("#%d", position+1));
}
#Override
public int getItemCount() {
return users.size();
}
public class LeaderboardViewHolder extends RecyclerView.ViewHolder {
TextView id;
RowLeaderboardBinding binding;
public LeaderboardViewHolder(#NonNull View itemView) {
super(itemView);
binding = RowLeaderboardBinding.bind(itemView);
}
}
}
LeaderboardFragments.java
package com.android.myquiz;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.myquiz.databinding.FragmentLeaderboardsBinding;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
import org.w3c.dom.Document;
import java.util.ArrayList;
public class LeaderboardsFragment extends Fragment {
public LeaderboardsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
FragmentLeaderboardsBinding binding;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
// Inflate the layout for this fragment
binding = FragmentLeaderboardsBinding.inflate(inflater, container,false);
FirebaseFirestore database = FirebaseFirestore.getInstance();
final ArrayList<User> users = new ArrayList<>();
final LeaderBoardAdapter adapter = new LeaderBoardAdapter(getContext(), users);
binding.recyclerView.setAdapter(adapter);
binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
database.collection("users")
.orderBy("coins", Query.Direction.DESCENDING).get().addOnSuccessListener(new
OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (DocumentSnapshot snapshot : queryDocumentSnapshots){
User user = snapshot.toObject(User.class);
users.add(user);
}
adapter.notifyDataSetChanged();
}
});
return binding.getRoot();
}
}
this is my code I want to retrieve data from the firebase real-time database in recyclerView in fragments.
Okay, so looks like you are able to fetch the data from firebase, but are making a mistake in setting the data.
When you are calling adapter.notifyDataSetChanged(), you need to take care that you are passing the new users list, to the adapter.
You need to create a method inside your adapter class,
public void setUsersList(ArrayList<User> users) {
this.users = users;
notifyDatasetChanged();
}
and call it inside your fragment like, adapter.setUsersList(users), instead of calling adapter.notifyDataSetChanged().
I fetch data from database and put it to RecyclerView. My database arrives 4 items I see it with log debug then I send it to my adapter. However I see only first item on my screen.
my adapter ListArticleAdapter
package uz.sherdevs.alishernavoiy.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import uz.sherdevs.alishernavoiy.R;
import uz.sherdevs.alishernavoiy.model.Article;
public class ListArticleAdapter extends RecyclerView.Adapter<ListArticleAdapter.MyViewHolder> {
private Context context;
private List<Article> articleList;
public ListArticleAdapter(Context context, List<Article> articleList) {
this.context = context;
this.articleList = articleList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.item_list, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.tv_title.setText(articleList.get(position).getTitle());
}
#Override
public int getItemCount() {
// Log.d("list", "" + articleList.size());
return articleList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_title;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tv_title = itemView.findViewById(R.id.article_title);
}
}
}
MainActivity
package uz.sherdevs.alishernavoiy;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import java.util.List;
import uz.sherdevs.alishernavoiy.adapter.ListArticleAdapter;
import uz.sherdevs.alishernavoiy.database.SQLiteDBHelper;
import uz.sherdevs.alishernavoiy.model.Article;
public class MainActivity extends AppCompatActivity {
private RecyclerView articleRecyclerView;
private ListArticleAdapter adapter;
private List<Article> articleList;
private SQLiteDBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
articleRecyclerView = (RecyclerView)findViewById(R.id.articles_recyclerview);
dbHelper = new SQLiteDBHelper(this);
articleList = dbHelper.getArticles();
// for (Article article : articleList) {
// Log.d("list", article.getTitle());
// }
articleRecyclerView.setHasFixedSize(true);
adapter = new ListArticleAdapter(this, articleList);
// Log.d("list", articleList.toString());
articleRecyclerView.setAdapter(adapter);
articleRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#drawable/background_icon"
>
<ImageView
android:src="#drawable/background_regtangle_green"
android:scaleType="centerCrop"
android:id="#+id/circle_background"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHeight_percent="0.3"
app:layout_constraintWidth_percent="1"
app:layout_constraintVertical_bias="0"
/>
<TextView
android:text="Dostonlar"
android:textColor="#FFDF6A"
android:textSize="60sp"
android:textStyle="bold"
android:gravity="center"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="#id/circle_background"
app:layout_constraintLeft_toLeftOf="#id/circle_background"
app:layout_constraintRight_toRightOf="#id/circle_background"
app:layout_constraintBottom_toBottomOf="#id/circle_background"
app:layout_constraintHeight_percent="0.1"
app:layout_constraintVertical_bias="0.3"
android:fontFamily="#font/myfont"
/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/articles_recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="?attr/actionBarSize">
</androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
item_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="12dp">
<androidx.cardview.widget.CardView
android:id="#+id/cardview1"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHeight_percent="0.15"
app:layout_constraintWidth_percent="0.8"
app:cardCornerRadius="20dp"
app:layout_constraintVertical_bias="0.23"
app:cardElevation="20dp"
>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/article_title"
android:textSize="45sp"
android:textStyle="bold"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHeight_percent="0.6"
android:gravity="center"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
I got 4 Objects from my database with command
articleList = dbHelper.getArticles();
However I see only first one on the screen.
Moreover as you see I loged in my adapter
#Override
public int getItemCount() {
// Log.d("list", "" + articleList.size());
return articleList.size();
}
That size also shows 4.
In item_list.xml, change android:layout_height="match_parent" with android:layout_height="wrap_content"
I am making an android app and I want to show all videos in the downloads directory, using a Recyclerview into the activity.
So far, I have tried the code below. It does not show any errors but when I switch to the activity in which the files are supposed to appear, all I see is a blank screen.
Downloads.java(The activity)
package com.example.singleactivity;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
#RequiresApi(api = 30)
public class Downloads extends AppCompatActivity {
File downloads_path = new File(Environment.DIRECTORY_DOWNLOADS);
public static ArrayList<File> allmedialist = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_downloads);
load_directory_files(downloads_path);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(this);
recyclerView.setAdapter(recyclerViewAdapter);
}
public static void load_directory_files(File download_path){
File[] filelist = download_path.listFiles();
if(filelist != null && filelist.length > 0){
for(File file:filelist){
if(file.isDirectory()){
load_directory_files(file);
}
else{
String name = file.getName().toLowerCase();
if(name.endsWith(".mp4")){
allmedialist.add(file);
break;
}
}
}
}
}
}
RecyclerView Class
package com.example.singleactivity;
import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mcontext;
RecyclerViewAdapter(Context mcontext){
this.mcontext = mcontext;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.files_list,parent,false);
return new FileLayoutHolder(view);
}
#RequiresApi(api = 30)
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
((FileLayoutHolder)holder).title.setText(Downloads.allmedialist.get(position).getName());
Uri uri = Uri.fromFile(Downloads.allmedialist.get(position));
Glide.with(mcontext).load(uri).thumbnail(0.1f).into(((FileLayoutHolder)holder).thumbnail);
}
#RequiresApi(api = 30)
#Override
public int getItemCount() {
return Downloads.allmedialist.size();
}
static class FileLayoutHolder extends RecyclerView.ViewHolder{
ImageView thumbnail;
TextView title;
ImageButton ic_more_btn;
public FileLayoutHolder(#NonNull View itemView) {
super(itemView);
thumbnail = itemView.findViewById(R.id.thumbnail);
title = itemView.findViewById(R.id.videotitle);
ic_more_btn = itemView.findViewById(R.id.ic_more_btn);
}
}
}
activity_downloads.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="match_parent"
android:layout_height="match_parent"
tools:context=".Downloads">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerView"/>
</androidx.constraintlayout.widget.ConstraintLayout>
file_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<ImageView
android:id="#+id/thumbnail"
android:layout_width="110dp"
android:layout_height="65dp"/>
<TextView
android:id="#+id/videotitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1" />
<ImageButton
android:id="#+id/ic_more_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_more"
android:layout_gravity="center"
android:paddingTop="20dp"
android:paddingBottom="20dp"
android:paddingRight="2dp"
android:paddingLeft="5dp"
android:paddingEnd="2dp"
android:paddingStart="5dp"/>
</LinearLayout>
How can I get the desired result?
The fragment only displays one cardview when I am trying to retrieve it from the news API.
Here is the code.
Main Activity
package com.manish.newapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create an instance of the tab layout from the view.
TabLayout tabLayout = findViewById(R.id.tab_layout);
// Set the text for each tab.
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label1));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label2));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label3));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label4));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label5));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label6));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label7));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label8));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label9));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label10));
// Set the tabs to scroll through the entire layout.
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
// Use PagerAdapter to manage page views in fragments.
// Each page is represented by its own fragment.
final ViewPager viewPager = findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
// Setting a listener for clicks.
viewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new
TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
TabNews Fragment
package com.manish.newapp.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.manish.newapp.Adapter;
import com.manish.newapp.ApiClient;
import com.manish.newapp.Models.Articles;
import com.manish.newapp.Models.Headlines;
import com.manish.newapp.Models.Source;
import com.manish.newapp.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class TabNews1 extends Fragment {
View v;
RecyclerView recyclerView;
final String API_KEY = "5a1ad719eee94e7ba60d19b51f4ff159";
String sources = "bbc-news";
Adapter adapter;
List<Articles> articles = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// String country = getCountry();
// retrieveJson(country,API_KEY);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v= inflater.inflate(R.layout.fragment_tab_news1, container, false);
recyclerView = (RecyclerView)v.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
String country = getCountry();
retrieveJson(country,API_KEY);
// retrieveJson(sources,API_KEY);
// Inflate the layout for this fragment
return v;
}
public void retrieveJson(String country, String apiKey){
Call<Headlines> call = ApiClient.getInstance().getApi().getHeadlines(country,apiKey);
call.enqueue(new Callback<Headlines>() {
#Override
public void onResponse(Call<Headlines> call, Response<Headlines> response) {
if (response.isSuccessful() && response.body().getArticles() != null){
articles.clear();
articles = response.body().getArticles();
adapter = new Adapter(getContext(),articles);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<Headlines> call, Throwable t) {
Toast.makeText(getContext(), t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public String getCountry(){
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
}
adapter Class
package com.manish.newapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.manish.newapp.Models.Articles;
import com.squareup.picasso.Picasso;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
List<Articles> articles;
public Adapter(Context context, List<Articles> articles) {
this.context = context;
this.articles = articles;
}
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_recycler,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Adapter.ViewHolder holder, int position) {
Articles art = articles.get(position);
holder.txtTitle.setText(art.getTitle());
holder.txtDescription.setText(art.getDescription());
holder.txtDate.setText(art.getPublishedAt());
String imageUrl = art.getUrlToImage();
Picasso.with(context).load(imageUrl).into(holder.imageView);
}
#Override
public int getItemCount() {
return articles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txtTitle, txtDescription, txtDate, txtTime;
ImageView imageView;
CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
txtTitle = (TextView)itemView.findViewById(R.id.title_text);
txtDescription = (TextView)itemView.findViewById(R.id.desc);
txtTime = (TextView)itemView.findViewById(R.id.time);
txtDate = (TextView)itemView.findViewById(R.id.date);
imageView = (ImageView)itemView.findViewById(R.id.image_news);
cardView = (CardView)itemView.findViewById(R.id.cardView);
}
}
}
Pager Adapter class
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import com.manish.newapp.Fragments.TabNews1;
import com.manish.newapp.Fragments.TabNews10;
import com.manish.newapp.Fragments.TabNews2;
import com.manish.newapp.Fragments.TabNews3;
import com.manish.newapp.Fragments.TabNews4;
import com.manish.newapp.Fragments.TabNews5;
import com.manish.newapp.Fragments.TabNews6;
import com.manish.newapp.Fragments.TabNews7;
import com.manish.newapp.Fragments.TabNews8;
import com.manish.newapp.Fragments.TabNews9;
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(#NonNull FragmentManager fm,int NumOfTabs) {
super(fm, NumOfTabs);
this.mNumOfTabs = NumOfTabs;
}
#NonNull
/**
* Return the Fragment associated with a specified position.
*
* #param position
*/
#Override
public Fragment getItem(int position) {
switch (position){
case 0 : return new TabNews1();
case 1 : return new TabNews2();
case 2 : return new TabNews3();
case 3 : return new TabNews4();
case 4 : return new TabNews5();
case 5 : return new TabNews6();
case 6 : return new TabNews7();
case 7 : return new TabNews8();
case 8 : return new TabNews9();
case 9 : return new TabNews10();
default: return null;
}
}
/**
* Return the number of views available.
*/
#Override
public int getCount() {
return mNumOfTabs;
}
}
Here are my layout files.
item_recycler.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cardView"
android:layout_margin="16dp"
android:padding="10dp"
app:cardElevation="4dp"
app:cardCornerRadius="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/image_news"
android:src="#drawable/image"
android:scaleType="centerCrop"/>
<!-- <FrameLayout-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="wrap_content"-->
<!-- android:id="#+id/frame_layout"-->
<!-- android:layout_below="#+id/image_news"-->
<!-- android:padding="5dp">-->
<!-- <RelativeLayout-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="wrap_content">-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TITLE"
android:textSize="20dp"
android:layout_below="#+id/image_news"
android:textStyle="bold"
android:id="#+id/title_text"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/desc"
android:text="DESCRIPTION"
android:layout_marginTop="10dp"
android:textSize="14dp"
android:layout_below="#+id/title_text"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/time"
android:layout_below="#+id/desc"
android:text="TIME"
android:layout_marginTop="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/date"
android:layout_below="#+id/time"
android:text="DATE"
android:layout_marginTop="5dp"/>
<!-- </RelativeLayout>-->
<!-- </FrameLayout>-->
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
fragment_tab_news1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".Fragments.TabNews1"
android:background="#color/colorBackground">
<!-- TODO: Update blank fragment layout -->
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- <TextView-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="wrap_content"-->
<!-- android:text="BBC NEWS"-->
<!-- android:textStyle="bold"-->
<!-- android:textSize="17sp"-->
<!-- android:layout_marginLeft="16dp"-->
<!-- android:layout_marginRight="16dp"-->
<!-- android:layout_marginTop="10dp"-->
<!-- android:fontFamily="sans-serif-light"/>-->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
</androidx.core.widget.NestedScrollView>
</RelativeLayout>
Mainactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/relative_main"
android:padding="16dp"
>
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/toolbar"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<androidx.viewpager.widget.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
Please help me with this, I am unable to find whats wrong here.
I am trying to make Popup Dialog Comment Section.
In this Comment section i done almost all things but facing new problem.
Here i am using Dialog for Show and add new comment but when user click on Enter a Comment (Edittext). It gets hide under Keyboard. So it will be problematic for user to post new comment.
Here My Xml File :
Popup.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/dialog_bg"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/popup_rcv"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="bottom">
<EditText
android:id="#+id/new_comment_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Please enter Comment" />
<Button
android:id="#+id/comment_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
Thank you in Advance.
Try this
dialog_layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/popup_rcv"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:orientation="horizontal">
<EditText
android:id="#+id/new_comment_et"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Please enter Comment" />
<Button
android:id="#+id/comment_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
</LinearLayout>
Activity
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
public class HomeActivity extends AppCompatActivity {
RecyclerView additionalDataList;
ArrayList<String> arrayList = new ArrayList<>();
DataAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_layout);
Window window = dialog.getWindow();
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.CENTER);
dialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
EditText edtComment = dialog.findViewById(R.id.new_comment_et);
Button btnComment = dialog.findViewById(R.id.comment_btn);
additionalDataList = dialog.findViewById(R.id.popup_rcv);
additionalDataList.setLayoutManager(new LinearLayoutManager(this));
additionalDataList.setHasFixedSize(true);
addDataToList();
btnComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!TextUtils.isEmpty(edtComment.getText().toString().trim())) {
arrayList.add(0, edtComment.getText().toString().trim());
edtComment.setText("");
adapter.notifyDataSetChanged();
}
}
});
adapter = new DataAdapter(this, arrayList);
additionalDataList.setAdapter(adapter);
dialog.show();
}
private void addDataToList() {
for (int i = 0; i < 5; i++) {
arrayList.add("Comment :" + i);
}
}
}
DataAdapter
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
Context context;
ArrayList<String> arrayList = new ArrayList<>();
public DataAdapter(Context context, ArrayList<String> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.test, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(arrayList.get(position));
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
public ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.additionalInfoTitle);
}
}
}
OUTPUT