Change View content in activity dynamically

假装没事ソ 提交于 2019-12-09 06:09:53

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/8880787/change-view-content-in-activity-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!