I am currently starting an Android app and want to build a list where each item occupies one single row. Right now I only have a TextView but will have more elements later.
I am having problems in placing one element per row since the TextViews just get placed one after the other, like this:
The layout for this is as follows:
<?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">
<TextView
android:id="@+id/twitterNumber"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="@dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" />
</LinearLayout>
The code for the RecyclerView is:
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView 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:id="@+id/list"
android:name="codehero.twitteralarmclock.ui.main.tweet.TweetsFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
app:layoutManager="LinearLayoutManager"
tools:context=".ui.main.tweet.TweetsFragment"
tools:listitem="@layout/fragment_tweets" />
I've tried changing the orientation of the LinearLayout, adding the maxLines and singleLine attributes to the TextView but nothing changed.
Thanks for you help in advance!
So it turns the Android Studio default FragmentList code will create a GridLayout if the list count is bigger than 1:
class TweetsFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_tweets_list, container, false)
// Set the adapter
if (view is RecyclerView) {
with(view) {
layoutManager = when {
columnCount <= 1 -> LinearLayoutManager(context)
else -> GridLayoutManager(context, columnCount)
}
adapter = TweetsViewAdapter(TwitterPlaceholderContent.ITEMS)
}
}
return view
}
}
The solution is to always create a LinearLayout inside the onCreateView method:
if (view is RecyclerView) {
with(view) {
layoutManager = LinearLayoutManager(context)
adapter = TweetsViewAdapter(TwitterPlaceholderContent.ITEMS)
}
}