Android中Fragment怎么addView?

Android中Fragment怎么addView?,第1张

Fragment是Android honeycomb 3.0新增的概念,在Android——Fragment介绍、Android

Fragment使用、Android FragmentManage

FragmentTransaction介绍中做了关于Fragment的详细介绍。这一片主要通过一个实例了解Fragment的使用。

先看一下布局文件(layout):

android:orientation=“horizontal” android:layout_width=“match_parent”

android:layout_height=“match_parent”>

class=“com.fragment.main.TitlesFragment”

android:id=“@+id/titles” android:layout_weight=“1″

android:layout_width=“0px” android:layout_height=“match_parent” />

android:layout_width=“0px” android:layout_height=“match_parent”

android:background=“?android:attr/detailsElementBackground” />

布局文件中使用了fragment标签和FrameLayout标签。Android Fragment使用

中介绍了2中嵌入Fragment的方法,这个实例中都用到,从布局文件看到有了fragment标签,这是一种使用方法,FrameLayout标签将会成为第二种加载fragment的载体view。

看一下程序实现(com.fragment.main.TitlesFragment):

public class TitlesFragment extends ListFragment {

int mCurCheckPosition = 0

int mShownCheckPosition = -1

@Override

public void onActivityCreated(Bundle savedInstanceState) {

super.onActivityCreated(savedInstanceState)

setListAdapter(new ArrayAdapter(getActivity(),

android.R.layout.simple_list_item_activated_1,

Shakespeare.TITLES))//使用静态数组填充列表

if (savedInstanceState != null) {

mCurCheckPosition = savedInstanceState.getInt(“curChoice”, 0)

mShownCheckPosition = savedInstanceState.getInt(“shownChoice”, -1)

}

getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE)

showDetails(mCurCheckPosition)

}

@Override

public void onSaveInstanceState(Bundle outState) {

super.onSaveInstanceState(outState)

outState.putInt(“curChoice”, mCurCheckPosition)

outState.putInt(“shownChoice”, mShownCheckPosition)

}

@Override

public void onListItemClick(ListView l, View v, int position, long id)

{

showDetails(position)

}

/**

*显示listview item 详情

*/

void showDetails(int index) {

mCurCheckPosition = index

getListView().setItemChecked(index, true)

if (mShownCheckPosition != mCurCheckPosition) {

DetailsFragment df = DetailsFragment.newInstance(index)

FragmentTransaction ft = getFragmentManager()

.beginTransaction()

ft.replace(R.id.details, df)

ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)

ft.commit()

mShownCheckPosition = index

}

}

}

TitlesFragment

TitlesFragment继承自Fragment的子类ListFragment,使用了一个静态数组填充列表,重写了onListItemClick方法,showDetails方法展示ListView

item的详情。

5DetailsFragment df =

DetailsFragment.newInstance(index)//获取详情Fragment的实例

FragmentTransaction ft =

getFragmentManager().beginTransaction()//获取FragmentTransaction 实例

ft.replace(R.id.details, df)//使用DetailsFragment 的实例

ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)

ft.commit()//提交

这里就使用到了Android Fragment使用中介绍的第二种加载fragment的方法。看一下DetailsFragment :

public class DetailsFragment extends Fragment {

/** * Create a new instance of DetailsFragment, initialized to * show the

text at ’index’. */

public static DetailsFragment newInstance(int index) {

DetailsFragment f = new DetailsFragment()

// Supply index input as an argument.

Bundle args = new Bundle()

args.putInt(“index”, index)

f.setArguments(args)

return f

}

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {

if (container == null) {

return null

}

ScrollView scroller = new ScrollView(getActivity())

TextView text = new TextView(getActivity())

int padding = (int) TypedValue.applyDimension(

TypedValue.COMPLEX_UNIT_DIP, 4, getActivity().getResources()

.getDisplayMetrics())

text.setPadding(padding, padding, padding, padding)

scroller.addView(text)

text.setText(Shakespeare.DIALOGUE[getArguments().getInt("index", 0)])

return scroller

}

}

