Android的工作室主要活动,有一个按钮,得到碎片布局 [英] Android Studio Main Activity That has a button and gets the Fragment layout

查看:258
本文介绍了Android的工作室主要活动,有一个按钮,得到碎片布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在主要活动的一个按钮,用户点击时
它的片段布局将出现?进出口新到Android Studio.If其可能
你认为你能告诉我它的一个例子。

Is it possible to have a button in the main activity and when the user clicks it , the fragment layout will appear? Im new to Android Studio.If its possible do you think you can show me an example of it.

推荐答案

您可以直接使用它的主要活动是这样的例子:

You can use it directly from the main activity like this example:

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    >

    <Button
        android:id="@+id/button"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:text="Click me"
        />

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.root_layout, new NewFragment());
                transaction.commit();
                //button.setVisibility(View.GONE);
            }
        });

    }
}

在哪里NewFragment只是一个黑色的片段。

Where NewFragment is just a black fragment.

问题是的LinearLayout被替换,但按钮没有

The problem is the LinearLayout is replaced, but the button is not:

一个片段取代布局的活动。

所以,你可以设置可见性(作为在code注释)。但我建议创建2片段,其中一个按钮和一个与你的内容。然后在活动onCreate()方法,你可以设置一个片段,并与其他一人后来取代它。

So you can set the visibility (as a commented in the code). But I suggest to create 2 fragments, one with the button and one with your content. Then in the activity onCreate() method, you can set the first fragment and replace it with the other one later.

这篇关于Android的工作室主要活动,有一个按钮,得到碎片布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