@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutId()); FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(getFragmentId()); if(fragment == null){ fragment = createFragment(); fm.beginTransaction(). add(getFragmentId(),fragment) .commit(); } } }
时间: 2024-02-14 18:04:53 浏览: 192
这段代码展示了一个典型的 Android 活动(Activity)类的 onCreate 方法。在 onCreate 方法中,我们:
1. 使用 setContentView 方法设置活动界面的布局。
2. 获取 FragmentManager 对象,用于管理多个碎片(Fragment)并执行事务。
3. 使用 FragmentManager 的 findFragmentById 方法查找指定 ID 的碎片。
4. 如果找不到指定 ID 的碎片,则创建一个新的碎片,并将其添加到指定 ID 的容器中。
其中,getLayoutId 和 getFragmentId 是抽象方法,需要在子类中实现。它们分别返回活动的布局和碎片的容器 ID。createFragment 方法也是抽象方法,需要在子类中实现,用于创建该活动所需的碎片。
相关问题
使用 ViewPager 和 Fragment 做一个简单版的好友列表界面 1. 使用 ViewPager 和 Fragment 做个可滑动界面 2. 使用 TabLayout 添加 Tab 支持给出文件的所有代码。要求可以直接运行,一定要给出import,以及配置
好的,以下是实现这个功能所需的代码。
activity_main.xml 布局文件:
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabGravity="fill"
app:tabMode="fixed" />
<androidx.viewpager.widget.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
```
FriendListFragment.java 代码:
```java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class FriendListFragment extends Fragment {
private static final String ARG_TITLE = "title";
private String mTitle;
public static FriendListFragment newInstance(String title) {
FriendListFragment fragment = new FriendListFragment();
Bundle args = new Bundle();
args.putString(ARG_TITLE, title);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mTitle = getArguments().getString(ARG_TITLE);
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_friend_list, container, false);
TextView titleTextView = view.findViewById(R.id.title_text_view);
titleTextView.setText(mTitle);
return view;
}
}
```
fragment_friend_list.xml 布局文件:
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/title_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceMedium" />
</LinearLayout>
```
MainActivity.java 代码:
```java
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ViewPager mViewPager;
private TabLayout mTabLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = findViewById(R.id.view_pager);
mTabLayout = findViewById(R.id.tab_layout);
List<String> titles = new ArrayList<>();
titles.add("好友");
titles.add("陌生人");
List<Fragment> fragments = new ArrayList<>();
fragments.add(FriendListFragment.newInstance("好友列表"));
fragments.add(FriendListFragment.newInstance("陌生人列表"));
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager(), titles, fragments);
mViewPager.setAdapter(adapter);
mTabLayout.setupWithViewPager(mViewPager);
}
private static class MyPagerAdapter extends FragmentPagerAdapter {
private List<String> mTitles;
private List<Fragment> mFragments;
public MyPagerAdapter(FragmentManager fm, List<String> titles, List<Fragment> fragments) {
super(fm);
mTitles = titles;
mFragments = fragments;
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return mTitles.get(position);
}
}
}
```
最后,别忘了在 AndroidManifest.xml 文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.INTERNET" />
```
以上就是实现 ViewPager 和 Fragment 做一个简单版的好友列表界面的所有代码。
在此配置下:Window系统;IDE:Android Studio;项目管理:Gradle;JDK 8;要求:1、创建一个App项目.2、创建1个Activity作为主界面。主界面下方有四个按钮,每个按钮点击的时候切换上方的主界面(使用Fragment实现)3、在其中一个按钮点击的时候在上方主界面使用ListView显示用户列表。(列表信息和内容为用户名鲁班,司马懿并生成他们的最近登陆时间)附上代码
好的,以下是实现你要求的代码示例。
activity_main.xml:
```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">
<!-- Fragment容器 -->
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/bottom_navigation_view" />
<!-- 底部导航栏 -->
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@color/colorPrimary"
app:itemIconTint="@color/white"
app:itemTextColor="@color/white"
app:menu="@menu/bottom_navigation_menu" />
</RelativeLayout>
```
bottom_navigation_menu.xml:
```xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/navigation_home"
android:icon="@drawable/ic_home"
android:title="@string/home" />
<item
android:id="@+id/navigation_user"
android:icon="@drawable/ic_user"
android:title="@string/user" />
<item
android:id="@+id/navigation_settings"
android:icon="@drawable/ic_settings"
android:title="@string/settings" />
<item
android:id="@+id/navigation_about"
android:icon="@drawable/ic_about"
android:title="@string/about" />
</menu>
```
MainActivity.java:
```java
public class MainActivity extends AppCompatActivity {
private BottomNavigationView mBottomNavigationView;
private FragmentManager mFragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBottomNavigationView = findViewById(R.id.bottom_navigation_view);
mFragmentManager = getSupportFragmentManager();
// 默认显示首页Fragment
mFragmentManager.beginTransaction()
.replace(R.id.fragment_container, new HomeFragment())
.commit();
// 底部导航栏点击事件
mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.navigation_home:
mFragmentManager.beginTransaction()
.replace(R.id.fragment_container, new HomeFragment())
.commit();
return true;
case R.id.navigation_user:
mFragmentManager.beginTransaction()
.replace(R.id.fragment_container, new UserFragment())
.commit();
return true;
case R.id.navigation_settings:
mFragmentManager.beginTransaction()
.replace(R.id.fragment_container, new SettingsFragment())
.commit();
return true;
case R.id.navigation_about:
mFragmentManager.beginTransaction()
.replace(R.id.fragment_container, new AboutFragment())
.commit();
return true;
}
return false;
}
});
}
}
```
HomeFragment.java:
```java
public class HomeFragment extends Fragment {
private ListView mListView;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
mListView = view.findViewById(R.id.list_view);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// 用户列表数据
String[] users = {"鲁班", "司马懿"};
String[] loginTimes = {"2021-07-01 10:00:00", "2021-07-01 11:00:00"};
// 创建Adapter
UserListAdapter adapter = new UserListAdapter(getContext(), users, loginTimes);
// 设置Adapter
mListView.setAdapter(adapter);
}
}
```
UserListAdapter.java:
```java
public class UserListAdapter extends ArrayAdapter<String> {
private Context mContext;
private String[] mUsers;
private String[] mLoginTimes;
public UserListAdapter(Context context, String[] users, String[] loginTimes) {
super(context, R.layout.item_user, users);
mContext = context;
mUsers = users;
mLoginTimes = loginTimes;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_user, parent, false);
viewHolder = new ViewHolder();
viewHolder.mUserNameTextView = convertView.findViewById(R.id.user_name_text_view);
viewHolder.mLoginTimeTextView = convertView.findViewById(R.id.login_time_text_view);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.mUserNameTextView.setText(mUsers[position]);
viewHolder.mLoginTimeTextView.setText(mLoginTimes[position]);
return convertView;
}
private static class ViewHolder {
TextView mUserNameTextView;
TextView mLoginTimeTextView;
}
}
```
item_user.xml:
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/user_name_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/login_time_text_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:textSize="14sp" />
</LinearLayout>
```
fragment_home.xml:
```xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
这样,你就可以在其中一个按钮点击时,在上方主界面使用 ListView 显示用户列表了。
阅读全文