在片段类中使用字符串数组的TextView的SetText

时间:2018-08-05 06:41:41

标签: android android-fragments textview settext cardview

我试图在Duolingo之类的cardView中制作卡片,我在线找到了代码,并尝试根据需要编辑该代码。问题是我不知道如何使用String的数组列表并在每个卡更改时更改其文本。 我希望根据创建的阵列列表更改每个卡中的文本。问题是我无法从"position"获取array to textview并将setText设置为它。以下是我的卡片片段代码。

public class CardFragment extends Fragment {

    private CardView cardView;

    public static Fragment getInstance(int position) {
        CardFragment f = new CardFragment();
        Bundle args = new Bundle();
        args.putInt("position", position);
        f.setArguments(args);

        return f;
    }


    public static String[] line1 ={
            "Card no 1",
            "Card no 2",
            "Card no 3",
            "Card no 4",
            "Card no 5",
            "Card no 6",

    };

    public static String[] line2 = {
            "This is card number 1",
            "This is card number 2",
            "This is card number 3",
            "This is card number 4",
            "This is card number 5",
            "This is card number 6",
    };

    @SuppressLint("DefaultLocale")
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.item_viewpager, container, false);

        cardView = (CardView) view.findViewById(R.id.cardView);
        cardView.setMaxCardElevation(cardView.getCardElevation() * CardAdapter.MAX_ELEVATION_FACTOR);

        TextView title = (TextView) view.findViewById(R.id.title);
        Button button = (Button)view.findViewById(R.id.button);
        TextView description = (TextView) view.findViewById(R.id.description);

        // how to setText here from the above array list.
        title.setText(line1[position]) // this is giving me error.



        title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "This is Card no " + getArguments().getInt("position"), Toast.LENGTH_SHORT).show();
            }
        });



        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(), "Button in Card " + getArguments().getInt("position")
                        + "Clicked!", Toast.LENGTH_SHORT).show();
            }
        });

        return view;
    }

    public CardView getCardView() {
        return cardView;
    }


}

1 个答案:

答案 0 :(得分:0)

在您的代码中,您尚未设置和分配int位置变量,因此请在出现错误的行上添加以下代码

int position = getArguments().getInt("position");

// how to setText here from the above array list.
title.setText(line1[position]) // this is giving me error.