viewpager嵌套多个Fragment并处理点击事件

前记:
本身自己对于fragment了解的就不太多,当自己半路插进项目组开始继续开发的时候,我发现了viewpager+fragment   而且做这个功能的那哥们儿告诉我说就差点击事件没实现了、、 我当时就菊花一紧,你大爷的,你做不出来的烂摊子让我这个不懂fragment的来收拾 让我情何以堪、、你都倒腾了半年了、心里虽然骂了特一顿,但是作为一个程序素养不错的咱,还是接过来了。

开始尝试:
一拿过代码我看的第一眼,我就又开始想骂了,只是画了个UI,连数据接口都没封装,这叫做的差不多了? 哎,原来显示的数据都是直接写在布局里的,服了。看重点,找到viewpager中的fragment,看了几个回调方法,看不大懂,找找文档,了解了下基本意思,开始真正尝试做监听、
直接在fragment中提取控件的同时对其进行了监听,没效果? 不是吧? 然后开始从各个方面找解答,有的人说是要写到viewPagerAdapter里面进行监听,有的人说要换成View,还有的说要、、 总之找了好多办法,通通试过,就是监听不到。
到群里讨论的时候,大家都说怎么可能,我把代码也贴上去了,基本都会所没有错,往往这种时候是最让人伤心欲绝的了,没有错,就是不能点!
怎么办? 各种debug,各种跟踪,就是不走点击,后来我单独写了个测试Demo,可以点击呀!!!
拓展视野:
僵持了一天多,这样不是办法呀、这还能一直耗着不成,先去联调接口去;过程中满脑子都是这个问题,百思不得其解;突然间想到了,程序中有手势滑动事件,会不会是焦点被劫持了! 好,抱着这个念头,回头把所有的尝试的代码全都给注释掉,就用fragment做测试! 我就不信了。把事件传递的回调函数的返回值全都返回TRUE,这样事件不就可以一直传递了吗、 将代码整理了下,果然可以点击了,我内心那个激动啊!!!

好了,探究过程代码如下:
1.单独抽出viewpager+fragment的Demo实现
主activity:

package com.k24.wheel;

import java.util.ArrayList;
import com.k24.wheel.adapter.MyViewPagerAdapter;
import com.k24.wheel.fragment.TestFragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;

public class TestViewPagerActivity extends FragmentActivity {

	private ViewPager viewPager;
	private ArrayList fragments;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_viewpager_ll);
		viewPager = (ViewPager) findViewById(R.id.my_viewpager);
		
		TestFragments fragmentItem;
		fragments = new ArrayList();
		for(int i = 0; i < 5; i++) {
			fragmentItem = new TestFragments(this, i, new String[]{"title"+(i+1), "contents"+(i+1)});
			fragments.add(fragmentItem);
		}
		MyViewPagerAdapter myPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager(), fragments);
		viewPager.setAdapter(myPagerAdapter);
		viewPager.setCurrentItem(0);
	}
	
}
Adapter:
package com.k24.wheel.adapter;

import java.util.ArrayList;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class MyViewPagerAdapter extends FragmentPagerAdapter {

	private ArrayList fragments;
	
	public MyViewPagerAdapter(FragmentManager fm, ArrayList fragments) {
		super(fm);
		this.fragments = fragments;
	}

	@Override
	public Fragment getItem(int arg0) {
		return fragments.get(arg0);
	}

	@Override
	public int getCount() {
		return fragments.size();
	}

}
具体要嵌套的fragment
package com.k24.wheel.fragment;

import com.k24.wheel.R;
import com.k24.wheel.WhellActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

@SuppressLint("ValidFragment")
public class TestFragments extends Fragment implements OnClickListener {

	private Context context;
	private int position;
	private String[] contentString;
	private TextView textView1;
	private TextView textView2;
	
	public TestFragments() {}
	
	public TestFragments(Context context, int position, String[] contentString) {
		this.context = context;
		Bundle bundle = new Bundle();
		bundle.putInt("position", position);
		bundle.putStringArray("contentString", contentString);
		setArguments(bundle);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle b = getArguments();
		if (b !=null) {
			position = getArguments().getInt("position");
			contentString = getArguments().getStringArray("contentString");
		}
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		textView1.setText(contentString[0]);
		textView2.setText(contentString[1]);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.test_fragment_ll, container, false);
		v.findViewById(R.id.fragment_btn).setOnClickListener(this);
		textView1 = (TextView) v.findViewById(R.id.fragment_textview1);
		textView1.setOnClickListener(this);
		textView2 = (TextView) v.findViewById(R.id.fragment_textview2);
		textView2.setOnClickListener(this);
		return v;
	}

	@Override
	public void onClick(View v) {
		Log.i("info_out", "have clicked the button in the fragment ");
		startActivity(new Intent(getActivity(), WhellActivity.class));
	}
	
}
跳转到的目标activity可以自己随意写个就好,这里不占空间了,略。
以上的Demo可以实现点击监听。

