teoREtik
teoREtik

Reputation: 7916

Change View content in activity dynamically

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?

Upvotes: 6

Views: 36579

Answers (2)

Guillaume
Guillaume

Reputation: 22822

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.

Upvotes: 8

Mahdi Hijazi
Mahdi Hijazi

Reputation: 4454

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

Upvotes: 0

Related Questions