Question

My abstract class extended from Activity class consists of three Views as described in the following XML snippet:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:background="@drawable/bg">

    <LinearLayout 
        android:id="@+id/top_border">
        ...
    </LinearLayout>

    <View 
        android:id="@+id/activity_content"
        ...
        />

    <LinearLayout 
        android:id="@+id/bottom_border">
        ...          
    </LinearLayout>
</LinearLayout>

And in onCreate() method I set this XML-layout as content view.

I want the Activitys which extend this one to override onCreate() and there define the activity_content View remaining borders immutable.

For example like this:

abstract public class MyActivity extends Activity {
   protected View mContent;

   @Override
   protected onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.common_layout);
      initializeContent();
   }

   abstract void initializeContent();  
}

class OneActivity extends MyActivity {

   @Override
   protected void initializeContent() {
      mContent = View.inflate(this, R.layout.some_view, null); // i.e. concrete View (e.g. LinearLayout, FrameLayout, GridView, etc.)
   }
}

But when I do so my mContent remain the same as it was when I defined it in MyActivity's onCreate().

How can I change view's type/content depends on what Activity is in foreground?

Was it helpful?

Solution

First change the view in your main layout into a view group (for example, a LinearLayout). Then you can add views to it. If you add a unique view, it will have exactly the effect you want to achieve.

class OneActivity extends MyActivity {
   @Override
   protected void initializeContent() {
      final ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_content);
      viewGroup.addView(View.inflate(this, R.layout.some_view, null)); 
   }
}

In your case that should work. If your custom view group contained other views from higher up in the hierarchy, you can clean it before adding your custom view:

viewGroup.removeAllViews();

It works, I do exactly that in most of my projects.

An alternative is to look at the Fragments API, available for latest versions of the SDK.

OTHER TIPS

You can't override class data members in Java, use methods instead

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top