//===================分割线==================================
真正项目工程中自己改进之后的监听代码实现:

//初始化viewpager数据
	public void initViewPagerData(List hotIssuesList) {
		imgsList = new ArrayList();
		homepageFragments = new ArrayList();
		pagerViewList = new ArrayList();
		LinearLayout layout = (LinearLayout) findViewById(R.id.layout_title_imgs);
		HomePage2Fragment homePage2Fragment = null;
		ImageView img = null;
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		
		//将要分页显示的View装入数组中
//		LayoutInflater mLi = LayoutInflater.from(this);
//		for(int i = 0; i < 5; i++) {
//			pagerViewList.add(mLi.inflate(R.layout.homepage_2, null));
//		}
		
//		if(hotIssuesList != null) {
//			describeArr = new String[hotIssuesList.size()];
//			solutionArr = new String[hotIssuesList.size()];
			describeArr = new String[]{"title1","title2","title3","title4","title5"};
			solutionArr = new String[]{"content1_1","content1_2","content1_3","content1_4","content1_5",};
			for(int i = 0; i < 5; i++) {//hotIssuesList.size()
//				describeArr[i] = hotIssuesList.get(i).getHotDescirbe();//提取对应pager数据源。
//				solutionArr[i] = hotIssuesList.get(i).getHotSolution();
				img = new ImageView(this);//准备5个小图标。
				img.setScaleType(ScaleType.FIT_XY);
				img.setImageResource(img_ID);
				imgsList.add(img);
				img.setPadding(6, 3, 6, 3);
				layout.addView(img, params);
				homePage2Fragment = new HomePage2Fragment(this, i, new String[]{describeArr[i], solutionArr[i]});
//				homePage2Fragment = new HomePage2Fragment(this, i, new String[]{"title", "answer"});
				homepageFragments.add(homePage2Fragment);
//				ViewPagerItemView viewPagerItemView = new ViewPagerItemView(this, i, new String[]{"title", "answer"});
//				pagerViewList.add(viewPagerItemView);
			}
//			MyHomePagerAdapter mPagerAdapter = new MyHomePagerAdapter(this, pagerViewList, new String[]{"title", "content"});
//			homePager.setAdapter(mPagerAdapter);
			
			HomePageAdapter adapter = new HomePageAdapter(this, getSupportFragmentManager(), homepageFragments);
			homePager.setAdapter(adapter);
			homePager.setCurrentItem(0);
			imgsList.get(0).setImageResource(img_ID_ov);
			homePager.setOnPageChangeListener(new PageListener());
//		}
	}
其中从注释可以看出我当时解决问题过程的纠结、愤怒、绝望、挣扎、、、、
用到的具体fragment,把监听事件就写在这里面:
package com.broadtext.phreportfault.view;

import com.broadtext.phreportfault.MoreHotDetail;
import com.broadtext.phreportfault.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("ValidFragment")
public class HomePage2Fragment extends Fragment {
	
	private TextView tv_problem  , tv_answer;
	private int title;
	private String[] contentString;
 
	public HomePage2Fragment(){}
	
	public HomePage2Fragment(Context context, int i, String[] contentString) {
		Bundle bundle = new Bundle();
		bundle.putInt("title", i);
		bundle.putStringArray("contentString", contentString);
		setArguments(bundle);
	}

//	public static HomePage2Fragment newInstance(String[] content) {
//		HomePage2Fragment f = new HomePage2Fragment();
//		Bundle args = new Bundle();
//		args.putStringArray("content", content);
//		f.setArguments(args);
//		return f;
//	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		tv_problem.setText(contentString[0]);
		tv_answer.setText(contentString[1]);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle arg = getArguments();
		if (arg !=null) {
			title = getArguments().getInt("title");
			contentString = getArguments().getStringArray("contentString");
		}
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (container == null) {
			return null;
		}
		View v=inflater.inflate(R.layout.homepage_2, container,false);
		tv_problem=(TextView)v.findViewById(R.id.tv_problem);
		tv_problem.setFocusable(true);
		tv_problem.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				Toast.makeText(getActivity(), "点击了problems::"+contentString[0], Toast.LENGTH_LONG).show();
				Intent i = new Intent();
				i.putExtra("hotnews_discribe", contentString[0]);
				i.putExtra("hotnews_solution", contentString[1]);
				i.setClass(getActivity(), MoreHotDetail.class);
				getActivity().startActivity(i);
			}
		});
		tv_answer=(TextView)v.findViewById(R.id.tv_answer);
		tv_answer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				Toast.makeText(getActivity(), "点击了answer::"+contentString[1], Toast.LENGTH_LONG).show();
