动态更改活动中的查看内容 [英] Change View content in activity dynamically
问题描述
我从Activity
类扩展的抽象类由三个View
组成,如以下XML代码段所述:
My abstract class extended from Activity
class consists of three View
s 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>
在onCreate()
方法中,我将此XML布局设置为内容视图.
And in onCreate()
method I set this XML-layout as content view.
我希望扩展该范围的Activity
覆盖onCreate()
,并在其中定义activity_content View
其余边界是不变的.
I want the Activity
s which extend this one to override onCreate()
and there define the activity_content View
remaining borders immutable.
例如这样的
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.)
}
}
但是当我这样做时,我的mContent仍然与在MyActivity
的onCreate()
中定义它的时候相同.
But when I do so my mContent remain the same as it was when I defined it in MyActivity
's onCreate()
.
如何根据前景中的Activity
更改视图的类型/内容?
How can I change view's type/content depends on what Activity
is in foreground?
推荐答案
首先将主布局中的视图更改为视图组(例如,LinearLayout
).然后,您可以向其中添加视图.如果添加唯一视图,它将完全具有您想要实现的效果.
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.
另一种方法是查看 Fragments API (可用于最新版本的SDK)
An alternative is to look at the Fragments API, available for latest versions of the SDK.
这篇关于动态更改活动中的查看内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!