我有一个 AppCompatActivity 和一些 fragment 。操作栏上的后退按钮在 AboutFragment 中不起作用。
Activity 没有展开菜单,而 Fragment 在操作栏中只有一个后退按钮。
fragment 菜单可见,但点击后退按钮时完全没有反应。
点击操作栏中的信息图标会显示 AboutFragment。
当点击 i 图标时,下面的方法在 MainActivity 中运行。
@Override
public void onInfoSelected() {
abf = (AboutFragment) getSupportFragmentManager().findFragmentByTag(ABOUT_FRAGMENT_TAG);
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
// ft.hide(pf);
//ft.hide(cf);
ft.hide(tlf);
ft.show(abf);
ft.addToBackStack(null);
ft.commit();
}
然后 AboutFragment 中的后退按钮不会调用 Fragment 中的 onOptionsItemSelected() 方法。
调试时,我可以看到 Fragment 和 Activity 的 onCreateOptionsMenu() 都被调用了,但是当点击按钮时,没有 onOptionsItemSelected() 被调用,既不是来自 Activity 也不是来自 Activity来自 fragment 。
这两天我一直在搜索和谷歌搜索,但没有任何效果。 将不胜感激。
Activity Java 代码
package me.declangao.jiasazsales.app;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import me.declangao.jiasazsales.R;
import me.declangao.jiasazsales.model.Post;
public class MainActivity extends AppCompatActivity implements
RecyclerViewFragment.PostListListener, PostFragment.PostListener,
TabLayoutFragment.TabLayoutListener, SearchResultFragment.SearchResultListener,
CommentFragment.CommentListener,AboutFragment.AboutListener {
private static final String TAG = MainActivity.class.getSimpleName();
public static final String TAB_LAYOUT_FRAGMENT_TAG = "TabLayoutFragment";
public static final String POST_FRAGMENT_TAG = "PostFragment";
public static final String COMMENT_FRAGMENT_TAG = "CommentFragment";
public static final String ABOUT_FRAGMENT_TAG = "AboutFragment";
private FragmentManager fm = null;
private TabLayoutFragment tlf;
private PostFragment pf;
private CommentFragment cf;
private SearchResultFragment srf;
private AboutFragment abf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
fm = getSupportFragmentManager();
// Setup fragments
tlf = new TabLayoutFragment();
pf = new PostFragment();
cf = new CommentFragment();
srf = new SearchResultFragment();
abf=new AboutFragment();
FragmentTransaction ft = fm.beginTransaction();
ft.add(android.R.id.content, abf, ABOUT_FRAGMENT_TAG);
ft.add(android.R.id.content, pf, POST_FRAGMENT_TAG);
ft.add(android.R.id.content, cf, COMMENT_FRAGMENT_TAG);
ft.add(android.R.id.content, tlf, TAB_LAYOUT_FRAGMENT_TAG);
ft.hide(pf);
ft.hide(cf);
ft.hide(abf);
ft.show(tlf);
ft.commit();
}
/**
* Invoked when a post in the list is selected
*
* @param post Selected Post object
*/
@Override
public void onPostSelected(Post post, boolean isSearch) {
// Find the fragment in order to set it up later
pf = (PostFragment) getSupportFragmentManager().findFragmentByTag(POST_FRAGMENT_TAG);
// Set necessary arguments
Bundle args = new Bundle();
args.putInt("id", post.getId());
args.putString("title", post.getTitle());
args.putString("date", post.getDate());
args.putString("author", post.getAuthor());
args.putString("content", post.getContent());
args.putString("url", post.getUrl());
//args.putString("thumbnailUrl", post.getThumbnailUrl());
args.putString("featuredImage", post.getFeaturedImageUrl());
// Configure PostFragment to display the right post
pf.setUIArguments(args);
// Show the fragment
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
if (!isSearch) { // Hide TabLayoutFragment if this is not search result
ft.hide(tlf);
} else { // Otherwise, hide the search result, ie. SearchResultFragment.
ft.hide(srf);
}
ft.show(pf);
ft.addToBackStack(null);
ft.commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//do something here like
Log.e("menu Test","rom Main activity");
int backStackEntryCount
=getSupportFragmentManager().getBackStackEntryCount();
if (backStackEntryCount > 0) {
getSupportFragmentManager().popBackStack();
}
return true;
}
return false;
}
/**
* Invoked when a search query is submitted
*
* @param query Selected Post object
*/
@Override
public void onSearchSubmitted(String query) {
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
// Send query to fragment using factory method
srf = SearchResultFragment.newInstance(query);
ft.add(android.R.id.content, srf);
ft.hide(tlf);
ft.addToBackStack(null);
ft.commit();
}
@Override
public void onInfoSelected() {
abf = (AboutFragment) getSupportFragmentManager().findFragmentByTag(ABOUT_FRAGMENT_TAG);
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
// ft.hide(pf);
//ft.hide(cf);
ft.hide(tlf);
ft.show(abf);
ft.addToBackStack(null);
ft.commit();
}
/**
* Invoked when comment menu is selected
*
* @param id ID of the article, assigned by WordPress
*/
@Override
public void onCommentSelected(int id) {
cf = (CommentFragment) getSupportFragmentManager().findFragmentByTag(COMMENT_FRAGMENT_TAG);
Bundle args = new Bundle();
args.putInt("id", id);
// Setup CommentFragment to display the right comments page
cf.setUIArguments(args);
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
ft.hide(pf);
//ft.hide(abf);
ft.show(cf);
ft.addToBackStack(null);
ft.commit();
}
/**
* Intercept back button event, reset ActionBar if necessary
*/
@Override
public void onBackPressed() {
resetActionBarIfApplicable();
super.onBackPressed();
}
/**
* Simulate a back button press when home is selected
*/
@Override
public void onHomePressed() {
resetActionBarIfApplicable();
fm.popBackStack();
}
/**
* Reset TabLayoutFragment's ActionBar if necessary
*/
private void resetActionBarIfApplicable() {
Log.d(TAG, "SearchResultFragment is visible: " + srf.isHidden());
if (srf.isVisible()) {
tlf.resetActionBar();
}
}
// Commented out coz we will let fragments handle their own Options Menus
/*
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
//Log.e("Erroraaa","aaaaa");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.e("menu","activity: action home has clicked");
switch (item.getItemId()){
case android.R.id.home:
onBackPressed();
return false;
}
return super.onOptionsItemSelected(item);
}
*/
}
AboutFragment
package me.declangao.jiasazsales.app;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import me.declangao.jiasazsales.R;
/**
* Fragment to display a Info about Jiasaz company.
* Activities that contain this fragment must implement the
* {@link AboutFragment.AboutListener} interface
* to handle interaction events.
*/
public class AboutFragment extends Fragment {
private AboutListener mListener;
private Toolbar toolbar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
this.setHasOptionsMenu(true);
}
// @Override
// public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Log.e("Menu:created","Menu");
//
//// super.onCreateOptionsMenu(menu, inflater);
//// menu.clear();
// inflater.inflate(R.menu.menu_post, menu);
// super.onCreateOptionsMenu(menu, inflater);
// }
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.e("Menu:selected","Menu");
if (item.getItemId() == android.R.id.home) {
mListener.onHomePressed();
}
return false;
}
public AboutFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.about_layout, container, false);
toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((MainActivity) getActivity()).setSupportActionBar(toolbar);
((MainActivity) getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
((MainActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((MainActivity) getActivity()).getSupportActionBar().setTitle( "www.Jiasaz.com");
Log.e("Menu: fragment created","onCreaate()");
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (AboutListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement AboutListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface AboutListener {
void onHomePressed();
//void onInfoSelected();
}
}
这是我的 AboutFragment xml 代码
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent"
android:layoutDirection="rtl"
android:textDirection="rtl"
tools:context="me.declangao.jiasazsales.app.AboutFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layoutDirection="rtl"
android:textDirection="rtl"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
android:layoutDirection="rtl"
android:textDirection="rtl"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layoutDirection="rtl"
android:textDirection="rtl"
android:padding="15dp"
android:orientation="vertical">
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
android:text="ئهم ئاپه لهلایهن كۆمپانیای جیاساز دروست كراوه"
android:textAppearance="@style/TextAppearance.AppCompat.Light.SearchResult.Title" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="214dp"
android:src="@drawable/jiasazlogo" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
android:text="كۆمپانیای جیاساز بۆ خزمهتگوزاری و چارهسهری تهكنهلۆجی، دروستكردنی وێبسایت و ئاپی مۆبایل و سیستهمی دام و دهزگاكان و ماركێتهكان"
android:textAppearance="@style/TextAppearance.AppCompat.Light.SearchResult.Title" />
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="all"
android:clickable="true"
android:text="@string/link"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Body1"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
</FrameLayout>
最佳答案
您可以设置 OnMenuItemClickListener 的实例直接在Toolbar .请记住,您不应使用 Activity.setSupportActionBar(Toolbar) .
public class AboutFragment extends Fragment {
// ...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.about_layout, container, false);
toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.menu_about_fragment);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.some_menu) {
// do sth...
return true; // event is handled.
}
return false;
}
});
// ...
}
// ...
}
.
启用独立的后退按钮Toolbar , 在 xml 中设置其默认图标文件使用 app:navigationIcon="?attr/homeAsUpIndicator" :
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
android:layoutDirection="rtl"
android:textDirection="rtl"
app:navigationIcon="?attr/homeAsUpIndicator" />
然后为其设置一个监听器
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// back button is pressed
mListener.onHomePressed();
}
});
关于java - onOptionsItemSelected() 方法未在 Fragment 上调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53354085/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案
我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby1.9+ 关于ruby-主要:Objectwhenrun
我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)