Harsha M V
Harsha M V

Reputation: 54949

Android Fragment Implementation

I am trying to implement Fragments in my Project using the https://github.com/JakeWharton/Android-ViewPagerIndicator plugin.

My Fragment

public final class NearByFragment extends Fragment {
    private static String TAG = "bMobile";

    public static NearByFragment newInstance(String content) {
        NearByFragment fragment = new NearByFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate");
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        return inflater.inflate(R.layout.fragment_search_nearby, null);
    }
}

Now I want to execute some code like start start a new thread and download a JSON from the server and then assign a list view from the content I download. In fragments we are assigning views in onCreateView. so where should I write the

listview = (ListView) findViewById(R.id.list_items);

((TextView) findViewById(R.id.title_text))
                .setText(R.string.description_blocked);

and other code to generate the Fragment view ?

Upvotes: 2

Views: 2206

Answers (2)

Martin Stone
Martin Stone

Reputation: 13007

You can search within the view that you just inflated:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        View v = inflater.inflate(R.layout.fragment_search_nearby, null);
        listview = (ListView)v.findViewById(R.id.list_items);
        ((TextView)v.findViewById(R.id.title_text))
                        .setText(R.string.description_blocked);
        return v;
    }

You can also use the Fragment.getView() function elsewhere in your code and call that view's findViewById() member.

Upvotes: 3

jprofitt
jprofitt

Reputation: 10964

You can use getActivity().findByView() from the Fragment if you want to have access to the layout elements. Alternatively, you can just put the findByView() call in the main Activity.

Upvotes: 1

Related Questions