在Android中做片段的正确方法是什么?

时间:2019-02-27 19:51:39

标签: java android firebase android-recyclerview

我是Android Studio的新手,正在开发一个应用程序,它的界面功能之一是显示各种用户的数据,我看到了许多有关如何使用FirebaseRecyclerAdapter列出数据的教程,但它们无法正常工作。现在,我正在尝试做一些尚不知道如何做的片段。

我想知道是否正确设置了这段代码来制作片段。

我的 MainActivity.java

public class MainActivity extends AppCompatActivity {

    private RelativeLayout pills_layout, appoint_layout, add_pills_layout, add_appoints_layout, account_layout, add_button;
    private TextView AccountName0, AccountAge0;
    private RecyclerView recyclerView;
    private LinearLayoutManager linearLayoutManager;
    private FirebaseRecyclerAdapter adapter;
    private View view;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    Home();
                    return true;
                case R.id.navigation_pills:
                    Pills();
                    return true;
                case R.id.navigation_appointment:
                    Appointment();
                    return true;
                case R.id.navigation_account:
                    Account();
                    return true;
            }
            return false;
        }
    };

    public MainActivity() {
    }

    private void Account(){
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
        params.addRule(RelativeLayout.BELOW, R.id.account);

        pills_layout.setVisibility(View.GONE);
        appoint_layout.setVisibility(View.GONE);
        add_pills_layout.setVisibility(View.GONE);
        add_appoints_layout.setVisibility(View.GONE);
        //account_layout.setVisibility(View.VISIBLE);

        add_button.setVisibility(View.VISIBLE);

        /*Button accountChangePass = findViewById(R.id.AccountChangePass);

        accountChangePass.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent ChangePW = new Intent(MainActivity.this, ChangePW.class);
                startActivity(ChangePW);
            }
        });*/
    }


    private void Appointment() {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
        params.addRule(RelativeLayout.BELOW, R.id.add_appoints);

        pills_layout.setVisibility(View.GONE);
        appoint_layout.setVisibility(View.GONE);
        add_pills_layout.setVisibility(View.GONE);
        add_appoints_layout.setVisibility(View.VISIBLE);
        //account_layout.setVisibility(View.GONE);

        add_button.setVisibility(View.VISIBLE);
    }

    private void Pills() {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
        params.addRule(RelativeLayout.BELOW, R.id.add_pills);

        pills_layout.setVisibility(View.GONE);
        appoint_layout.setVisibility(View.GONE);
        add_pills_layout.setVisibility(View.VISIBLE);
        add_appoints_layout.setVisibility(View.GONE);
        //account_layout.setVisibility(View.GONE);

        add_button.setVisibility(View.VISIBLE);
    }

    private void Home() {
        pills_layout.setVisibility(View.VISIBLE);
        appoint_layout.setVisibility(View.VISIBLE);
        add_pills_layout.setVisibility(View.GONE);
        add_appoints_layout.setVisibility(View.GONE);
        //account_layout.setVisibility(View.GONE);

        add_button.setVisibility(View.GONE);
    }

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

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user == null) {
            Intent VerifyLogin = new Intent(MainActivity.this, Launcher.class);
            VerifyLogin.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(VerifyLogin);
        }

        pills_layout = findViewById(R.id.pills_layout);
        appoint_layout = findViewById(R.id.appoint_layout);
        add_pills_layout = findViewById(R.id.add_pills);
        add_appoints_layout = findViewById(R.id.add_appoints);
        //account_layout = findViewById(R.id.accountlist);

        AccountName0 = findViewById(R.id.AccountName0);
        AccountAge0 = findViewById(R.id.AccountAge0);

        add_button = findViewById(R.id.add);

        pills_layout.setVisibility(View.VISIBLE);
        appoint_layout.setVisibility(View.VISIBLE);
        add_pills_layout.setVisibility(View.GONE);
        add_appoints_layout.setVisibility(View.GONE);
        //account_layout.setVisibility(View.GONE);
        add_button.setVisibility(View.GONE);

        recyclerView = findViewById(R.id.accountlist);

        linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setHasFixedSize(true);

        BottomNavigationView navigation = findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public RelativeLayout root;
        public TextView txtTitle;
        public TextView txtDesc;

        public ViewHolder(View itemView) {
            super(itemView);
            root = itemView.findViewById(R.id.account);
            txtTitle = itemView.findViewById(R.id.AccountName0);
            txtDesc = itemView.findViewById(R.id.AccountAge0);
        }

        public void setTxtTitle(String string) {
            txtTitle.setText(string);
        }


        public void setTxtDesc(String string) {
            txtDesc.setText(string);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Query query = FirebaseDatabase.getInstance()
                .getReference()
                .child("Users");

        FirebaseRecyclerOptions<Account> options =
                new FirebaseRecyclerOptions.Builder<Account>()
                        .setQuery(query, new SnapshotParser<Account>() {
                            @NonNull
                            @Override
                            public Account parseSnapshot(@NonNull DataSnapshot snapshot) {
                                return new Account(snapshot.child("name").getValue().toString(),
                                        snapshot.child("idade").getValue().toString());
                            }
                        })
                        .build();

        adapter = new FirebaseRecyclerAdapter<Account, ViewHolder>(options) {
            @Override
            public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.account, parent, false);

                return new ViewHolder(view);
            }


            @Override
            protected void onBindViewHolder(ViewHolder holder, final int position, Account model) {
                holder.setTxtTitle(model.getName());
                holder.setTxtDesc(model.getIdade());

                holder.root.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_SHORT).show();
                    }
                });
            }

        };
        recyclerView.setAdapter(adapter);
        adapter.startListening();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Query query = FirebaseDatabase.getInstance()
                .getReference()
                .child("Users");

        FirebaseRecyclerOptions<Account> options =
                new FirebaseRecyclerOptions.Builder<Account>()
                        .setQuery(query, new SnapshotParser<Account>() {
                            @NonNull
                            @Override
                            public Account parseSnapshot(@NonNull DataSnapshot snapshot) {
                                return new Account(snapshot.child("name").getValue().toString(),
                                        snapshot.child("idade").getValue().toString());
                            }
                        })
                        .build();

        adapter = new FirebaseRecyclerAdapter<Account, ViewHolder>(options) {
            @Override
            public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.account, parent, false);

                return new ViewHolder(view);
            }


            @Override
            protected void onBindViewHolder(ViewHolder holder, final int position, Account model) {
                holder.setTxtTitle(model.getName());
                holder.setTxtDesc(model.getIdade());

                holder.root.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_SHORT).show();
                    }
                });
            }

        };
        recyclerView.setAdapter(adapter);
        adapter.stopListening();
    }
};

