Android 在不使用片段的情况下在相同布局中更改屏幕

Android 在不使用片段的情况下在相同布局中更改屏幕,android,android-layout,Android,Android Layout,我正在用Android Studio开发。 我创建了一个侧面有按钮的屏幕,看起来像一个菜单栏。 我想使左侧(红色侧)布局可更改-意味着如果我单击右侧(绿色侧)的一个图像,左侧布局将更改为不同的布局并打开不同的活动。 我已经有了活动和它们的布局,我想用右侧的可点击图像显示在左侧。 我能不使用碎片让它工作吗 布局如下: 您可以使用替换片段 在OnClickListener中 FragmentManager manager = getSupportFragmentManager(); m

我正在用Android Studio开发。 我创建了一个侧面有按钮的屏幕,看起来像一个菜单栏。 我想使左侧(红色侧)布局可更改-意味着如果我单击右侧(绿色侧)的一个图像,左侧布局将更改为不同的布局并打开不同的活动。 我已经有了活动和它们的布局,我想用右侧的可点击图像显示在左侧。 我能不使用碎片让它工作吗

布局如下:


您可以使用替换片段

在OnClickListener中

 FragmentManager manager = getSupportFragmentManager();
    manager.beginTransaction()
            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
            .replace(R.id.content_main, new TargetFragment())
            .commit();
并在

 <ScrollView
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_gravity="left"
    android:layout_weight=".7">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="My List"

            android:textAlignment="center"
            android:textSize="20dp"
            android:textStyle="bold" />

    </LinearLayout>

</ScrollView>

更好、更简单的方法是使用片段。但是,如果您不想使用片段,那么您可以将活动xml中的所有视图放在单独的相对或线性布局中,以您喜欢的方式,并在每次单击时使用隐藏显示视图。

简单的方法是使用片段。片段被设计成可重用的UI布局。但如果您不想使用片段,可以创建CustomView并使用
addView
removeView
,例如:

LinearLayout layout=new LinearLayout(context);
layout.addView(new  Button(context));
layout.addView(new ImageButton(context));

TextView view = new TextView(context);
view.setText("Hello World");
layout.addView(view); 

layout.removeView(view);

从标题上看,我相信他不想使用碎片我正在尝试将所有内容都变成碎片…看看它是否有效..我有一个问题-布局目标\u fragment\u xml应该包含什么?另一个问题是OnClickListener中有一个:。替换(R.id.content\u main………我在这里做什么来替换什么?我希望您能解释一下我在做什么,谢谢!:)在OnClickListener中。您在activity\u main.xml==target\u fragment.xml中替换target\u fragment.xml是您显示屏幕的新位置
 import android.support.v4.app.Fragment;
 public class TargetFragment extends Fragment {
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.target_fragment_xml, container, false);

 // Enter code here
 return root;
 }
LinearLayout layout=new LinearLayout(context);
layout.addView(new  Button(context));
layout.addView(new ImageButton(context));

TextView view = new TextView(context);
view.setText("Hello World");
layout.addView(view); 

layout.removeView(view);