Tổng hợp Vấn đề về Fragment trong android

Thảo luận trong 'Thảo luận về lập trình Android' bắt đầu bởi NgocDuy, 15/12/16.

  1. NgocDuy

    NgocDuy New Member

    Lượt xem: 242
    Chào mọi người, mình mới làm android có 1 số thắc mắc mong mọi người giúp đỡ.
    Tình hình là mình có 1 TrainingAdapter chứa file xml sau :
    Mã:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    	android:orientation="vertical"
    	android:layout_width="match_parent"
    	android:layout_height="match_parent"
    	android:background="@color/jv_background"
    	android:weightSum="1">
     
    	<LinearLayout
    		android:orientation="horizontal"
    		android:layout_width="fill_parent"
    		android:layout_height="wrap_content"
    		android:layout_marginTop="10dp">
     
    		<ImageView
    			android:layout_width="32dp"
    			android:layout_height="32dp"
    			android:id="@+id/imageView"
    			android:src="@drawable/user2" />
    		<TextView
    			android:layout_width="10dp"
    			android:layout_height="wrap_content"
    			android:textAppearance="?android:attr/textAppearanceLarge"
    			/>
     
    		<TextView
    			android:layout_width="wrap_content"
    			android:layout_height="wrap_content"
    			android:textAppearance="?android:attr/textAppearanceLarge"
    			android:hint="Tên UV"
    			android:id="@+id/txtName"
    			android:textColor="@color/list_divider"
    			android:layout_gravity="center_horizontal" />
     
     
    	</LinearLayout>
    	<LinearLayout
    		android:layout_width="match_parent"
    		android:layout_height="wrap_content"
    		android:layout_marginTop="10dp"
    		android:gravity="left"
    		android:orientation="horizontal">
     
    		<Button
    			android:layout_width="wrap_content"
    			android:layout_height="38dp"
    			android:text="Lịch sử"
    			android:textSize="16dp"
    			android:textStyle="bold"
    			android:focusable="false"
    			android:textColor="@color/button_text_color"
    			android:background="@drawable/custom_button_history"
    			android:id="@+id/btnHistory"  />
    		<Button
    			android:layout_width="wrap_content"
    			android:layout_height="38dp"
    			android:textColor="@color/button_text_color"
    			android:layout_marginLeft="10dp"
    			android:text="Đánh giá"
    			android:textSize="16dp"
    			android:textStyle="bold"
    			android:focusable="false"
    			android:background="@drawable/custom_button"
    			android:id="@+id/btnTest" />
     
    	</LinearLayout>
    	<LinearLayout
    		android:layout_width="match_parent"
    		android:orientation="horizontal"
    		android:layout_marginTop="10dp"
    		android:layout_height="3dp"
    		android:background="@color/light_gray" />
     
     
    </LinearLayout>
    
    Đây là code trong Adapter


    Mã:
    package vn.jupviec.frontend.android.monitor.app.ui.training;
     
    import android.app.Fragment;
    import android.content.Context;
    import android.content.Intent;
    import android.graphics.drawable.Drawable;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;
     
    import com.fasterxml.jackson.databind.ObjectMapper;
     
    import java.util.List;
     
    import butterknife.BindView;
    import butterknife.ButterKnife;
    import vn.jupviec.frontend.android.monitor.app.R;
    import vn.jupviec.frontend.android.monitor.app.domain.training.LeaderDTO;
    import vn.jupviec.frontend.android.monitor.app.domain.training.TrainingDTO;
    import vn.jupviec.frontend.android.monitor.app.domain.training.TrainingYesterdayDTO;
    import vn.jupviec.frontend.android.monitor.app.util.Constants;
    import vn.jupviec.frontend.android.monitor.app.util.Utils;
     
    /**
    * Created by MyPC on 11/10/2016.
    */
    public class TrainingAdapter extends ArrayAdapter<TrainingDTO> {
    	Context context;
    	int resource;
    	ListView listView;
    	List<TrainingDTO> objects;
     
    	private OnFragmentInteractionListener mListener;
    	public TrainingAdapter(Context context, int resource, List<TrainingDTO> objects, Fragment fragment) {
    		super(context, resource, objects);
    		this.context=context;
    		this.resource=resource;
    		this.objects=objects;
    		try {
    			mListener = (OnFragmentInteractionListener) fragment;
    		} catch (ClassCastException e) {
    			throw new ClassCastException(fragment.toString()
    					+ " must implement OnFragmentInteractionListener");
    		}
    	}
     
    	@Override
    	public View getView(int position, View convertView, ViewGroup parent) {
    		ViewHolder holder;
    		LayoutInflater inflater = (LayoutInflater) context
    				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    		View view = inflater.inflate(this.resource,null);
    		holder = new ViewHolder(view);
    		view.setTag(holder);
     
    		final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
    		final TrainingDTO trainingDTO = mapper.convertValue(this.objects.get(position), TrainingDTO.class);
    		final TrainingYesterdayDTO trainingYesterdayDTO = mapper.convertValue(this.objects.get(position), TrainingYesterdayDTO.class);
     
     
    		holder.tvName.setText(trainingDTO.getMaidName());
    		int maidId = trainingDTO.getMaidId();
     
    		holder.btnHistory.setOnClickListener(new View.OnClickListener() {
    			@Override
    			public void onClick(View v) {
    //				showHistory(trainingDTO);
    			}
    		});
    		holder.btnTest.setOnClickListener(new View.OnClickListener() {
    			@Override
    			public void onClick(View v) {
    				showComment(trainingDTO,trainingYesterdayDTO);
    			}
    		});
    		return view;
    	}
     
     
    	private void showComment(TrainingDTO trainingDTO, TrainingYesterdayDTO trainingYesterdayDTO) {
    		Intent intent = new Intent(getContext(),CommentActivity.class);
    		intent.putExtra(Constants.ARG_NAME_DETAIL,trainingDTO);
    		intent.putExtra(Constants.ARG_NAME_DETAIL_YESTERDAY,trainingYesterdayDTO);
    		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    		context.startActivity(intent);
    	}
     
    //	private void showHistory(TrainingDTO trainingDTO) {
    //		Intent intent = new Intent(getContext(),CandidateHistoryActivity.class);
    //		intent.putExtra(Constants.ARG_CANDIDATE_HISTORY_DETAIL,trainingDTO);
    //		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    //		context.startActivity(intent);
    //	}
     
    	static class ViewHolder {
    		@BindView(R.id.btnHistory) Button btnHistory;
    		@BindView(R.id.btnTest) Button btnTest;
    		@BindView(R.id.txtName) TextView tvName;
     
    		public ViewHolder(View view) {
    			ButterKnife.bind(this, view);
    		}
    	}
    	public interface OnFragmentInteractionListener {
     
    	}
     
    }
    Một FragmentTapNew chứ file xml sau:
    Mã:
    <?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:paddingLeft="@dimen/activity_horizontal_margin"
    	android:paddingRight="@dimen/activity_horizontal_margin"
    	android:paddingTop="@dimen/activity_vertical_margin"
    	android:paddingBottom="@dimen/activity_vertical_margin"
    	android:background="@color/jv_background"
    	android:orientation="vertical" >
     
    	<ListView
    		android:id="@+id/lvToday"
    		android:layout_width="match_parent"
    		android:layout_height="wrap_content"
    		android:divider="#00000000"
    		android:focusable="true">
     
    	</ListView>
     
    </LinearLayout>
    Đây là code trong Fragment


    Và 1 Activity TrainingActivity chứa file xml
    Mã:
    <android.support.v4.app.FragmentTabHost
    	xmlns:android="http://schemas.android.com/apk/res/android"
    	android:id="@android:id/tabhost"
    	android:layout_width="match_parent"
    	android:layout_height="match_parent" >
     
    	<LinearLayout
    		android:layout_width="match_parent"
    		android:layout_height="match_parent"
    		android:orientation="vertical" >
     
    		<TabWidget
    			android:id="@android:id/tabs"
    			android:layout_width="fill_parent"
    			android:layout_height="wrap_content"
    			android:layout_gravity="bottom"/>
     
    		<FrameLayout
    			android:id="@android:id/tabcontent"
    			android:layout_width="fill_parent"
    			android:layout_height="0dp"
    			android:layout_weight="1" />
    	</LinearLayout>
     
    </android.support.v4.app.FragmentTabHost>
    Code in fragment
    Mã:
    package vn.jupviec.frontend.android.monitor.app.ui.training;
    import android.app.Activity;
    import android.app.Fragment;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.ListView;
    import android.widget.Spinner;
    import android.widget.TextView;
    import java.sql.Timestamp;
    import java.util.List;
    import butterknife.BindView;
    import butterknife.ButterKnife;
    import butterknife.Unbinder;
    import retrofit.Callback;
    import retrofit.RetrofitError;
    import retrofit.client.Response;
    import vn.jupviec.frontend.android.monitor.app.R;
    import vn.jupviec.frontend.android.monitor.app.domain.ResultDTO;
    import vn.jupviec.frontend.android.monitor.app.domain.training.CandidateService;
    import vn.jupviec.frontend.android.monitor.app.domain.training.TrainingYesterdayDTO;
    import vn.jupviec.frontend.android.monitor.app.util.Constants;
    import vn.jupviec.frontend.android.monitor.app.ui.training.TrainingAdapter;
     
    /**
    * Created by Windows 10 Gamer on 09/12/2016.
    */
    public class FragmentTapNew extends Fragment{
    private static final String TAG = FragmentTapNew.class.getSimpleName();
    Activity myContext= null;
    @BindView(R.id.lvToday) ListView lvToday;
    private Unbinder unbinder;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.activity_candidate_training, container, false);
    unbinder = ButterKnife.bind(this, v);
    yesterday();
    return v;
    }
    public void yesterday() {
    String s = "a";
    CandidateService.getApiDummyClient(getActivity().getApplicationContext()).getCandidateYesterday(
    s,
    Constants.TRAINING,
    new Callback<ResultDTO>() {
    @Override
    public void success(ResultDTO resultDTO, Response response) {
    List<TrainingYesterdayDTO> trainingYesterdayDTOs = (List<TrainingYesterdayDTO>) resultDTO.getData();
    if (trainingYesterdayDTOs.size() == 0) {
    TextView textView = new TextView(getActivity().getApplicationContext());
    textView.setText(getString(R.string.msg_no_candidate_found));
    return;
    }
    lvToday.setAdapter(new TrainingYesterdayAdapter(getActivity().getApplicationContext(), R.layout.candidate_item, trainingYesterdayDTOs,FragmentTapNew.this));
    }
    @Override
    public void failure(RetrofitError error) {
    Log.e(TAG, "JV-ERROR: " + error.getMessage());
    Log.e(TAG, "JV-ERROR: " + error.getSuccessType());
    }
    });
    }
    @Override public void onDestroyView() {
    super.onDestroyView();
    unbinder.unbind();
    }
    // @Override
    // public void onAttach(Activity activity) {
    // myContext = activity;
    // super.onAttach(activity);
    // try {
    // mListener = (TrainingAdapter.OnFragmentInteractionListener) activity;
    // } catch (ClassCastException e) {
    // throw new ClassCastException(activity.toString()
    // + " must implement OnFragmentInteractionListener");
    // }
    // }
    }
    Đây là code trong Activity
    Mã:
    package vn.jupviec.frontend.android.monitor.app.ui.training;
     
    import android.app.FragmentTransaction;
    import android.os.Bundle;
     
     
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.FragmentTabHost;
     
     
    import vn.jupviec.frontend.android.monitor.app.R;
     
    /**
    * Created by Windows 10 Gamer on 09/12/2016.
    */
     
    public class TrainingActivity extends FragmentActivity {
    	private FragmentTabHost mTabHost;
     
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
     
    		setContentView(R.layout.activity_main);
    		mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
    		mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
    		mTabHost.addTab(
    				mTabHost.newTabSpec("Ư.V.MỚI").setIndicator("Ư.V.MỚI", null),
    				FragmentTapNew.class, null);
    		mTabHost.addTab(
    				mTabHost.newTabSpec("Ư.V.ĐANG ĐT").setIndicator("Ư.V.ĐANG ĐT", null),
    				FragmentTabYesterday.class, null);
    		mTabHost.addTab(
    				mTabHost.newTabSpec("Ư.V.ĐÃ ĐT").setIndicator("Ư.V.ĐÃ ĐT", null),
    				FragmentTabAll.class, null);
    	}
    }
    
    Khi run project FragmentTapNew sẽ được add vào TrainingActivity . FragmentTapNew sẽ được nạp dữ liệu từ TrainingAdapter. Nhưng bây h khi đã load được dữ liệu lên TrainingActivity, mình muốn khi trên Activity người dùng bấm button btnTest mà button này nằm trên TrainingAdapter thì sẽ chuyển sang Activity mới nhưng mình chưa biết phải làm thế nào để gọi được đến button này ạ mình tham khảo thì được biết phải viết interface để gọi nhưng chưa biết làm thế nào ? mong mọi người giúp đỡ.

    Thanks

Chia sẻ trang này