DetailsFragment 中使用newInstance(int index)方法产生DetailsFragment

实例并接受整型参数,重载了onCreateView方法创建view。

这个例子基本完成了,主要介绍的是在3.0以后的使用方法,其实Fragment在SDK1.6之后就可以使用了,在1.6上使用需要借助

android-support-v4.jar包实现。android-support-v4.jar在:SDK根目录\extras\android

\compatibility\v4下可以找到,如果想了解Fragment在SDK1.6上怎么实现的请参考Fragment 在Android

SDK1.6上实现。

因为CordovaWebView 默认的初始化里判断了Content是不是继承CordovaInterface,如果直接使用Fragment继承CordovaInterface,CordovaInterface有个抽象方法getActicity ()和Fragment的相冲突了,并且Fragment的这个同名方法还是final的,无法覆盖。

查看CordovaWebView的源码,它是这样实现的。

public CordovaWebView(Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing) {

super(context, attrs, defStyle, privateBrowsing)

if (CordovaInterface.class.isInstance(context))

{

this.cordova = (CordovaInterface) context

}

else

{

Log.d(TAG, "Your activity must implement CordovaInterface to work")

}

this.setWebChromeClient(new CordovaChromeClient(this.cordova))

this.initWebViewClient(this.cordova)

this.loadConfiguration()

this.setup()

}

所以只要让CordovaWebView的Content是实现CordovaInterface的接口就可以了。

实现一个类继承接口CordovaInterface:

private ...因为CordovaWebView 默认的初始化里判断了Content是不是继承CordovaInterface,如果直接使用Fragment继承CordovaInterface,CordovaInterface有个抽象方法getActicity ()和Fragment的相冲突了,并且Fragment的这个同名方法还是final的,无法覆盖。

查看CordovaWebView的源码,它是这样实现的。

public CordovaWebView(Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing) {

super(context, attrs, defStyle, privateBrowsing)

if (CordovaInterface.class.isInstance(context))

{

this.cordova = (CordovaInterface) context

}

else

{

Log.d(TAG, "Your activity must implement CordovaInterface to work")

}

this.setWebChromeClient(new CordovaChromeClient(this.cordova))

this.initWebViewClient(this.cordova)

this.loadConfiguration()

this.setup()

}

所以只要让CordovaWebView的Content是实现CordovaInterface的接口就可以了。

实现一个类继承接口CordovaInterface:

private class CordovaContext extends ContextWrapper implements CordovaInterface {

Activity activity

protected final ExecutorService threadPool = Executors.newCachedThreadPool()

public CordovaContext(Activity activity) {

super(activity.getBaseContext())

this.activity = activity

}

public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {

//activity.startActivityForResult(command, intent, requestCode)

}

public void setActivityResultCallback(CordovaPlugin plugin) {

//activity.setActivityResultCallback(plugin)

}

public Activity getActivity() {

return activity

}

public Object onMessage(String id, Object data) {

return null

}

public ExecutorService getThreadPool() {

return threadPool

}

}

然后在Fragment的onCreateView方法里,更改默认的LayoutInflater inflater的content;

inflater = cloneInContext(new CordovaContext(mActivity);

这样就可以实现Fragment里正常使用CordovaWebView。

fragment 中的代码,

你只需要完成VPadapter中 具体实现,

getItem(int position) 获取你要实例化的Fragment

getCount() 返回要实例化的fragmnet个数。

@Override

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.activity_main, container, false)

    ViewPager vp = view.findViewById(R.id.viewpager)

    vp.setAdapter(new VPadapter(getFragmentManager()))

}

class VPadapter extends FragmentPagerAdapter {

    FragmentManager manager

    public VPadapter(FragmentManager fm) {

        super(fm)

        this.manager = fm

    }

    @Override

    public Fragment getItem(int position) {

        return new Fragment()

    }

    @Override

    public int getCount() {

        return 0

    }

}

有什么问题追问即可。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11263216.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-14
下一篇 2023-05-14

发表评论

登录后才能评论

评论列表(0条)

保存