我是android开发的新手。在我的应用程序中有两个选项卡(我使用查看分页器来开发此选项卡),每个选项卡包含列表(FragmentA和FragmentC)(我使用 listfragment )。当按下/单击两个选项卡中的每个列表项时,它将导航到新片段(FragmentB)并显示所有包含的已单击列表视图项。
我使用Communicator接口来传递片段和主要活动。第一个片段将数据传递给主要活动,然后活动将数据传递给第二个片段。
我的问题: 第一个片段(FragmentA- listfragment)将数据传递给main actitvty。但是当主要活动试图将数据传递给第二个片段(FragmentB)时,它会给出错误。 FragmentA无法转换为FragmentB。我试着找了几天的解决方案。但我无法为此找到合适的解决方案。
Communicator界面
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无法强制转换为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);
答案 0 :(得分:1)
您没有将FragmentB附加到Activity。流程应该是这样的
1.创建一个包含viewpager的片段(ViewPagerFragment.java)
2.在活动(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)
@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);
}
}