Create Textview’s dynamically

Asked

Viewed 785 times

4

I have a TextView and would like that instead of filling with a Arraylist, with all items in your setText, that it be created several times on the screen, with the respective items of this array, in each setText of each TextView.

Follows the code:

public class RideRequestActivity extends AppCompatActivity implements CommunityRequestView {

    private SessionManager user;
    private String departure;
    private String arrival;



    @BindView(R.id.request_email)
    TextView email;


    @BindView(R.id.request_name)
    TextView name;


    @BindView(R.id.request_photo)
    ImageView photo;


    @BindView(R.id.textView_first)
    TextView first;

    @BindView(R.id.textView_second)
    TextView second;

    @BindView(R.id.textView_third)
    TextView third;

    @BindView(R.id.button0)
    CheckBox button0;

    @BindView(R.id.button1)
    CheckBox button1;

    @BindView(R.id.button2)
    CheckBox button2;

    @BindView(R.id.button3)
    CheckBox button3;

    @BindView(R.id.button4)
    CheckBox button4;

    @BindView(R.id.button5)
    CheckBox button5;

    @BindView(R.id.send_offer_request)
    Button send_offer_request;

    @BindView(R.id.send_ask_request)
    Button send_ask_request;

    @BindView(R.id.txtInterests)
    TextView mListView;

    @BindView(R.id.img_favorite)
    ImageView imgFavorite;

    CommunityPresenter presenter;
    UserCommunity selectedUser;
    UsersMySQLiteHelper serviceDB;
    private List<UserCommunity> userInterest = new ArrayList<UserCommunity>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setEnterTransition(new Fade());
        }
        setContentView(R.layout.activity_ride_request);
        serviceDB = new UsersMySQLiteHelper(AppController.getInstance().getApplicationContext());

        ButterKnife.bind(this);
        presenter = new CommunityPresenter(this);


        first.setText(presenter.getDay(0));
        second.setText(presenter.getDay(1));
        third.setText(presenter.getDay(2));

        user = new SessionManager();

        selectedUser = CommunityService.i(getContext()).selectedUser;
        reloadView();

        send_offer_request.setOnClickListener(presenter.sendRequestOnClickListener(0));
        send_ask_request.setOnClickListener(presenter.sendRequestOnClickListener(1));
        imgFavorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(selectedUser.favorite == 0) {
                    selectedUser.favorite = 1;
                    imgFavorite.setImageResource(R.drawable.ic_star_black_on_48px);
                }else{
                    selectedUser.favorite = 0;
                    imgFavorite.setImageResource(R.drawable.ic_star_border_black_off_48px);
                }
                selectedUser.save(serviceDB, user.getLoggedUser().getCompany());
            }
        });

        populateInterests();
        getPoints();

        imgFavorite = (ImageView)findViewById(R.id.img_favorite);
        if (selectedUser.favorite == 0){
            imgFavorite.setImageResource(R.drawable.ic_star_border_black_off_48px);
        }else{
            imgFavorite.setImageResource(R.drawable.ic_star_black_on_48px);
        }




    }

    private void getPoints() {
    }

    private void populateInterests() {
        RequestManager.UsersInterests(selectedUser.id, new FutureCallback<String>() {
            @Override
            public void onCompleted(Exception e, String result) {
                if(e== null || result != null) {
                    UserCommunity user = new Gson().fromJson(new JsonParser().parse(result).getAsJsonObject().get("data").toString(),
                            UserCommunity.class);

                    selectedUser.interests = user.interests;
                    String name = "";
                    TextView txt_Interests = (TextView) findViewById(R.id.txtInterests);
                    for (UserCommunity.Interest interest: selectedUser.interests
                         ) {
                           name += interest.name + " ";
                           txt_Interests.setText(name);
                    }
                    String point = "";
                    TextView points = (TextView)findViewById(R.id.txt_Points);
                    selectedUser.points = user.points;
                    point = selectedUser.points + "\npontos";
                    points.setText(point);

                }
            }
        });

    }

XML:

