gpt4 book ai didi

java - viewpager 中的 fragment 转换问题

转载 作者:行者123 更新时间:2023-12-01 12:00:33 25 4
gpt4 key购买 nike

我是 Android 开发新手。在我的应用程序中有两个选项卡(我使用 view pager 来开发此选项卡),每个选项卡都包含列表(FragmentA 和 FragmentC)(我使用 listfragment)。当按下/单击两个选项卡中的每个列表项时,它会导航到新 fragment (FragmentB)并显示单击的 ListView 项的所有内容。

我使用了 Communicator 接口(interface)来传达 fragment 和主要 Activity 。第一个 fragment 将数据传递给主 Activity ,然后 Activity 将数据传递给第二个 fragment 。

我的问题:第一个 fragment (FragmentA-listfragment)将数据传递给主要 Activity 。但是当主要 Activity 尝试将数据传递给第二个 fragment (FragmentB)时,它会给出错误。 FragmentA 无法转换为 FragmentB。我花了几天时间试图找到解决方案。但我无法找到合适的解决方案。

通讯器接口(interface)

public interface Communicator {
void sendData(String msg);
}

FragmentA.java

package com.example.tab;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
* A simple {@link Fragment} subclass.
*
*/
public class FragmentA extends Fragment implements OnItemClickListener {

public FragmentA() {
// Required empty public constructor
}

ListView listView;
Communicator com;
View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_a, container, false);
listView = (ListView) view.findViewById(R.id.listView1);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.books, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
return view;
}


@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
com = (Communicator) getActivity();
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {

com.sendData("Hello");

}

}

FragmentB.java

package com.example.tab;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

/**
* A simple {@link Fragment} subclass.
*
*/
public class FragmentB extends Fragment {

public FragmentB() {
// Required empty public constructor
}

TextView textView;
Context context;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
context = getActivity().getBaseContext();
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_b, container, false);
textView= (TextView) view.findViewById(R.id.text1);
return view;
}

public void setData(String msg) {
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
textView.setText(msg);
}

}

MainActivity.java

package com.example.tab;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBarActivity;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity implements TabListener,
Communicator {

ViewPager viewPager;
ActionBar actionBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOnPageChangeListener(new OnPageChangeListener() {

public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
actionBar.setSelectedNavigationItem(arg0);
}

public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub

}

public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub

}
});
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setTitle("");

ActionBar.Tab tab1 = actionBar.newTab().setText("1-50")
.setTabListener(this);
ActionBar.Tab tab2 = actionBar.newTab().setText("50-100")
.setTabListener(this);

actionBar.addTab(tab1);
actionBar.addTab(tab2);
actionBar.setBackgroundDrawable(new ColorDrawable(0xff7e3e00));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub

}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub

}

@Override
public void sendData(String msg) {
// TODO Auto-generated method stub

try {
FragmentManager manager = getSupportFragmentManager();
FragmentB fragmentB = (FragmentB) manager
.findFragmentById(R.id.pager);
fragmentB.setData(msg);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
}

class MyAdapter extends FragmentPagerAdapter {

public MyAdapter(FragmentManager fm) {
super(fm);

}

@Override
public Fragment getItem(int arg0) {
Fragment fragment = null;

// TODO Auto-generated method stub

if (arg0 == 0) {
fragment = new FragmentA();
}
if (arg0 == 1) {
fragment = new FragmentC();
}
return fragment;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return 2;
}

}

activity_main.xml

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tab.MainActivity" >

</android.support.v4.view.ViewPager>

错误消息

com.example.tab.FragmentA cannot be cast to com.example.tab.FragmentB

完整的 Logcat:

01-18 13:21:03.380: D/AndroidRuntime(15257): Shutting down VM
01-18 13:21:03.380: W/dalvikvm(15257): threadid=1: thread exiting with uncaught exception (group=0x41572ba8)
01-18 13:21:03.390: E/AndroidRuntime(15257): FATAL EXCEPTION: main
01-18 13:21:03.390: E/AndroidRuntime(15257): Process: com.example.tab, PID: 15257
01-18 13:21:03.390: E/AndroidRuntime(15257): java.lang.ClassCastException: com.example.tab.FragmentA cannot be cast to com.example.tab.FragmentB
01-18 13:21:03.390: E/AndroidRuntime(15257): at com.example.tab.MainActivity.sendData(MainActivity.java:105)
01-18 13:21:03.390: E/AndroidRuntime(15257): at com.example.tab.FragmentA.onItemClick(FragmentA.java:52)
01-18 13:21:03.390: E/AndroidRuntime(15257): at android.widget.AdapterView.performItemClick(AdapterView.java:299)
01-18 13:21:03.390: E/AndroidRuntime(15257): at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
01-18 13:21:03.390: E/AndroidRuntime(15257): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2911)
01-18 13:21:03.390: E/AndroidRuntime(15257): at android.widget.AbsListView$3.run(AbsListView.java:3645)
01-18 13:21:03.390: E/AndroidRuntime(15257): at android.os.Handler.handleCallback(Handler.java:733)
01-18 13:21:03.390: E/AndroidRuntime(15257): at android.os.Handler.dispatchMessage(Handler.java:95)
01-18 13:21:03.390: E/AndroidRuntime(15257): at android.os.Looper.loop(Looper.java:136)
01-18 13:21:03.390: E/AndroidRuntime(15257): at android.app.ActivityThread.main(ActivityThread.java:5001)
01-18 13:21:03.390: E/AndroidRuntime(15257): at java.lang.reflect.Method.invokeNative(Native Method)
01-18 13:21:03.390: E/AndroidRuntime(15257): at java.lang.reflect.Method.invoke(Method.java:515)
01-18 13:21:03.390: E/AndroidRuntime(15257): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
01-18 13:21:03.390: E/AndroidRuntime(15257): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
01-18 13:21:03.390: E/AndroidRuntime(15257): at dalvik.system.NativeStart.main(Native Method)

调试后我可以看到这一行会发生错误

FragmentB fragmentB = (FragmentB) manager.findFragmentById(R.id.pager);

最佳答案

您没有将 FragmentB 附加到 Activity。流程应该是这样的

1.创建一个保存viewpager的fragment(ViewPagerFragment.java)

2.在activity(activity_main.xml)中你应该创建一个FrameLayout

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>

3.在 Activity 的 oncreate 方法中添加此代码,将 viewpager Fragment 添加到 Activity

   getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, new ViewPagerFragment())
.commit();

不要忘记将 viewpager 参数更改为 getChildFragmentManager()

4.从 FragmentA 列表中点击调用此方法,这将用新的 ViewPagerFragment(FragmentB) 替换 ViewPagerFragment

@Override
public void sendData(String msg) {
try {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.content_frame, new FragmentB().newInstance(msg));
transaction.addToBackStack(null);
transaction.commit();

} catch (Exception e) {
// TODO Auto-generated catch block
}
}

将 FragmentB 更改为此。

public class FragmentB extends Fragment {
private static final String ARG_PARAM1 = "param1";
String mParam;

public static FragmentB newInstance(String param1) {
FragmentB fragment = new FragmentB();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam = getArguments().getString(ARG_PARAM1);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_b, container, false);
}
}

关于java - viewpager 中的 fragment 转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28007844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com