GVKun编程网logo

Android Fragment getArguments()返回null(android gettext返回类型)

30

想了解AndroidFragmentgetArguments()返回null的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于androidgettext返回类型的相关问题,此外,我们还将为您

想了解Android Fragment getArguments()返回null的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于android gettext返回类型的相关问题,此外,我们还将为您介绍关于android 3.0中的getSupportFragmentManager()与getFragmentManager()、Android FindFragmentById 返回值总是null、Android Fragment FragmentTabHost 问题、Android Fragment getActivity null 解决的新知识。

本文目录一览:

Android Fragment getArguments()返回null(android gettext返回类型)

Android Fragment getArguments()返回null(android gettext返回类型)

正如标题所示.
我从这里下载了片段代码,http://developer.android.com/shareables/training/FragmentBasics.zip.
这是来自Android官方开发者网站的片段示例. http://developer.android.com/training/basics/fragments/fragment-ui.html

这是MainActivity.java的onCreate():

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_articles);

    // Check whether the activity is using the layout version with
    // the fragment_container FrameLayout. If so, we must add the first fragment
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a prevIoUs state,
        // then we don't need to do anything and should return or else
        // we Could end up with overlapping fragments.
        if (savedInstanceState != null) {
            return;
        }

        // Create an instance of ExampleFragment
        HeadlinesFragment fragment = new HeadlinesFragment();

        // In case this activity was started with special instructions from an Intent,
        // pass the Intent's extras to the fragment as arguments
        //fragment.setArguments(getIntent().getExtras());
        Bundle args= new Bundle();
        args.putString("category", "clothes");
        args.putString("item", "shirts");
        fragment.setArguments(args);

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment).commit();
    }
}

和HeadlinesFragment.java的onCreate():

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // We need to use a different list item layout for devices older than Honeycomb
    int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
            android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

    Bundle args = getArguments();
    if (args == null) {
        Toast.makeText(getActivity(), "arguments is null " , Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getActivity(), "text " + args , Toast.LENGTH_LONG).show();
    }        

    // Create an array adapter for the list view, using the Ipsum headlines array
    setlistadapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));

}

我在这里读了几个QA,比如这个@L_301_2@,以及与setArguments()和getArguments()相关的许多其他QA,但我仍然被卡住了.

我已经将Bundle和Toast代码移动到onAttach()和onCreateView(),但没有用.我的代码有什么问题?我想我错过了什么,但不知道它是什么.
请帮忙!谢谢.

编辑:
我会更清楚地表明我的意图.在我下载的FragmentBasic中,有MainActivity.java,HeadlinesFragment.java和ArticlesFragment.java.从MainActivity.java到ArticlesFragment.java的“通信”不是问题.我想要的是将数据从MainActivity.java发送到HeadlinesFragment.java.他们的联系是这样的:

--------------------------------------
| MainActivity <-> HeadlinesFragment |
|      |                             |
|      |>> ArticlesFragment          |
--------------------------------------

HeadlinesFragment正在运行时运行.

*当使用带有<的Android小工具时,这些代码可以正常工作600px宽度.但是在平板电脑上使用时不起作用(> = 600px),正如下面@ Tesla1984所证明的那样.但我想要的是小工具< 600px和小工具> 600px的.

解决方法:

@tonny

我下载了FragmentBasics.zip.我只更改参数名称.代码和结果图片.

主要活动

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_articles);

    // Check whether the activity is using the layout version with
    // the fragment_container FrameLayout. If so, we must add the first fragment
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a prevIoUs state,
        // then we don't need to do anything and should return or else
        // we Could end up with overlapping fragments.
        if (savedInstanceState != null) {
            return;
        }

        // Create an instance of ExampleFragment
        HeadlinesFragment fragment = new HeadlinesFragment();

        // In case this activity was started with special instructions from an Intent,
        // pass the Intent's extras to the fragment as arguments