<RelativeLayout
    android:id="@+id/relative_first"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <ImageView
        android:id="@+id/request_photo"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:src="@drawable/avatar5"
        android:transitionName="infoboxImage" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/request_photo"
        android:layout_weight="1">

        <ImageView
            android:id="@+id/img_favorite"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:src="@drawable/ic_star_border_black_off_48px" />

        <TextView
            android:id="@+id/request_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/img_favorite"
            android:padding="5dp"
            android:text="Abraao Barros Lacerda"
            android:textAppearance="@android:style/TextAppearance.Material.Display1"
            android:textSize="25sp"
            android:transitionName="infoboxName" />

        <TextView
            android:id="@+id/request_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/request_name"
            android:padding="5dp"
            android:text="[email protected]" />

        <ImageView
            android:id="@+id/img_points"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:layout_alignRight="@+id/request_name" />

        <TextView
            android:id="@+id/txt_Points"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignStart="@+id/img_points"
            android:layout_below="@+id/img_points"
            android:text="50.000 pontos" />

        <LinearLayout
            android:id="@+id/linear_interests"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/txt_Points"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/txtInterests"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="6dp"
                android:text="INTERESTS"
                android:textStyle="bold"
                android:background="@drawable/txt_border_circle"/>
        </LinearLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/linear_interests">

            <android.support.v7.widget.CardView
                android:id="@+id/card_1"
                android:layout_width="match_parent"
                android:layout_height="105dp"
                android:layout_marginTop="10dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/textView_first"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="0.03"
                        android:padding="10dp"
                        android:text="Segunda-feira"
                        android:textAppearance="@android:style/TextAppearance.Material.Small"
                        android:textSize="14sp" />

                    <CheckBox
                        android:id="@+id/button0"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="0.03"
                        android:text="Ida - 7:00" />

                    <CheckBox
                        android:id="@+id/button1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="0.03"
                        android:text="Volta -18:00" />

                </LinearLayout>
            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView
                android:id="@+id/card_2"
                android:layout_width="match_parent"
                android:layout_height="105dp"
                android:layout_below="@+id/card_1"
                android:layout_marginTop="10dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/textView_second"
                        android:layout_width="100dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:padding="10dp"
                        android:text="Quarta-Feira"
                        android:textAppearance="@android:style/TextAppearance.Material.Small" />

                    <CheckBox
                        android:id="@+id/button2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="Ida - 7:00" />

                    <CheckBox
                        android:id="@+id/button3"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="Volta -18:00" />


                </LinearLayout>
            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView
                android:id="@+id/card_3"
                android:layout_width="match_parent"
                android:layout_height="105dp"
                android:layout_below="@id/card_2"
                android:layout_marginTop="10dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/textView_third"
                        android:layout_width="100dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:padding="10dp"
                        android:text="Quinta-Feira"
                        android:textAppearance="@android:style/TextAppearance.Material.Small" />

                    <CheckBox
                        android:id="@+id/button4"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="Ida - 7:00" />

                    <CheckBox
                        android:id="@+id/button5"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="Volta -18:00" />


                </LinearLayout>
            </android.support.v7.widget.CardView>

            <Button
                android:id="@+id/send_offer_request"
                style="@style/ByndButtonStyle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_below="@+id/card_3"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"
                android:paddingTop="10dp"
                android:text="Oferecer carona" />

            <Button
                android:id="@+id/send_ask_request"
                style="@style/ByndButtonStyle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_below="@id/card_3"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"
                android:paddingTop="10dp"
                android:text="Pedir carona" />
        </RelativeLayout>


    </RelativeLayout>


</RelativeLayout>

Improvement to this question, which I put myself: How to fill Textview setText from an Arraylist?

  • Do not understand... has how to explain better what you mean by: "...instead of filling with an arraylist..."

  • @seamusd as in the previous question, I took all the items of the array and placed it in a setText of a textView on the screen. I would like each item of the array to be, separately in each setText of each created textView, dynamically on the screen. So that they are separated, in the layout and not separated by spaces as it is today. I was clearer?

  • Our friend’s answer below solves your problem. Try to implement it the way it showed.

3 answers

2


Follow an example:

XML:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:id="@+id/mContent"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></LinearLayout>
</ScrollView>

JAVA:

/**
 * Layout que irá receber os TextView
 */
LinearLayout mContent = LinearLayout.class.cast(findViewById(R.id.mContent));
/**
 * Lista de TextView que serão criados dinamicamente
 */
List<TextView> textos = new ArrayList<>();

// Ponteiroi 
int idPt = 1;
 for (UserCommunity.Interest interest: selectedUser.interest) {
    // Vamos criar a a instancia do TExtView
    final TextView txtItem = new TextView(this);  
    // Informamos um id 
    txtItem.setId( idPt );   
    idPt++;
    txtItem.setText(interest.name);
    // Vamos adicionar um Layout ao TextView 
    toggleButton.setLayoutParams(new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT));
    // Adicionamos no Linear Layout
    mContent.addView(toggleButton);
    // Adicionamos em uma lista para guarda a referencia, 
    // Caso precise manipular novamente os objetos
    textos.add(toggleButton);


}
  • Luiz Failed, the variable idPt is incorrect in the code, underlined in red, as an error. And I can’t find with this, the list texts.

  • You must use the this only if it forms a global variable (of the class). What error occurs with the variable idPt???

  • worked here, almost like your answer

  • It’s an example, then you adapt your need

  • Yeah, it was great!!!!!

1

You can try this way by defining a LinearLayout within the .xml:

JAVA

LinearLayout llayout = (LinearLayout) findViewById(R.id.linearLayout);

for (int i = 0; i<selectedUser.interests.size(); i++) {
    final TextView txtItem = new TextView(this);
    txtItem.setId(i);
    point = user.points.get(i).toString() + "\npontos";
    txtItem.setText(""+point);
    llayout.addView(txtItem);
}

XML

<LinearLayout
    android:id="@+id/llayout"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></LinearLayout>
  • Thank you very much!

  • @Henriquemendes has solved his problem or needs something else?

  • Got, thank you very much! I put the answer as wanted

0

Exactly as I resolved, according to the responses in the post:

private void populateInterests() {
    RequestManager.UsersInterests(selectedUser.id, new FutureCallback<String>() {
        @Override
        public void onCompleted(Exception e, String result) {
            if (e == null || result != null) {
                UserCommunity user = new Gson().fromJson(new JsonParser().parse(result).getAsJsonObject().get("data").toString(),
                        UserCommunity.class);
                LinearLayout layout = (LinearLayout) findViewById(R.id.linear_interests);
                selectedUser.interests = user.interests;
                String name = "";
                // TextView txt_Interests = (TextView) findViewById(R.id.txtInterests);
                for (UserCommunity.Interest interest : selectedUser.interests) {
                    final TextView txt_Interests = new TextView(AppController.getAppContext());
                    txt_Interests.setBackgroundResource(R.drawable.txt_border_circle);
                    txt_Interests.setPadding(5,5,5,5);
                    name = interest.name;
                    txt_Interests.setText(name);
                    layout.addView(txt_Interests);

                }
                String point = "";
                TextView points = (TextView) findViewById(R.id.txt_Points);
                selectedUser.points = user.points;
                point = selectedUser.points + "\npontos";
                points.setText(point);

            }
        }
    });

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.