【问题标题】:start fragment on actionbar icon click在操作栏图标上开始片段单击
【发布时间】:2016-01-02 11:50:02
【问题描述】:

我想在单击活动的操作栏图标时打开一个片段,并在单击后退按钮(在片段的布局中)时删除该片段(并返回到活动)。小鬼是我的活动布局中没有<fragment>

main activity layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is main activity layout"
        android:textAppearance="?android:attr/textAppearanceLarge" />
        
</LinearLayout>
MainActivity

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		 
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		
		case R.id.settings:
			newintent();

		default:
			break;
		}
		
		return true;
		
	}

	private void newintent() {
		
		
		// Do something here to open FragmentOne.class
		
	}

	
}

【问题讨论】:

    标签: android android-fragments android-actionbar


    【解决方案1】:

    创建一个片段并将此代码添加到您的点击事件方法中

    private Fragment newFragment=new NewFragment();//global variable
    
    FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.popBackStack();
            FragmentTransaction ft =fragmentManager.beginTransaction();
    ft.replace(R.id.current_layout, newFragment,"Order");
    ft.commit();
    

    您可以点击此链接 ..click

    【讨论】:

    • 我试过了。为此,我们需要在活动布局中添加一个 ,我不想添加任何片段,因为我的布局中会有很多东西。 @Tanim。
    • 在活动布局中添加一个 这是什么意思...你不需要在你的主要活动中添加任何东西...当你创建一个 newFragment 时会创建完全不同的布局文件...
    • @SomnathPal 你的意思是覆盖部分屏幕的东西吗?片段是可以托管在基础活动中的活动的一部分。这个基础活动可以有多个片段。我认为您的问题需要更多解释...!!!
    • @SomnathPal 你不需要在布局文件中添加&lt;fragment&gt; 元素:Tanim 的方法是动态的Fragment。但是,您需要将id 属性分配给您的根布局(在本例中为LinearLayout)以替换此示例中的R.id.order_navigation_frameLayout - 或者您可以使用android.R.id.content
    • 我想要他们在个人资料页面中拥有的类似 Instagram 的设置。当您单击设置图标时,将打开一个新布局,但它不会覆盖底部导航选项卡。我想做同样的动作。
    猜你喜欢
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 2020-05-19
    • 2011-07-13
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2014-03-29
    相关资源
    最近更新 更多