//            firstFragment.setArguments(getIntent().getExtras());
        //test
        Bundle args= new Bundle();
        args.putString("category", "clothes");
        args.putString("item", "shirts");
        fragment.setArguments(args);

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment).commit();
    }
}

HeadlinesFragment

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // We need to use a different list item layout for devices older than Honeycomb
    int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
            android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

    Bundle args = getArguments();
    if (args == null) {
        Toast.makeText(getActivity(), "arguments is null " , Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getActivity(), "text " + args , Toast.LENGTH_LONG).show();
    }    

    // Create an array adapter for the list view, using the Ipsum headlines array
    setlistadapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));
}

这是结果

android 3.0中的getSupportFragmentManager()与getFragmentManager()

android 3.0中的getSupportFragmentManager()与getFragmentManager()

在 android.support.v4.app.FragmentManager的文档中:

“框架的FragmentManager的静态库支持版本.用于编写在Android 3.0之前的平台上运行的应用程序.在Android 3.0或更高版本上运行时,仍然使用此实现;它不会尝试切换到框架的实现.请参阅用于类概述的框架SDK文档.“

那么,我是否需要在运行时进行检查并使用适当的FragmentManager来运行应用程序的Android版本?即如果在android 3.0而不是getSupportFragmentManager()上调用getFragmentManager()

解决方法

只要您导入了支持库,在Android 3.0上使用getSupportFragmentManager()就没有错.如果你想对SDKs 11使用getFragmentManager(),那就去吧;请记住,如果使用版本检查,您可能会使用大量代码.

Android FindFragmentById 返回值总是null

Android FindFragmentById 返回值总是null

package com.text.fragmentbestpractice;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class TitleFragment extends Fragment implements OnItemClickListener{
	private ArrayList<News> newslist;
	private TitileAdapter newsAdapter;
	private ListView newsTitleListView;
	private boolean istwoPane;
	public void onAttach(Activity activity){
		super.onAttach(activity);
		newslist=setNews();
		newsAdapter=new TitileAdapter(activity,R.layout.newsitem,newslist);
	}
	@Override
	public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
		View view=inflater.inflate(R.layout.newslist, container,false);
		newsTitleListView=(ListView)view.findViewById(R.id.newslist_view);
		newsTitleListView.setAdapter(newsAdapter);
		newsTitleListView.setOnItemClickListener(this);
		return view;
		
	}
	public void onActivityCreated(Bundle savedInstanceState){
		super.onActivityCreated(savedInstanceState);
		if(getActivity().findViewById(R.id.news_content_layout1)!=null){
		//为双页显示
			istwoPane=true;
		}else{
			istwoPane=false;
		}
	}
	
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO 自动生成的方法存根
		News news=newslist.get(position);
		if(istwoPane){
			ContextFragment newContentFragment=(ContextFragment)getFragmentManager().findFragmentById(R.id.newcontext11); //为什么getFragmentManager().findFragmentById返回值总是null
			if(newContentFragment==null){
				Log.e("MyFragment", "newContentFragment is null");
				return;
			}
			newContentFragment.refresh(news.getTitle(), news.getContext());
			
		}else{
			NewsContextActivity.actionStart(getActivity(), news.getTitle(), news.getContext());
		}
	}
	public ArrayList<News> setNews(){
		newslist=new ArrayList<News>();
		News news1=new News();
		news1.setTitle("Android is Winner");
		news1.setContext("Android is Winner");
		newslist.add(news1);
		News news2=new News();
		news2.setTitle("Google Android exec poached by China''s Xiaomi");
		news2.setContext("China''s Xiaomi has poached a key Google executive for the rapidly growing Chinese smartphone maker.");
		newslist.add(news2);
		return newslist;
	}
	
}

安卓大神请问,为什么getFragmentManager().findFragmentById返回值总是null



Android Fragment FragmentTabHost 问题

Android Fragment FragmentTabHost 问题

今天需要做一个功能,实现 tab 切换功能,但是又不能向 viewpager 一样可以滑动,只能通过顶部的 tab 标签滑动,就是类似 ActionBar 的 tab 一样的切换。

