1

I am having the following method which passes View

private void doSomething(View view){ }

The problem am having is how do i call this view in onCreate method in an Activity, i will have to pass the view

For Example

View view;

doSomething(view)

How do is assign view/instantiate view, am using getView() but its not working

Like

view = getView()

For Example in fragments onViewCreatedMethod has an argument view which i can assign to the method when am calling it. Example below

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    doSomething(view);
}   

Is it possible to do that inside onCreate method in fragment, can I parse the View arguments in onCreate method in activity

Sir l33tname
  • 4,026
  • 6
  • 38
  • 49
Emmanuel Njorodongo
  • 1,004
  • 17
  • 35
  • What view do you want to get ? the activity view (layout) ? a view inside the layout ? – SebastienRieu Jul 16 '20 at 14:00
  • Do You want to assign `view` with some View from Your layout? – iknow Jul 16 '20 at 14:00
  • 1
    Instead of using `getView()`, in the `onCreate` method you can just use `findViewById(R.id.xxx)` – Gabriele Mariotti Jul 16 '20 at 14:11
  • @SebastienRieu i have edited the question to further explain – Emmanuel Njorodongo Jul 16 '20 at 14:21
  • First, the right question to ask is "what do you need a view in a method of activity" ? (1) If you need to setup a specific view of your layout, for example TextView with id textView you can get this view doing "TextView tv = findViewById(R.id.textView)" (2) If you needs the "activity" view, i suggest you to set an id to the activity layout parent view, and get it in the activity like this "View parent = findViewById(R.id.myActivityLayoutParentId)" and then pass this view to your doSomething method. – SebastienRieu Jul 16 '20 at 14:56

1 Answers1

2

In your onCreate method, once you've called setContentView, you can use findViewById to get whatever View you want. If you want the root view for some reason, you can pass android.R.id.content.

For example:

@Override
public void onCreate(Bundle savedInstanceState) {
    // Replace your_layout_id with your Activity layout ID
    setContentView(R.layout.your_layout_id);

    View rootView = findViewById(android.R.id.content);

    // Replace with whatever ID/View type you have in your code
    // Button and your_button_id are just examples
    Button button = findViewById(R.id.your_button_id); 
}
Ryan M
  • 18,333
  • 31
  • 67
  • 74