我的 Account.java

public class Account {
    private String name, idade;

    public Account() {

    }

    public Account(String name, String idade) {
        this.name = name;
        this.idade = idade;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getIdade() {
        return idade;
    }

    public void setIdade(String idade) {
        this.idade = idade;
    }
}

我的 account.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/account">

        <RelativeLayout
            android:id="@+id/AccountUser"
            android:layout_width="match_parent"
            android:layout_height="163dp"
            android:layout_marginStart="15dp"
            android:layout_marginLeft="15dp"
            android:layout_marginTop="15dp"
            android:layout_marginEnd="15dp"
            android:layout_marginRight="15dp"
            android:layout_marginBottom="15dp"
            android:background="@drawable/edit_bg"
            android:padding="15dp">

            <RelativeLayout
                android:id="@+id/AccountImage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_user"/>

            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/AccountInfos"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/AccountImage"
                android:layout_toEndOf="@id/AccountImage"
                android:layout_marginStart="15dp"
                android:layout_marginLeft="15dp">

                <TextView
                    android:id="@+id/AccountName0"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingTop="5dp"
                    android:paddingBottom="5dp"
                    android:text="Nome1"
                    android:textColor="@color/colorWhite"
                    android:textSize="20sp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/AccountAge0"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/AccountName0"
                    android:paddingTop="5dp"
                    android:paddingBottom="5dp"
                    android:text="Idade1"
                    android:textColor="@color/colorWhite"
                    android:textSize="20sp"
                    android:textStyle="bold" />