然后我就去找例子,在 ApiDemos 中有 FragmentTabs(extends Activity),FragmentTabsFragment (extends Fragment),两个例子,特别说一下 FragmentTabsFragment,这个类中的 TabManager 是重写了 FragmentTabHost,自己实现的状态保存等等,值得参考一下,当然,这个类也参考了 FragmentTabHost 的实现。

在 Support4Demos 中,有 FragmentTabs (extends FragmentActivity),FragmentTabsFragmentSupport (extends Fragment);

我主要参考的是 FragmentTabsFragmentSupport,因为我想用 Fragment 去实现我的需求。

 遇到的几个问题:

1.FragmentTabHost 的顶部 tab 样式是系统的,不符合我的要求,那么如何定制这个样式呢?

你一定是这样使用的:

mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator(“simple”), ArrayListFragment.class, null);

如果要改这个 tab 的样式,可以这样:

Button simple = new Button(getActivity());
simple.setText("xxx");
simple.setTextColor(this.getResources().getColor(R.color.green));
// simple.setBackgroundColor(R.color.indicate);
simple.setBackgroundResource(R.drawable.ic_star_p);
// set padding
// simple.setPadding(150, 150, 0, 0);
// set margin
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
0, LinearLayout.LayoutParams.MATCH_PARENT, 1);  // 1 是可选写的
lp.setMargins(150, 50, 0, 50);
simple.setLayoutParams(lp);

看到了吧,可以设置 padding, margin, background 等。。。

然后 -》setIndicator (View view), 看到了吧,有个方法是支持自定义 view 的,所以我们就可以自定义一个 view,比如,把上面定义的 Button simple 传进去就可以了。

还可以设置 TabWidget 的高度和背景:

mTabHost.getTabWidget().setBackgroundResource(R.drawable.ic_new_tab_p);

mTabHost.getTabWidget().setMinimumHeight(300);
mTabHost.getTabWidget().setDividerDrawable(null);

2. 多个 tab 切换的时候,每次都会从新执行:onCreateView,onDestroyView,导致比如 listview 这种无法保存浏览的位置?

我是这样解决的:

if (rootView == null) {
rootView = inflater.inflate(R.layout.fragment_pager_list, container, false);
}
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}

View tv = rootView.findViewById(R.id.text);
((TextView)tv).setText("Fragment #" + mNum);
return rootView;


测试代码下载地址:

http://download.csdn.net/detail/song_shi_chao/7168045

参考:

http://www.cnblogs.com/asion/archive/2013/09/25/3339313.html

http://ar.newsmth.net/thread-ffd9fb821607d1.html

http://www.eoeandroid.com/thread-322096-1-1.html

http://www.byywee.com/page/M0/S910/910755.html

http://blog.csdn.net/renpengben/article/details/12615487(我使用了这种方法)

http://www.2cto.com/kf/201309/242225.html

http://www.eoeandroid.com/thread-153696-1-1.html(ViewPager 与其中的子 View 滑动冲突该如何解决


Android Fragment getActivity null 解决

Android Fragment getActivity null 解决

解决这个办法:

  1. 直接在 activity. onsaveinstance 那里直接把重写:

@Override
protected void onSaveInstanceState(Bundle outState) {
	// TODO Auto-generated method stub
	//super.onSaveInstanceState(outState);
}

这样的话,就 fragment 就会直接跟 activity 一起销毁了、

2. 直接在初始化 fragment 的时候 把 activity 保存下来,在使用的时候 要判定一下。

@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = activity;
    }



今天关于Android Fragment getArguments()返回nullandroid gettext返回类型的讲解已经结束,谢谢您的阅读,如果想了解更多关于android 3.0中的getSupportFragmentManager()与getFragmentManager()、Android FindFragmentById 返回值总是null、Android Fragment FragmentTabHost 问题、Android Fragment getActivity null 解决的相关知识,请在本站搜索。

本文标签: