Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setContentView and Listeners

I'm changing my ContentView of the Activity at some point. (to View2). After changing it back to View1, the listeners are not more working. I already tried putting the Listener in the onResume() method.

Is it common anyway to use setContentView() to display e.g. a Progress screen/please wait,...(while an asyncTask is running). Or should you only have ONE mainView for each Activity? (and replacing the content dynamically).

//EDIT: To be more specific: I am looking for something like

LinearLayout item = (LinearLayout) findViewById(R.id.mainView);
View child = getLayoutInflater().inflate(R.layout.progress, null);
item.addView(child);

but instead of adding the "progress.xml", it should remove the current layout and ONLY show "progress.xml". Do I need an "container" and show/hide mainView/progress? But that doesn't seem very proper to me...

See also code below (stripped)

public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.view1);

       button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                doSomething();
            }
        });
}

setContentView(R.layout.view2);
[...]
setContentView(R.layout.view1);

//Listener not more working
like image 480
Johannes Staehlin Avatar asked Sep 03 '25 02:09

Johannes Staehlin


2 Answers

Thank you all, for your reply. You made me realize, the onClickListeners are getting lost when I remove or replace (using setContentView()) the main view. I ended up this way now:

onCreate:

setContentView(R.layout.parse);
LinearLayout container = (LinearLayout) findViewById(R.id.container);
container.addView(getLayoutInflater().inflate(R.layout.dialog, null));
container.addView(getLayoutInflater().inflate(R.layout.progress, null));

onStartDoingSomething:

findViewById(R.id.dialog).setVisibility(View.INVISIBLE);
findViewById(R.id.progress).setVisibility(View.VISIBLE);

onEndDoingSomehting:

findViewById(R.id.dialog).setVisibility(View.VISIBLE);
findViewById(R.id.progress).setVisibility(View.INVISIBLE);

I might change View.INVISIBLE to View.GONE, like nmr said, but since I have never used View.GONE, I have to check the Android doku first ;)

like image 172
Johannes Staehlin Avatar answered Sep 04 '25 20:09

Johannes Staehlin


Assuming you use 'findViewById' to initialize 'button', you would need to do that every time that you do setContentView(R.layout.view1);

like image 38
Jim Rhodes Avatar answered Sep 04 '25 19:09

Jim Rhodes