我遇到的一个问题是,我很难抓住MainActivity Viewpager片段的子片段。我正在使用View Pager在选项卡式活动中实现主从视图。
在ListView中单击一个项目时,HandleCallback被触发,并尝试从MainActivity调用该片段的子片段,该子片段返回一个空引用。
下面的代码块返回空值。
@Override
public void loadImage(int imageSrc) {
// Returns null. How to get a reference of a fragment child fragment?
ImageDetailFragment imageDetailFragment = (ImageDetailFragment) getSupportFragmentManager().findFragmentById(R.id.image_detail_fragment);
if(imageDetailFragment != null){
imageDetailFragment.setImageView(imageSrc);
}
}
请在下面找到完整的实现。非常感谢您的帮助。我仍在学习android,它是一个全新的领域。
MainActivity。
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
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.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements HandleCallBack{
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
@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);
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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void loadImage(int imageSrc) {
// Returns null. How to get a reference of a fragment child fragment?
ImageDetailFragment imageDetailFragment = (ImageDetailFragment) getSupportFragmentManager().findFragmentById(R.id.image_detail_fragment);
if(imageDetailFragment != null){
imageDetailFragment.setImageView(imageSrc);
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position){
case 0: {
Tab1 tab1 = new Tab1();
return tab1;
}
case 1: {
Tab2 tab2 = new Tab2();
return tab2;
}
case 2: {
MasterDetailFragment masterDetailFragment = new MasterDetailFragment();
return masterDetailFragment;
}
}
return null;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
MasterDetailFragment.java
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MasterDetailFragment extends Fragment{
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.master_detailfragment, container, false);
return view;
}
}
ImageListFragment.java
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
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.ArrayAdapter;
import android.widget.ListView;
public class ImageListFragment extends Fragment {
private int[] imageSrc = new int[]{
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3,
R.drawable.pic4,
R.drawable.pic5,
R.drawable.pic6,
R.drawable.pic7
};
private String[] imageNames = new String[]{
"pic1",
"pic2",
"pic3",
"pic4",
"pic5",
"pic6",
"pic7"
};
private HandleCallBack handleCallBack;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof HandleCallBack){
handleCallBack = (HandleCallBack) context;
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.image_listfragment, container, false);
ListView imageListView = (ListView) viewGroup.findViewById(R.id.imagelist);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, imageNames);
imageListView.setAdapter(adapter);
imageListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
handleCallBack.loadImage(imageSrc[position]);
}
});
return viewGroup;
}
}
ImageDetailFragment.java
import android.media.Image;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageDetailFragment extends Fragment {
private ImageView imageView;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.image_detailfragment, container, false);
imageView = (ImageView) viewGroup.findViewById(R.id.mainimage);
return viewGroup;
}
public void setImageView(int imgResId) {
imageView.setImageResource(imgResId);
}
}
HandleCallback.java
public interface HandleCallBack {
public abstract void loadImage(int imageSrc);
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/appbar_padding_top"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:title="@string/app_name">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabItem
android:id="@+id/tabItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tab_text_1" />
<android.support.design.widget.TabItem
android:id="@+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tab_text_2" />
<android.support.design.widget.TabItem
android:id="@+id/tabItem3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tab_text_3" />
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
master_detailFragment.xml(纵向)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/masterDetailFragment">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/image_list_fragment"
android:name="ca.agnition.tabbedlayoutmasterdetail.ImageListFragment"
/>
</LinearLayout>
master_detailfragment.xml(横向)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:baselineAligned="false"
android:id="@+id/masterDetailFragment">
<fragment
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:id="@+id/image_list_fragment"
android:name="ca.agnition.tabbedlayoutmasterdetail.ImageListFragment" />
<fragment
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="match_parent"
android:id="@+id/image_detail_fragment"
android:name="ca.agnition.tabbedlayoutmasterdetail.ImageDetailFragment" />
</LinearLayout>
image_detailfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/img_name"
android:padding="10sp"
android:background="@android:color/black"
android:textColor="@android:color/white"
android:gravity="center"
android:layout_alignParentTop="true"
android:id="@+id/title"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/mainimage"
android:contentDescription="@string/app_name"
android:layout_below="@+id/title"
android:src="@drawable/pic1"/>
</RelativeLayout>
image_listfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/imagelist"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</LinearLayout>
是的!所以我终于弄清楚了我的问题。而且我对代码进行了一些更改。
在ImageListFragment.java中,我更改了onAttach方法,并指出它要检查HandleCallBack是ParentFragment的实例,该实例是MasterDetailFragment,如果是,则将其初始化。
@Override
public void onAttach(Context context) {
super.onAttach(context);
if(getParentFragment() instanceof HandleCallBack){
handleCallBack = (HandleCallBack) getParentFragment();
}
}
在MasterDetailFragment.java中,在覆盖loadImage方法中,我使用getChildFragment来获取image_detail_fragment鞭子,就像魔术一样。
在此之后,现在我还有另一个问题需要以纵向模式加载细节视图。当用户单击列表上的项目时,其详细信息视图应以一个单独的片段打开。为此,我创建了一个新的片段,其布局如下。
ImageListDetailFragment.java
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageListDetailFragment extends Fragment {
public static ImageListDetailFragment newInstance(int position) {
ImageListDetailFragment fragment = new ImageListDetailFragment();
// fragment.position = position;
return fragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.image_listdetailfragment, container, true);
ImageDetailFragment imageDetailFragment = (ImageDetailFragment) getFragmentManager().findFragmentById(R.id.image_detail_fragment);
ActionBar actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("back");
Bundle bundle = this.getArguments();
if(bundle != null){
imageDetailFragment.setImageView(bundle.getInt(MasterDetailFragment.IMAGE_ID));
}
return viewGroup;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home){
((AppCompatActivity)getActivity()).finish();
}
return super.onOptionsItemSelected(item);
}
}
image_listdetailfragment.java
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/image_list_detail_fragment"
android:name="ca.agnition.tabbedlayoutmasterdetail.ImageListDetailFragment" />
</LinearLayout>
然后在MasterDetailFragment中,我单击列表上的一个项目,首先,它检查设备是否处于横向模式,然后初始化image_detail_fragment,如果不是,则加载image_listdetailfragment以在单独的片段中显示细节。下面是方法。
@Override
public void loadImage(int imageSrc) {
if (getChildFragmentManager().findFragmentById(R.id.image_detail_fragment) != null) {
ImageDetailFragment imageDetailFragment = (ImageDetailFragment) getChildFragmentManager().findFragmentById(R.id.image_detail_fragment);
imageDetailFragment.setImageView(imageSrc);
} else {
ImageListDetailFragment ImageListDetailFragment = (ImageListDetailFragment) getFragmentManager().findFragmentById(R.id.image_list_detail_fragment);
Bundle bundle = new Bundle();
bundle.putInt(IMAGE_ID, imageSrc);
ImageListDetailFragment.setArguments(bundle);
}
}
但是同样,ImageListDetailFragment从getFragmentManager()。findFragmentById(R.id.image_list_detail_fragment);获取空引用
我也尝试过使用以下方法。
ImageListDetailFragment imageListDetailFragment = new ImageListDetailFragment();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.container, imageListDetailFragment).commit();
但是这也不起作用。我不确定这是否是正确的方法。因此,我们非常感谢您的帮助,如果您有更好的方法在ViewPager内实现Master-Detail视图或可以参考的工作示例,请提出建议。
谢谢!