omega
omega

Reputation: 43843

How to get a view from a fragment layout in android?

I have an xml like this

activity_loginscreen.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="android.arin.LoginScreen"
    tools:ignore="MergeRootFrame" />

and then gragment_loginscreen.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    style="@style/LoginView"
    tools:context="android.arin.LoginScreen$PlaceholderFragment" >

    <ImageView
        android:id="@+id/bubbles"
        android:contentDescription="@string/bubbles_cd"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:alpha=".75"
        android:src="@drawable/bubbles" />

</RelativeLayout>

In my java file I have

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login_screen);

    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }

    ImageView bubbles = (ImageView) findViewById(R.id.bubbles);
}

But bubbles ends up being null because it can't find it because its looking in the activity xml one, but really the imageview is in the fragment one, how can I get it to look there?

Thanks

Upvotes: 0

Views: 1024

Answers (2)

M D
M D

Reputation: 47807

Make your PlaceholderFragment fragment onCreateView(....) like

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.gragment_loginscreen, container, false);
    ImageView bubbles = (ImageView)view.findViewById(R.id.bubbles);
    return view;
}

and used getActivity() as a Context in Fragment like

Animation animContentUp = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_up_service);

Upvotes: 1

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

Place the imageView in your PlaceholderFragment onCreateView and in the PlaceholderFragment inflate the layout gragment_loginscreen which will generate a view..

example:

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.gragment_loginscreen, container, false);
        ImageView bubbles = (ImageView)view.findViewById(R.id.bubbles);
        return view;
}

Upvotes: 0

Related Questions