John
John

Reputation: 750

Dynamic TextView not displaying properly

I am generating some TextViews dynamically in a loop. They are being displayed but I am not able create gap among them. They shows up as one row instead of separate rows.

    <?xml version="1.0" encoding="utf-8"?>
    <ScrollView 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"
    android:fitsSystemWindows="true">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    >

        <LinearLayout

            android:id="@+id/ll"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="18dp"
            android:paddingRight="18dp"
            android:paddingTop="60dp"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:focusableInTouchMode="true"
            android:orientation="vertical">

        </LinearLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>

tviewlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/light"
    android:textAlignment="gravity"
    android:padding="10dp"
    android:layout_margin="10dp"
    android:textSize="20sp" />

Java Code

LinearLayout linearLayout =  (LinearLayout) binding.ll;
                for (int i=0; i<arrSplit.length; i++)
                {
                    TextView tv = (TextView)getLayoutInflater().inflate(R.layout.tviewlayout, null);
                    tv.setText(arrSplit[i]);
                    tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                    linearLayout.addView(tv);
                }

enter image description here

Upvotes: 3

Views: 340

Answers (2)

Zain
Zain

Reputation: 40820

I want to create gaps between each TextViews so that they appear separate. Now all are being covered by the blue background

You can add a margin in pixels to each of the TextViews:

LinearLayout linearLayout =  (LinearLayout) binding.ll;

for (int i=0; i<arrSplit.length; i++) {
    TextView tv = (TextView)getLayoutInflater().inflate(R.layout.tviewlayout, null);
    tv.setText(arrSplit[i]);
    tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tv.getLayoutParams();
    params.bottomMargin = (int) getPx(100); // adding 100dp gap between TextViews
    linearLayout.addView(tv);
}



/*
 * Convert dp value to pixel
 * */
private float getPx(float dp) {
    return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dp,
            getResources().getDisplayMetrics());
}

UPDATE

Can you show me how the same can be achieved with RecyclerView ?

Here is a demo:

main_activity.xml:

<?xml version="1.0" encoding="utf-8"?>

<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rvList"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" />

list_item.xml: contains a template for your TextView Use android:layout_marginBottom to add the desired margin between two successive TextViews

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tvColorName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="32dp"
    android:textSize="18sp" />

Adapter:

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.CustomViewHolder> {

    private List<String> mColors;

    // Constructor
    RecyclerAdapter(List<String> colors) {
        this.mColors = colors;
    }


    @NonNull
    @Override
    public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        View listItem = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item, parent, false);
        return new CustomViewHolder(listItem);
    }

    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
        String color = mColors.get(position);
        holder.tvColorName.setText(color);
    }

    @Override
    public int getItemCount() {
        return mColors.size();
    }


    class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {

        TextView tvColorName;

        CustomViewHolder(@NonNull View listItem) {
            super(listItem);
            // caching views
            tvColorName = listItem.findViewById(R.id.tvColorName);
        }

    }


}

Activity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Building RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // Building RecyclerAdapter
        RecyclerAdapter adapter = new RecyclerAdapter(this, getColors());
        recyclerView.setAdapter(adapter);

    }
    
    
    private ArrayList<String> getColors() {
        ArrayList<String> colors = new ArrayList<>();
        colors.add("Red");
        colors.add("White");
        colors.add("Green");
        colors.add("Purple");
        colors.add("Yellow");
        colors.add("Blue");
        colors.add("Black");
        colors.add("Brown");
        colors.add("Magenta");
        colors.add("Cyan");
        colors.add("Gray");
        colors.add("Orange");
        return colors;
    }
    
}

Upvotes: 1

Upendra Shah
Upendra Shah

Reputation: 2301

I suggest to use recylerview for this type of purpose. It is more efficeint and dynamic.The example is in Kotlin

<?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:id="@+id/consRideInfo"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/10dp"
    android:padding="@dimen/10dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/incActionBar">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rcvList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="0dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:itemCount="3"
        tools:listitem="@layout/row_item" />

</androidx.constraintlayout.widget.ConstraintLayout>

on Activity define adapter

 private var adapter: GeneralAdapter<DataModel, MainActivity>? = null
 private val list: ArrayList<DataModel> = ArrayList()

and in onCreate

 adapter = GeneralAdapter(R.layout.row_item, list, this)
 binding.rcvList.adapter = adapter

and also create Adapter for showing

class GeneralAdapter<D, F>(
    val layoutId: Int,
    private val arrayList: ArrayList<D>,
    val listener: F
) : RecyclerView.Adapter<GeneralAdapter.GeneralHolder<D, F>>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GeneralHolder<D, F> {
        val layoutInflater = LayoutInflater.from(parent.context)
        val binding: ViewDataBinding =
            DataBindingUtil.inflate(layoutInflater, layoutId, parent, false)

        return GeneralHolder(binding, listener)
    }

    override fun getItemCount(): Int = arrayList.size

    override fun onBindViewHolder(holder: GeneralHolder<D, F>, position: Int) {
        holder.bind(arrayList[position])
    }

    class GeneralHolder<D, F>(
        private val binding: ViewDataBinding,
        val listener: F
    ) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(data: D) {
            binding.setVariable(BR.item, data)
            binding.setVariable(BR.presenter, listener)
            binding.executePendingBindings()
        }
    }
}

Upvotes: 2

Related Questions