I have a file called row_list.xml
which holds the style of a CardView. This CardView is the root object of this xml file. I'm using this CardView
in a RecyclerView
in my activity_main
.
row_list.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
//codes>
<TextView
//codes />
</LinearLayout>
</androidx.cardview.widget.CardView>
In my MainActivity.java
I want to get the current height of this CardView, and then use this height for something. But when I call the code below, I got Attempt to invoke virtual method 'int androidx.cardview.widget.CardView.getHeight()' on a null object reference
.
MainActivity.java
public class MainActivity extends AppCompatActivity {
CardView cardView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cardView = findViewById(R.id.card_view);
System.out.println(cardView); //prints null
int height = cardView.getHeight(); //I get "null" object error
Why does cardView = findViewById(R.id.card_view)
returns null? How can I get the attributes of a CardView? Couldn't find a related question/solution on the web.
Edit after comment
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {layoutInflater = LayoutInflater.from(context);
View v = layoutInflater.inflate(R.layout.row_list,parent,false);
ViewHolder vh = new ViewHolder(v);
return vh;
}