使用Fragment实现顶部菜单栏

    之前使用ViewPager+ActivityGroup实现过顶部菜单栏切换,参照http://blog.csdn.net/tan313/article/details/4174501今天使用Fragment实现顶部菜单栏。ViewPager类似一个View容器,他可以将View的数组添加进去。Fragment这个控件是依附activity存在的,

1.继承Fragment,重写onCreateView决定Fragment的布局

2.在activity中声明此Fragment,就当和普通的View一样


使用示例如下:

首先开始编写三个Fragment布局文件,简单的布局:

第一个chatfragment.xml文件:

<?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" >

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        
         <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="100dp"
        android:background="#ffffff"
        android:gravity="center"
        android:orientation="vertical" >

        <Button 
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="聊天,点击我"
        android:id="@+id/chatbtn"
        />

    	</LinearLayout>
        
    </RelativeLayout>

</LinearLayout>

2.第二个foundfragment文件:

<?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" >

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        
         <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="100dp"
        android:background="#ffffff"
        android:gravity="center"
        android:orientation="vertical" >

        <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发现,点击我"
        android:id="@+id/foundbtn"
        />

    	</LinearLayout>
        
    </RelativeLayout>

</LinearLayout>

3.第三个contactfragment.xml文件:

<?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" >

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        
        <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="100dp"
        android:background="#ffffff"
        android:gravity="center"
        android:orientation="vertical" >

        <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="通讯录,点击我"
        android:id="@+id/contactbtn"
        />

    	</LinearLayout>
        
    </RelativeLayout>

</LinearLayout>


上面三个布局只是简单的往界面添加一个按钮。


主布局文件activity_main.xml文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    
    <RelativeLayout 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
        <LinearLayout 
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:id="@+id/title"
            android:orientation="horizontal"
            >
            <LinearLayout 
                android:id="@+id/chat_layout"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_weight="1"
                android:gravity="center"
                >
                <TextView
                android:id="@+id/chatText"
                android:text="聊天"
                android:gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:textSize="20sp"
                 />
            </LinearLayout>
            
            <LinearLayout 
                android:id="@+id/found_layout"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_weight="1"
                android:gravity="center"
                >
                <TextView
                android:id="@+id/foundText"
                android:text="发现"
                android:gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:textSize="20sp"
                 />
            </LinearLayout>
            <LinearLayout 
                android:id="@+id/contact_layout"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_weight="1"
                android:gravity="center"
                >
               <TextView
                android:id="@+id/contactText"
                android:text="通讯录"
                android:gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:textSize="20sp"
                 /> 
            </LinearLayout>
 
        </LinearLayout>
        <FrameLayout 
            android:id="@+id/content"
            android:layout_below="@id/title"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >
            
        </FrameLayout>
    </RelativeLayout> 

</RelativeLayout>

在主布局文件中,书写了顶部菜单栏标题。


接下来实现继承Fragment的java文件:

第一个ChatFragment.java文件:

package com.example.chattdwdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;


public class ChatFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.chatfragment, container, false);
		Button button = (Button) view.findViewById(R.id.chatbtn);
		button.setOnClickListener(new OnClickListener());
		return view;
	}
	
	private final class OnClickListener implements android.view.View.OnClickListener{

		@Override
		public void onClick(View v) {
			Toast.makeText(getActivity(), "聊天", Toast.LENGTH_SHORT).show();
		}
		
	}
}

第二个FoundFragment.java文件:

package com.example.chattdwdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;


public class FoundFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.foundfragment, container, false);
		Button button = (Button) view.findViewById(R.id.foundbtn);
		button.setOnClickListener(new OnClickListener());
		return view;
	}
	
	private final class OnClickListener implements android.view.View.OnClickListener{

		@Override
		public void onClick(View v) {
			Toast.makeText(getActivity(), "发现", Toast.LENGTH_SHORT).show();
		}
		
	}
}

第三个ContactsFragment文件:


package com.example.chattdwdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;


public class ContactsFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.contactfragment, container, false);
		Button button = (Button) view.findViewById(R.id.contactbtn);
		button.setOnClickListener(new OnClickListener());
		return view;
	}
	
	private final class OnClickListener implements android.view.View.OnClickListener{

		@Override
		public void onClick(View v) {
			Toast.makeText(getActivity(), "通讯录", Toast.LENGTH_SHORT).show();
		}
		
	}
}

这三个文件类似,通过重写onCreateView方法加载布局文件。

接下来是核心的主activity

package com.example.chattdwdemo;

import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TextView;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.os.Bundle;

public class MainActivity extends Activity implements OnClickListener{

	private ChatFragment chatFragment;
	private FoundFragment foundFragment;
	private ContactsFragment contactsFragment;
	
	private View chatView;
	private View foundView;
	private View contactView;
	
	private TextView chatText;
	private TextView foundText;
	private TextView contactText;
	
	private FragmentManager manager;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		manager = getFragmentManager();
		
		InitFragments();
		