                <Button
                    android:id="@+id/AccountChangePass"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/AccountAge0"
                    android:text="Mudar Palavra-Passe"
                    android:textColor="@color/colorWhite"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:textAllCaps="false"
                    android:padding="10dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/custom_button"/>
            </RelativeLayout>

        </RelativeLayout>
    </RelativeLayout>

</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

我认为最好的方法是使用片段。

创建3个片段:

Just check the checkBox that says " Create layout XML? "

只需选中显示“是否创建布局XML?”的复选框,

创建一个Java类,并在创建3个片段之后添加以下代码:

import typing

class A(list: typing.List[str]):  # Maybe something like this
   def __init__(self):
      list.__init__(self)

>> a = A()
>> a.append("a")  # No typing error
>> a.append(1)  # Typing error

}

现在在您的mainActivity.java中添加以下代码:

公共类MainActivity扩展了AppCompatActivity {

public class /* class name 1 */ extends FragmentPagerAdapter {

public /* class name 1 */ (FragmentManager fm) {

    super(fm);
}

@Override
public Fragment getItem(int position) {

    switch (position){
        case 0:
            Fragment1 fragment1= new Fragment1 ();
            return fragment1;
        case 1:
            Fragment2 fragment2 = new Fragment2();
            return fragment2 ;
        case 2:
            Fragment3 fragment3 = new Fragment3 ();
            return fragment3 ;

        default:
            return null;
    }
}


@Override
public int getCount() {

    return 3;

}

public CharSequence getPageTitle(int position){

    switch (position){
        case 0:
            return "/* set a name to fragment1*/";
        case 1:
            return "/* set a name to fragment2*/";
        case 2:
            return "/* set a name to fragment3*/";
        default:
            return null;
    }

}

}

现在在您的mainactivity.xml中添加以下内容:

private ViewPager mViewPager;

private /* class name 1 */ mSectionsPagerAdapter;

private TabLayout mTabLayout;

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

    mViewPager = findViewById(R.id.main_tabPager);

    mSectionsPagerAdapter = new /* class name 1 */(getSupportFragmentManager());

    mViewPager.setAdapter(mSectionsPagerAdapter);

    mTabLayout = findViewById(R.id.main_tabs);
    mTabLayout.setupWithViewPager(mViewPager);

}

最终结果将如下所示:

答案 1 :(得分:0)

我想吃药,布局,布局是您的片段布局。 通过更改其VISIBILITY属性来维护它们不是一个好主意。

您必须改为使用supportFragmentManager。 创建像这样的loadFragment方法

    public final boolean loadFragment(@NotNull Fragment fragment) {
    this.getSupportFragmentManager().beginTransaction()
      .replace(<<id of your fragment container layout>>, fragment, "fragment").commit();
    return true;
}

并将您的onNavigationItemSelected方法更改为此:

@Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_home:
                return loadFragment(new HomeFragment());
            case R.id.navigation_pills:
                return loadFragment(new PillsFragment());
            case R.id.navigation_appointment:
                return loadFragment(new AppointmentFragment());
            case R.id.navigation_account:
                return loadFragment(new AccountFragment());
        }
        return false;
    }
};

现在为每个片段创建一个单独的类,并为右侧片段增加布局。 这是您的HomeFragment类必须看起来像这样的示例:

public final class HomeFragment extends Fragment {

@Override
public View onCreate(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    return inflater.inflate(R.layout.<<your homefragment layout name>>, null);
}

}

我希望这足以帮助您。很抱歉,如果语法上没有什么错误,我曾经用Kotlin编写Android代码。但是您会得到背后的想法。