Ken D
Ken D

Reputation: 61

How to use textView with Fragments Android/Java?

public class YourComputerRig extends Fragment {

        public void onCreate(Bundle savedInstanceState) {

            // Create the text view
            TextView textView = new TextView(this);
            textView.setTextSize(30);

            textView.setText("Passed in var: " + variable);

            // Set the text view as the activity layout
            setContentView(textView);
        }

new TextView(this) and setContentView are throwing errors... What would I use as the parameter instead of this? Or would it be better to not use a fragment for what I am trying to do?

Upvotes: 1

Views: 47

Answers (1)

Blackbelt
Blackbelt

Reputation: 157437

overriding onCreateView, that is called to have the fragment instantiate its user interface view.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    TextView textView = new TextView(getActivity());
    textView.setTextSize(30);
    textView.setText("Passed in var: " + variable);
    return textView;
 }

Through getView() you can get the root view for the fragment's layout (the one returned by onCreateView. In your case it will return a TextView

Upvotes: 1

Related Questions