		InitView();
		setTabSelection(0);
	}

	private void InitView() {
		chatView = findViewById(R.id.chat_layout);
		foundView = findViewById(R.id.found_layout);
		contactView = findViewById(R.id.contact_layout);
		
		chatText = (TextView) findViewById(R.id.chatText);
		foundText = (TextView) findViewById(R.id.foundText);
		contactText = (TextView) findViewById(R.id.contactText);
		
		chatView.setOnClickListener(this);
		foundView.setOnClickListener(this);
		contactView.setOnClickListener(this);
	}

	private void InitFragments() {
		FragmentTransaction ft = manager.beginTransaction();
		
		chatFragment = new ChatFragment();
		ft.add(R.id.content,chatFragment);
		
		foundFragment = new FoundFragment();
		ft.add(R.id.content, foundFragment);
		
		contactsFragment = new ContactsFragment();
		ft.add(R.id.content, contactsFragment);
		
		ft.commit();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.chat_layout:
			setTabSelection(0);
			break;
		case R.id.found_layout:
			setTabSelection(1);
			break;
		case R.id.contact_layout:
			setTabSelection(2);
			break;
		}
	}

	private void setTabSelection(int index) {
		clearSelection();
		FragmentTransaction transaction = manager.beginTransaction();
		hideFragments(transaction);
		switch (index) {
		case 0:
			chatText.setTextColor(Color.BLACK);
			chatView.setBackgroundResource(R.drawable.btn_down);
			if(chatFragment == null){
				chatFragment = new ChatFragment();
				transaction.add(R.id.content, chatFragment);
			}else{
				transaction.show(chatFragment);
			}
			break;
		case 1:
			foundText.setTextColor(Color.BLACK);
			foundView.setBackgroundResource(R.drawable.btn_down);
			if(foundFragment == null){
				foundFragment = new FoundFragment();
				transaction.add(R.id.content, foundFragment);
			}else{
				transaction.show(foundFragment);
			}
			break;
		case 2:
			contactText.setTextColor(Color.BLACK);
			contactView.setBackgroundResource(R.drawable.btn_down);
			if(contactsFragment == null){
				contactsFragment = new ContactsFragment();
				transaction.add(R.id.content, contactsFragment);
			}else{
				transaction.show(contactsFragment);
			}
			break;
		}
		transaction.commit();
	}

	private void clearSelection() {
		chatView.setBackgroundDrawable(null);
		foundView.setBackgroundDrawable(null);
		contactView.setBackgroundDrawable(null);
		
		chatText.setTextColor(Color.BLACK);
		foundText.setTextColor(Color.BLACK);
		contactText.setTextColor(Color.BLACK);
	}

	private void hideFragments(FragmentTransaction transaction) {
		if(chatFragment != null){
			transaction.hide(chatFragment);
		}
		if(foundFragment != null){
			transaction.hide(foundFragment);
		}
		if(contactsFragment != null){
			transaction.hide(contactsFragment);
		}
	}
}

Fragment是通过事务进行处理的,首先必须getFragmentManager()方法得到FragmentManager,通过他开始一个事务

FragmentManager manager = getFragmentManager();

FragmentTransaction ft = manager.beginTransaction();

 

chatFragment = new ChatFragment();
ft.add(R.id.content,chatFragment);

foundFragment = new FoundFragment();
ft.add(R.id.content, foundFragment);

contactsFragment = new ContactsFragment();
ft.add(R.id.content, contactsFragment);

将各个Fragment界面添加到一个activity中。

ft.commit();

事务进行提交后后。即添加上去 了。


代码下载:http://download.csdn.net/detail/tan313/8502797

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用Fragment实现底部导航栏的跳转,您需要执行以下步骤: 1. 在您的项目中创建一个BottomNavigationView对象,它将用于显示底部导航栏。 2. 创建多个Fragment类,每个类都代表底部导航栏的一个选项。 3. 在您的Activity类中,创建一个FragmentManager对象并使用beginTransaction()方法开始一个新的FragmentTransaction。 4. 在FragmentTransaction中,使用add()方法将您的第一个Fragment添加到Activity中。同时,将BottomNavigationView的setOnNavigationItemSelectedListener()方法定义为一个监听器,以便在用户点击底部导航栏时执行相应的操作。 5. 在监听器中,使用replace()方法切换到用户选择的Fragment。 以下是一个简单的示例代码,可以帮助您更好地理解如何使用Fragment实现底部导航栏的跳转: ``` public class MainActivity extends AppCompatActivity { private BottomNavigationView bottomNavigationView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bottomNavigationView = findViewById(R.id.bottom_navigation); // 设置默认选中项 bottomNavigationView.setSelectedItemId(R.id.navigation_home); // 设置监听器 bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { Fragment fragment; switch (menuItem.getItemId()) { case R.id.navigation_home: fragment = new HomeFragment(); break; case R.id.navigation_dashboard: fragment = new DashboardFragment(); break; case R.id.navigation_notifications: fragment = new NotificationsFragment(); break; default: return false; } getSupportFragmentManager() .beginTransaction() .replace(R.id.fragment_container, fragment) .commit(); return true; } }); } } ``` 在这个例子中,我们首先获取了一个BottomNavigationView对象,并将其与我们的布局文件关联。我们还设置了默认选中项并添加了一个监听器。 在监听器中,我们使用了一个switch语句来确定用户选择了哪个选项。然后我们创建了相应的Fragment,并使用replace()方法将其添加到Activity中。 请注意,我们使用了一个FrameLayout来承载我们的Fragment。您需要在布局文件中添加一个类似的视图,以便能够动态添加和删除Fragment。 希望这可以帮助您开始使用Fragment实现底部导航栏的跳转。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值