//				getActivity().startActivity(new Intent(getActivity(), MoreHotDetail.class));
				Intent i = new Intent();
				i.putExtra("hotnews_discribe", contentString[0]);
				i.putExtra("hotnews_solution", contentString[1]);
				i.setClass(getActivity(), MoreHotDetail.class);
				getActivity().startActivity(i);
			}
		});
		return v;
	}
	
}
pageradapter:
package com.broadtext.phreportfault.adapter;

import java.util.ArrayList;
import java.util.zip.Inflater;

import com.broadtext.phreportfault.R;
import com.broadtext.phreportfault.ReportFaultSelect_Detail;

import android.content.Context;
import android.content.Intent;
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.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class HomePageAdapter extends FragmentPagerAdapter {

//	private FragmentManager fm;
	private ArrayList fragments = null;
	private Context context;

	public HomePageAdapter(Context context, FragmentManager fm, ArrayList fragments) {
		super(fm);
		this.context = context;
		this.fragments = fragments;
	}

	@Override
	public Fragment getItem(int arg0) {
		return fragments.get(arg0);
	}

	@Override
	public int getCount() {
		return fragments.size();
	}
	
//	@Override
//	public boolean isViewFromObject(View arg0, Object arg1) {
//		return arg0 == arg1;
//	}
	
	@Override
	public Fragment instantiateItem(View container, int position) {
//		LayoutInflater inflater = LayoutInflater.from(context);
//		LayoutInflater inflater = LayoutInflater.from(context);
//		View v = inflater.inflate(R.layout.homepage_2, (ViewGroup) container);
		
//		View v =inflater.inflate(R.layout.homepage_2, (ViewGroup) container,false);
//		TextView tv_problem = (TextView)v.findViewById(R.id.tv_problem);
//		TextView tv_answer = (TextView)v.findViewById(R.id.tv_answer);
		
		switch (position) {
//		case 0:
//			tv_problem.setOnClickListener(new OnClickListener() {
//				@Override
//				public void onClick(View v) {
//					Toast.makeText(context, "点击了text_title", Toast.LENGTH_LONG).show();
//				}
//			});
			fragments.get(position).startActivity(new Intent(context, ReportFaultSelect_Detail.class));
//			
//			break;
		default:
			break;
		}
		
		return fragments.get(position);
	}
	
}
注释原班带上,我解决的过程果断比较惨痛,只是为了点击弹出那个提示、或者跳转,容易么我!!!
主activity中将能干扰到焦点传递的地方全部给置成TRUE!!!(关键代码) 
/**
	 * -----------------------------------手势监听----------------------------------------------
	 * 实现方法     onDown()、 onFling()、 onLongPress()、 onScroll()、onShowPress()、onSingleTapUp()、
	 */
	@Override
	public boolean onDown(MotionEvent e) {
		return true;
	}

	@Override
	public void onShowPress(MotionEvent e) {
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return true;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
		return true;
	}

	@Override
	public void onLongPress(MotionEvent e) {
	}

	private boolean isPushUp;
	private boolean isPullDown;
	
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		// 处理上推,下拉事件。
		if(e1.getY() - e2.getY() > 50) {//上推
			if(!isPushUp) {
				isPushUp = true;
				isPullDown = true;
				dynamicSetViewsHeightWhenPushUp();
			}
		} 
		
		if(e2.getY() - e1.getY() > 50) {//下拉
			if(isPullDown) {
				isPushUp = false;
				isPullDown = false;
				dynamicSetViewsHeightWhenPullDown();
			}
		}
		
		return true;
	}
	
	/**
	 * 触摸事件监听
	 * 此处是为了手势gesture监听做准备, 将触摸事件传递给gesture--
	 * gestureDetector.onTouchEvent(event)
	 */
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		return detector.onTouchEvent(event);
	}
好,基本上当你能够看到这篇文章的时候,肯定是也遇到了类似焦点问题,想必代码就不需要多做过多解释了,自己看上文。

实现感悟: 其实问题总是可以被解决的,尤其是面对你之前不曾接触过的,耐住性子,慢慢倒腾,肯定能解决,在Android的UI领域,应该没有什么解决不了的了,因为你碰到的其他人也肯定会碰到并在某处已经给出了解决办法,剩下的就是看你能不能找到,想通。

你可能感兴趣的:(Android开发)