I am using ViewPager in side activity and add Fragment-State-Pager-Adapter and trying to remove current page position after add the some pages.but every time removed last page position.so please recommend me for use right approach for doing this.Thanks in advance.
This is my activity and adapter code.
public class Main-Activity extends Fragment-Activity implements AddItemFragment.OnFragmentInteractionListener {
PagerAdapter mAdapter;
ViewPager mPager;
Button button ,btn_add;
int pos,TOTAL_PAGES=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
//THIS IS THE MODEL CLASS WHERE I ADD THE PAGES.
MoveItems.items = new ArrayList<>();
MoveItems.items.clear();
Intialize();
}
public void Intialize() {
mPager = (ViewPager)findViewById(R.id.pager);
mAdapter = new PagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mAdapter);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
pos = position + 1;
}
#Override
public void onPageScrollStateChanged(int state) {
//Function.toast(MainActivity.this, "onPageScrollStateChanged");
}
});
Addpage();
button = (Button)findViewById(R.id.delete_current);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAdapter.deletePage(mPager.getCurrentItem());
Function.toast(MainActivity.this,"'Delete page");
}
});
btn_add=(Button)findViewById(R.id.goto_first);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Addpage();
}
});
}
public void Addpage() {
TOTAL_PAGES++;
ItemDescription item = new ItemDescription();
MoveItems.items.add(item);
if (mAdapter != null)
mAdapter.notifyDataSetChanged();
mPager.setCurrentItem((TOTAL_PAGES - 1));
}
#Override
public void onFragmentCreated(ItemDescription itemDescription, int position) {
if (mAdapter != null)
mAdapter.notifyDataSetChanged();
}
public class PagerAdapter extends FragmentStatePagerAdapter
{
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
ItemDescription description = new ItemDescription();
description.setItemNo(position);
description = MoveItems.items.get(position);
return AddItemFragment.newInstance(position, description);
}
#Override
public int getCount() {
return MoveItems.items.size();
}
public void deletePage(int position)
{
MoveItems.items.remove(position);;
notifyDataSetChanged();
}
}
}
This The XML PART
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
<LinearLayout android:orientation="horizontal"
android:gravity="center"
android:measureWithLargestChild="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0">
<!--go to the first page in the view pager-->
<Button android:id="#+id/goto_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First">
</Button>
<!--Delete the current page-->
<Button android:id="#+id/delete_current"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete">
</Button>
<!--go to the last page in the view pager-->
<Button android:id="#+id/goto_last"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Last">
</Button>
</LinearLayout>
</LinearLayout>
THIS THE FRAGMENT CLASS WHERE I INFLATE THE LAYOUT WHICH HAVE CHECK-BOXES AND EDITEXT.
public class AddItemFragment extends Fragment {
// Store instance variables
private int page;
ItemDescription description;
CheckBox furniture, mattress, box, appliance;
EditText other, item_description;
private OnFragmentInteractionListener listener;
LinearLayout line1;
CheckBox checkboxes[];
View v;
// newInstance constructor for creating fragment with arguments
public static AddItemFragment newInstance(int page, ItemDescription item) {
AddItemFragment fragmentFirst = new AddItemFragment();
Bundle args = new Bundle();
args.putInt("pagecount", page);
args.putSerializable("item", item);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
#Override
public void onAttach(Activity activity) {
try {
listener = (OnFragmentInteractionListener) getActivity();
}
catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener");
}
super.onAttach(activity);
}
/**
* Interface for communicating data
*/
public interface OnFragmentInteractionListener {
public void onFragmentCreated(ItemDescription itemDescription, int position);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_add_item, container, false);
page = getArguments().getInt("pagecount", 0);
description = (ItemDescription) getArguments().getSerializable("item");
One = (CheckBox) v.findViewById(R.id.furniture);
Two = (CheckBox) v.findViewById(R.id.mattress);
Three = (CheckBox) v.findViewById(R.id.box);
Four = (CheckBox) v.findViewById(R.id.appliance);
other = (EditText) v.findViewById(R.id.other);
item_description = (EditText) v.findViewById(R.id.item_description);
checkboxes = new CheckBox[]{One, Two, Three, Four};
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
BitmapsForImage bitmapsForImage = null;
imagePath = "";
if (resultCode == Activity.RESULT_OK) {
if (requestCode == Constants.ImagePick) {
Uri imageUri = getPickImageResultUri(data);
imagePath = getPath(getActivity(), imageUri);
bitmapsForImage = Function.resizeBitmap(imagePath, getActivity());
} else if (Constants.CAMERA_REQUEST_CODE == requestCode) {
bitmapsForImage = Function.resizeBitmap(imagePath, getActivity());
} else if (Constants.GALLERY_IMAGE == requestCode && null != data) {
if (data != null) {
Uri contentURI = data.getData();
String imagePath = Function.getRealPathFromURI(getActivity(), contentURI);
bitmapsForImage = Function.resizeBitmap(imagePath, getActivity());
}
}
if (bitmapsForImage != null && imagePath != null && imagePath.length() > 0) {
MoveItems.itemsBitmapList.set(page, bitmapsForImage.getBitmapToShow());
line1.setVisibility(View.GONE);
description.setItemFilePath(imagePath);
description.setItemFile(new File(imagePath));
MoveItems.items.get(page).setItemFile(new File(imagePath));
MoveItems.items.get(page).setItemFilePath(imagePath);
try {
listener.onFragmentCreated(description, page);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Function.toast(getActivity(), "Some Error Occured");
return;
}
}
}
}
THIS IS THE Fragment_Add_Item WHICH HAVE CHECK BOX AND EDIT TEXT.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:layout_marginTop="20dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:orientation="horizontal">
<CheckBox
android:id="#+id/furniture"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingLeft="10dp"
android:singleLine="true"
android:text="Furniture"
android:textSize="15sp" />
<CheckBox
android:id="#+id/mattress"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingLeft="10dp"
android:singleLine="true"
android:text="Mattress"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="5dp"
android:orientation="horizontal">
<CheckBox
android:id="#+id/box"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingLeft="10dp"
android:singleLine="true"
android:text="Box"
android:textSize="15sp" />
<CheckBox
android:id="#+id/appliance"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingLeft="10dp"
android:singleLine="true"
android:text="Appliance"
android:textSize="15sp" />
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/other_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">
<EditText
android:id="#+id/other"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Other"
android:singleLine="true"
android:textSize="15sp" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/notes_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/item_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Item Notes"
android:singleLine="true"
android:textSize="15sp" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:id="#+id/line1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="2dp"
android:text="Add a Photo"
android:textSize="15sp" />
<TextView android:id="#+id/Des"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="2dp"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
This problem occurs when I get any input type inside Fragment_Add_Item layout please help me for find out this problem.This very-very important from me and i am using first time view-pager. In this code item of view-pager deleted but not exact.so i was doing this differnt ways. but not getting right output. thanks in advance.
Related
I have an FragmentActivity which contain WebView, Edittext1, Edittext2, Checkboxes and button. When I click the button in fragment it will move to Results_activity. And if I click button from Results_activity it move back to FragmentActivity.
But my edittext values getting cleared while moving back.
FragmentActivity xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/background_light"
android:orientation="vertical">
<LinearLayout
android:id="#+id/questionContainer"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<WebView
android:id="#+id/questionWV"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:id="#+id/ansA_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp">
<EditText
android:id="#+id/ansA"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:freezesText="true"
android:hint="Enter answer here..."
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:textAppearance="#android:style/TextAppearance.Medium" />
</LinearLayout>
<LinearLayout
android:id="#+id/ansB_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp">
<EditText
android:id="#+id/ansB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:freezesText="true"
android:hint="Enter answer here..."
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:textAppearance="#android:style/TextAppearance.Medium" />
</LinearLayout>
<LinearLayout
android:id="#+id/answers_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp">
<RelativeLayout
android:id="#+id/answer_a_container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_gravity="top"
android:layout_weight="1">
<CheckBox
android:id="#+id/answerA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:hint="0"
android:maxLines="100"
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:text="Varianta A"
android:textAppearance="#android:style/TextAppearance.Medium" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/answer_b_container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<CheckBox
android:id="#+id/answerB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="false"
android:layout_marginStart="15dp"
android:hint="1"
android:maxLines="100"
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:text="Varianta B"
android:textAppearance="#android:style/TextAppearance.Medium" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/answer_c_container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<CheckBox
android:id="#+id/answerC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:hint="2"
android:maxLines="100"
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:text="Varianta C"
android:textAppearance="#android:style/TextAppearance.Medium" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/answer_d_container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<CheckBox
android:id="#+id/answerD"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:hint="3"
android:maxLines="100"
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:text="Varianta D"
android:textAppearance="#android:style/TextAppearance.Medium" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom|center"
android:orientation="horizontal"
android:paddingBottom="30dp">
<Button
android:id="#+id/btnFinishTest"
style="#android:style/Widget.Button.Inset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/testbutton"
android:onClick="FinishTest"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Finish Test" />
<Button
android:id="#+id/btnAnswer"
style="#android:style/Widget.Button.Inset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/testbutton"
android:onClick="SubmitAnswer"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Submit Answer" />
</LinearLayout>
</LinearLayout>
Fragment Code
my edittexts are et1 and et2
public class QuestionFragment2018ii extends Fragment {
LinearLayout answersContainer;
int currentPageNr;
private String input1;
#Override
public View onCreateView(LayoutInflater lInflater, ViewGroup container,Bundle saveInstanceState){
currentPageNr = getArguments().getInt("position");
//initialize some variables
final Question2018ii currentQuestion2018ii = MyServerData2018ii.getInstance().getQuestion(currentPageNr);
View rootView = lInflater.inflate(R.layout.quiz_activity_fragment,container,false);
//initialize show answer option
final String ans = currentQuestion2018ii.getExplanationText();
final EditText et1 = rootView.findViewById(R.id.ansA);
final EditText et2 = rootView.findViewById(R.id.ansB);
if(MyServerData2018ii.getInstance().getTestState().equals("finished") ){
et1.setText("Your Response: " + et.getText());
et2.setText("Correct Answer: " + ans);
}
//initialize Explanation option
//initialize answers
answersContainer = (LinearLayout)rootView.findViewById(R.id.answers_container);
String[] answers = currentQuestion2018ii.getAllAnswersText();
for (int i = 0; i < answersContainer.getChildCount(); i++) {
RelativeLayout checkboxContainer = (RelativeLayout)answersContainer.getChildAt(i);
CheckBox cb = (CheckBox)checkboxContainer.getChildAt(0);
cb.setMovementMethod(new ScrollingMovementMethod());
cb.setText(answers[i]);
cb.setChecked(currentQuestion2018ii.isChecked(i));
if(MyServerData2018ii.getInstance().getTestState().equals("finished") ){
cb.setEnabled(false);
questionWebView.loadUrl("file:///android_asset/" + currentQuestion2018ii.getSolutionText());
//check if answer is right or wrong
if(currentQuestion2018ii.isCorrectAnswer(i)){
cb.setTextColor(Color.parseColor("#4DAD47"));
cb.setTypeface(null, Typeface.BOLD);
} else {
cb.setTextColor(Color.parseColor("#CE0B0B"));
}
}else{
cb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = ((CheckBox) v);
int number = Integer.parseInt(cb.getHint().toString());
currentQuestion2018ii.setChecked(number, cb.isChecked());
}
});
}
}
return rootView;
}
}
ResultsActivity xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingBottom="10dp"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:paddingTop="30dp"
android:text="#string/results"
android:textColor="#4DAD47"
android:textSize="20sp"
android:textStyle="bold|italic" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingTop="30dp" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:paddingBottom="20dp"
android:text="#string/correct_answers" />
</LinearLayout>
<TextView
android:id="#+id/myTotalAnswers"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_vertical|center_horizontal"
android:paddingRight="5dp"
android:text="50/100" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mainContainer"></LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<Button
android:id="#+id/check_results"
style="#android:style/Widget.Button.Inset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:background="#drawable/testbutton"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/check_results" />
<Button
android:id="#+id/btnMainMenu"
style="#android:style/Widget.Button.Inset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:background="#drawable/testbutton"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/main_menu" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
Quiz activity
public class QuizActivity2018ii extends AppCompatActivity {
Spinner spinCategory;
EditText questionNr;
ArrayList<String> allCategories;
int totalQuestions;
AlertDialog dialog;
ViewPager pager;
QuestionPagerAdapter2018ii pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_activity_view_pager);
allCategories = new ArrayList<>(MyServerData2018ii.getInstance().getCategoryList());
totalQuestions = MyServerData2018ii.getInstance().getTotalQuestions();
//initialize category spinner
ArrayAdapter<String> categoryAdapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_dropdown_item,allCategories);
spinCategory = (Spinner) findViewById(R.id.category);
spinCategory.setAdapter(categoryAdapter);
spinCategory.setSelection(0);
//set Category spinner callback
spinCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String currentQuestionRealCategory = MyServerData2018ii.getInstance().getQuestionCategory(pager.getCurrentItem());
String selectedCategory = spinCategory.getItemAtPosition(position).toString();
if (!selectedCategory.equals(currentQuestionRealCategory)) {
int firstQuestionNumberFromCategory = MyServerData2018ii.getInstance().getFirstQuestionNumberFromCategory(selectedCategory);
ViewPager pager = (ViewPager) findViewById(R.id.qPager);
pager.setCurrentItem(firstQuestionNumberFromCategory, false);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//initialize number
questionNr = (EditText) findViewById(R.id.dialog_question_number);
questionNr.clearFocus();
//set number callbacks
questionNr.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_ENTER)) {
v.clearFocus();
CharSequence s = questionNr.getText();
if (!s.toString().isEmpty()) {
Integer questionNumber = Integer.parseInt(s.toString());
//avoids out of range indexes
if (questionNumber > totalQuestions + 1) {
questionNumber = totalQuestions;
}
if (questionNumber < 0) {
questionNumber = 1;
}
//create looping effect
if (questionNumber == totalQuestions + 1) {
questionNumber = 1;
((EditText)v).setText("1");
}
if (questionNumber == 0) {
questionNumber = totalQuestions;
((EditText)v).setText(String.valueOf(totalQuestions));
}
ViewPager pager = (ViewPager) findViewById(R.id.qPager);
pager.setCurrentItem(questionNumber, false);
questionNr.clearFocus();
} else {
questionNr.setText("1");
}
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
return false;
}
});
//initialize pager
pager = (ViewPager)findViewById(R.id.qPager);
pagerAdapter = new QuestionPagerAdapter2018ii(getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
pager.setCurrentItem(1, false);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {
Integer currentQuestion = pager.getCurrentItem();
//change spinner
String currentCategory = MyServerData2018ii.getInstance().getQuestionCategory(currentQuestion);
int categoryPosition = MyServerData2018ii.getInstance().getCategoryList().indexOf(currentCategory);
spinCategory.setSelection(categoryPosition);
//change numberPicker
if(currentQuestion <= 0){currentQuestion = totalQuestions;}
if(currentQuestion > totalQuestions){currentQuestion = 1;}
questionNr.setText(currentQuestion.toString());
questionNr.clearFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(questionNr.getWindowToken(), 0);
}
#Override
public void onPageScrollStateChanged(int state) {
int totalQuestions = MyServerData2018ii.getInstance().getTotalQuestions();
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (pager.getCurrentItem() == totalQuestions + 1) {
pager.setCurrentItem(1, false);
}
if (pager.getCurrentItem() == 0) {
pager.setCurrentItem(totalQuestions, false); // false will prevent sliding animation of view pager
}
}
}
});
}
public void FinishTest(View v){
//check if there are unanswered questions
if(MyServerData2018ii.getInstance().getTestState().equals("inProgress")){
ArrayList<String> UnansweredQuestions = new ArrayList<>();
LinkedHashMap<String,Object> allQuestions = MyServerData2018ii.getInstance().getAllQuestions();
for(Map.Entry category: allQuestions.entrySet()){
Question2018ii[] question2018iis = (Question2018ii[])category.getValue();
for(int i = 0; i < question2018iis.length; i++){
Boolean[] userAnswers = question2018iis[i].getUserAnswers();
if(!Arrays.asList(userAnswers).contains(true)){
String checkedCategory = (String)category.getKey();
Integer questionNumberInList = MyServerData2018ii.getInstance().getQuestionListNumber(checkedCategory,i);
UnansweredQuestions.add(String.valueOf(questionNumberInList));
}
}
}
if(UnansweredQuestions.size() > 0){
dialog = new AlertDialog.Builder(this)
.create();
LayoutInflater infl = LayoutInflater.from(this);
dialog.setView(infl.inflate(R.layout.dialog_message,null));
dialog.show();
TextView message = (TextView)dialog.findViewById(R.id.message);
String unfinished = getResources().getString(R.string.unfinished_text);
String questions = TextUtils.join(",",UnansweredQuestions);
message.setText(unfinished + "\n" + questions + ".");
dialog.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
showResults();
}
});
}else{showResults();}
}else{
showResults();
}
}
public void showResults(){
int animationDuration;
if(MyServerData2018ii.getInstance().getTestState().equals("finished")){
animationDuration = 10;
}else{
animationDuration = 2000;
}
View mainView = LayoutInflater.from(this).inflate(R.layout.quiz_activity_show_results,null);
LinearLayout mainContainer = (LinearLayout)mainView.findViewById(R.id.mainContainer);
mainView.findViewById(R.id.btnMainMenu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//finish the test and go to main menu
Intent Main = new Intent(getApplicationContext(),MainActivity.class);
finish();
startActivity(Main);
MyServerData2018ii.getInstance().setTestState("notStarted");
MyServerData2018ii.getInstance().clearAnswers();
Toast.makeText(getBaseContext(),R.string.text_ended,Toast.LENGTH_LONG).show();
}
});
mainView.findViewById(R.id.check_results).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
Question2018ii[] currentCategory;
int totalCategoryQuestions;
int correctCategoryQuestions;
int totalCorrectQuestions = 0;
//checking and adding each category
for(String category: allCategories){
View categoryContainer = LayoutInflater.from(this).inflate(R.layout.quiz_activity_category_results,null);
TextView categoryName = (TextView)categoryContainer.findViewById(R.id.categoryName);
//set name
categoryName.setText(category);
currentCategory = MyServerData2018ii.getInstance().getCategory(category);
totalCategoryQuestions = currentCategory.length;
//check answers
correctCategoryQuestions = 0;
for(int i=0; i < currentCategory.length;i++){
Boolean isCorrect = Arrays.equals(currentCategory[i].getAllCorrectAnswers(),currentCategory[i].getUserAnswers());
if(isCorrect){ correctCategoryQuestions++;}
}
totalCorrectQuestions += correctCategoryQuestions;
//set results
String result = String.valueOf(correctCategoryQuestions) + "/" + String.valueOf(totalCategoryQuestions);
final ProgressBar progress = (ProgressBar)categoryContainer.findViewById(R.id.progressBar);
progress.setMax(totalCategoryQuestions*100);
final TextView myResult = (TextView)categoryContainer.findViewById(R.id.categoryResult);
final String myResultText = "/" + String.valueOf(totalCategoryQuestions);
ValueAnimator val = new ValueAnimator();
val.setObjectValues(0, correctCategoryQuestions*100);
val.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
myResult.setText(String.valueOf((Integer)animation.getAnimatedValue()/100) + myResultText);
progress.setProgress( ((Integer) animation.getAnimatedValue()));
}
});
val.setDuration(animationDuration);
val.start();
mainContainer.addView(categoryContainer);
}
//animate results
final TextView tvTotalResult =(TextView)mainView.findViewById(R.id.myTotalAnswers);
final String totalResultS = "/" + String.valueOf(totalQuestions);
ValueAnimator totalResultsAnimator = new ValueAnimator();
totalResultsAnimator.setObjectValues(0, totalCorrectQuestions);
totalResultsAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
tvTotalResult.setText(String.valueOf(animation.getAnimatedValue()) + totalResultS);
}
});
totalResultsAnimator.setDuration(animationDuration);
totalResultsAnimator.start();
MyServerData2018ii.getInstance().setTestState("finished");
setContentView(mainView);
}
}
this is my question yearwise activity(from this I launched the fragment activity)
public class QuestionYearwise extends AppCompatActivity{
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.question_yearwise);
Button btn2018ii = (Button)findViewById(R.id.btn2018ii);
btn2018ii.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent Quiz2018ii = new Intent(getApplicationContext(),QuizActivity2018ii.class);
MyServerData2018ii.getInstance().setTestState("inProgress");
startActivity(Quiz2018ii);
}
});
}
}
Replace the method like this,
mainView.findViewById(R.id.check_results).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
My app has a RawMaterialFragment that displays raw materials data in a recyclerView from room database.
I am trying to build a detail activity(MetrialItemView) to show up the details of an individual raw material by clicking or selecting the raw material from the recyclerView.
my problem is how to send the data from the adapter and how to receive the data in the MetrialItemView Activity and display it.
MaterialListAdapter:
public class MaterialListAdapter extends RecyclerView.Adapter<MaterialListAdapter.ViewHolder> {
private final LayoutInflater mInflater;
private FragmentRawMaterials mContext;
private List<RawMaterialsEntity> mMaterial; // Cached copy of Materials
RawMaterialsEntity mCurrent;
public MaterialListAdapter(FragmentRawMaterials context) {
mInflater = LayoutInflater.from(context.getActivity());
mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.list_item, parent, false);
return new ViewHolder(itemView);
}
public class ViewHolder extends RecyclerView.ViewHolder {
private final TextView materialName;
private final TextView materialBrand;
private final TextView materialQuantity;
LinearLayout parentLayout;
private ViewHolder(View itemView) {
super(itemView);
materialName = itemView.findViewById(R.id.raw_material_name);
materialBrand = itemView.findViewById(R.id.raw_material_brand);
materialQuantity = itemView.findViewById(R.id.raw_material_quantity);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if (mMaterial != null) {
mCurrent = mMaterial.get(position);
holder.materialName.setText(mCurrent.getRawMaterialName());
holder.materialBrand.setText(mCurrent.getRawMaterialBrand());
holder.materialQuantity.setText(String.valueOf(mCurrent.getRawMaterialQuantity()));
} else {
// Covers the case of data not being ready yet.
holder.materialName.setText("Name NA");
holder.materialBrand.setText("Brand NA");
holder.materialQuantity.setText("Quantity NA");
}
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext.getContext(), MaterialItemView.class);
mContext.startActivity(intent);
}
});
}
public void setMaterial(List<RawMaterialsEntity> materials){
mMaterial = materials;
notifyDataSetChanged();
}
// getItemCount() is called many times, and when it is first called,
// mWords has not been updated (means initially, it's null, and we can't return null).
#Override
public int getItemCount() {
if (mMaterial != null)
return mMaterial.size();
else return 0;
}
}
MaterialItemView:
public class MaterialItemView extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.material_item_view);
}
}
material_list_item:
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Raw Material Name:"
style="#style/OtherTextViews"/>
<TextView
android:id="#+id/material_name_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Raw Material Brand:"
style="#style/OtherTextViews"/>
<TextView
android:id="#+id/material_brand_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Unit Weight:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2000"
style="#style/OtherTextViewsBody"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="gm"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Unit Cost:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="50"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cost per gm/ml:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0.1"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Available Quantity:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1000"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Total Cost:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="50000"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Supplier Name:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pandah"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Supplier Email:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pandah#panadh.com"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Supplier Phone:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+966555699517"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
</LinearLayout>
FragmentRawMaterials:
public class FragmentRawMaterials extends Fragment{
private RawMaterialViewModel mMaterialViewModel;
private static final int NEW_MATERIAL_ACTIVITY_REQUEST_CODE = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_raw_materials, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Setup any handles to view objects here
//FloatingActionButton fab to insert recipes
TextView emptyViewText = view.findViewById(R.id.empty_raw__materials_view);
FloatingActionButton fab = view.findViewById(R.id.fab_raw_materials);
fab.setOnClickListener(view1 -> {
Intent intent = new Intent(getActivity(), RawMaterialsEditor.class);
startActivityForResult(intent, NEW_MATERIAL_ACTIVITY_REQUEST_CODE);
});
RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
//Decoration to add a line divider between recyclerView items
DividerItemDecoration decoration =
new DividerItemDecoration(Objects.requireNonNull(this.getActivity()),
R.drawable.border_line);
recyclerView.addItemDecoration(decoration);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
final MaterialListAdapter adapter = new MaterialListAdapter(this);
recyclerView.setAdapter(adapter);
// Check if adapter list is empty, if so empty text view will appear.
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
super.onChanged();
if (adapter.getItemCount() == 0) {
recyclerView.setVisibility(View.GONE);
emptyViewText.setVisibility(View.VISIBLE);
}
else {
recyclerView.setVisibility(View.VISIBLE);
emptyViewText.setVisibility(View.GONE);
}
}
});
mMaterialViewModel = new ViewModelProvider(this).get(RawMaterialViewModel.class);
// Update the cached copy of the words in the adapter.
mMaterialViewModel.getAllMaterials().observe(this, adapter::setMaterial);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == NEW_MATERIAL_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
RawMaterialsEntity material = new RawMaterialsEntity(data
.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_NAME),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_BRAND),
Float.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_WEIGHT)),
Float.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_COST)),
Integer.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_QUANTITY)),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_NAME),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_EMAIL),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_PHONE),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_UOM));
mMaterialViewModel.insertMaterial(material);
mMaterialViewModel.costPerGm();
mMaterialViewModel.totalCost();
} else {
Toast.makeText(
Objects.requireNonNull(getActivity()).getApplicationContext(),
R.string.editor_insert_rm_failed,
Toast.LENGTH_LONG).show();
}
}
}
each row of dataModel() must have ID and then use putExtra() whan clicked It happens
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext.getContext(), MaterialItemView.class);
intent.putExtra("ID",mCurrent.getID());
mContext.startActivity(intent);
}
});
and use getIntent() in detailActivity
int id =getIntent().getIntExtra("ID",-1);
and then get a row data in detail activity from database(viewModel)by ID and parse it
Am trying to build my first app and my recyclerView only displays the first item from the json.I have tried changing the layout height to wrap_content but its still not working
Here is the xml layout for the recyclerview activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aleky.carrental.cars">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/rv"
android:clickable="false"
/>
</RelativeLayout>
</RelativeLayout>
the cardview xml layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
cardview:cardCornerRadius="2dp"
cardview:cardElevation="3dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:paddingBottom="15dp">
<TextView
android:id="#+id/car_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:fontFamily="sans-serif-smallcaps"
android:text="Car Name"
android:textColor="#996515"
android:textSize="24sp"
android:textStyle="bold" />
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/Car_image"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_below="#+id/car_name"
android:layout_marginBottom="2dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="2dp" />
<TextView
android:id="#+id/tvfeature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="90dp"
android:layout_marginTop="25dp"
android:layout_toRightOf="#+id/car_name"
android:text="Features"
android:textColor="#000"
android:textSize="22sp" />
<View
android:layout_width="100dp"
android:layout_height="1dp"
android:layout_below="#+id/tvfeature"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/Car_image"
android:background="#000" />
<ImageView
android:id="#+id/ac"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_below="#+id/tvfeature"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/Car_image"
android:src="#drawable/air_conditioner" />
<TextView
android:id="#+id/feature1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvfeature"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/ac"
android:text="Air conditioner"
android:textColor="#000"
android:textSize="16sp" />
<ImageView
android:id="#+id/tr"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_below="#+id/feature1"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/Car_image"
android:src="#drawable/transmission" />
<TextView
android:id="#+id/feature2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/feature1"
android:layout_marginLeft="2dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/tr"
android:text="Manual"
android:textColor="#333333"
android:textSize="16sp" />
<ImageView
android:id="#+id/pass"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_below="#+id/tr"
android:layout_marginLeft="20dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#+id/Car_image"
android:src="#drawable/passengers" />
<TextView
android:id="#+id/feature3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/feature2"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#id/pass"
android:text="6 Passengers"
android:textColor="#333333"
android:textSize="16sp" />
<TextView
android:id="#+id/pricetxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Car_image"
android:text="Price :"
android:textColor="#333333"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:id="#+id/car_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Car_image"
android:layout_marginLeft="2dp"
android:layout_toRightOf="#+id/pricetxt"
android:text="KSH.2000"
android:textColor="#996515"
android:textSize="22sp" />
<TextView
android:id="#+id/organiser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/pricetxt"
android:layout_marginTop="5dp"
android:text="Owner :"
android:textColor="#333333"
android:textSize="14sp" />
<TextView
android:id="#+id/crAgent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/pricetxt"
android:layout_marginLeft="2dp"
android:layout_marginTop="5dp"
android:layout_toEndOf="#+id/organiser"
android:layout_toRightOf="#+id/organiser"
android:text="Supercars Rentals"
android:textColor="#05056c"
android:textSize="14sp" />
<Button
android:id="#+id/btn_rent"
style="#style/AppTheme.ButtonCorners"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/Car_image"
android:layout_marginRight="12dp"
android:clickable="true"
android:text="Rent"
android:textColor="#eef525" />
<TextView
android:id="#+id/car_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible" />
</RelativeLayout>
</android.support.v7.widget.CardView>
The cars.java class to load items into the recyclerview
public class cars extends AppCompatActivity {
String url = "http://192.168.43.201/Car_rental/retrievecars.php";
Context context = null;
ProgressDialog dialog;
private List<CarsItem> array_cars = new ArrayList<>();
AdapterClass adapter;
NetworkImageView carsImageview;
private String user_Location = "cLocation";
private String Category = "category";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cars);
adapter = new AdapterClass(cars.this, array_cars);
RecyclerView recycler = (RecyclerView) findViewById(R.id.rv);
recycler.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(layoutManager);
recycler.setItemAnimator(new DefaultItemAnimator());
recycler.setAdapter(adapter);
setCars();
recycler.addOnItemTouchListener(new RecyclerTouchListener(this, recycler, new ClickListener() {
#Override
public void onClick(View view, int position) {
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
public void setCars() {
dialog = new ProgressDialog(this);
dialog.setMessage("Loading cars...");
dialog.show();
if (array_cars != null) {
array_cars.clear();
}
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
hideDialog();
Log.d("Sever Message", s);
JSONObject cars = new JSONObject(s);
JSONArray jsonArray = cars.getJSONArray("Cars");
JSONObject jobject = null;
int len = jsonArray.length();
for (int i = 0; i < len; i++) {
jobject = jsonArray.getJSONObject(i);
CarsItem carsdata = new CarsItem();
carsdata.setId(jobject.getString("0"));
carsdata.setCarname(jobject.getString("1"));
carsdata.setImages(jobject.getString("car_image"));
carsdata.setfeature1(jobject.getString("5"));
carsdata.setfeature2(jobject.getString("6"));
carsdata.setfeature3(jobject.getString("7"));
carsdata.setPrice(jobject.getString("8"));
array_cars.add(carsdata);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Getting Image Location & category
String Location = "";
String Ccategory = "cars";
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put(Category, Ccategory);
params.put(user_Location, Location);
//returning parameters
return params;
}
};
//RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding our request to the queue
// requestQueue.add(request);
AppController.getmInstance().addToRequestQueue(request);
}
public void hideDialog() {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
GestureDetector gestureDetector;
cars.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final cars.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView recycler, MotionEvent e) {
View child = recycler.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, recycler.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recycler, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
and finally my adapter class
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.CustomViewHolder> {
private List<CarsItem> Array_cars;
private ImageLoader imageLoader;
private Context mContext;
public AdapterClass(Context context, List<CarsItem> array_cars) {
this.Array_cars = array_cars;
this.mContext = context;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cars_design, null);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder,final int i) {
final CarsItem carsItem = Array_cars.get(i);
holder.imageUrl = carsItem.getImages();
imageLoader = AppController.getmInstance().getmImageLoader();
holder.Carname.setText(carsItem.getCarname());
holder.feature1.setText(carsItem.getfeature1());
holder.feature2.setText(carsItem.getfeature2());
holder.feature3.setText(carsItem.getfeature3());
holder.price.setText(carsItem.getPrice());
holder.agent.setText(carsItem.getcarowner());
holder.carid.setText(carsItem.getId());
holder.carimage.setImageUrl("http://192.168.43.201/Car_rental/cars/"+carsItem.getImages(), imageLoader);
holder.rent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, HireCar.class);
intent.putExtra("carname",carsItem.getCarname());
intent.putExtra("car_rate",carsItem.getPrice());
intent.putExtra("car_image", carsItem.getImages());
intent.putExtra("car_id", carsItem.getId());
intent.putExtra("c_owner", carsItem.getcarowner());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return (null != Array_cars ? Array_cars.size() : 0);
}
class CustomViewHolder extends RecyclerView.ViewHolder {
String imageUrl;
TextView Carname, feature1, feature2, feature3, price,agent,carid;
NetworkImageView carimage;
Button rent;
public CustomViewHolder(View view) {
super(view);
this.Carname = (TextView) view.findViewById(R.id.car_name);
this.feature1 = (TextView) view.findViewById(R.id.feature1);
this.feature3 = (TextView) view.findViewById(R.id.feature3);
this.price = (TextView) view.findViewById(R.id.car_price);
this.feature2=(TextView) view.findViewById(R.id.feature2);
this.carimage = (NetworkImageView) view.findViewById(R.id.Car_image);
this.rent=(Button)view.findViewById(R.id.btn_rent);
this.agent=(TextView)view.findViewById(R.id.crAgent);
this.carid=(TextView)view.findViewById(R.id.car_id);
}
}
}
I think the problem is that you are not adding the elements to the adapter. You need to have a method in the adapter to add items after the adapter has been created. Inside that method you need to notify. Example:
void addItems(List<CarItem> carItems){
Array_cars.addAll(carItems);
notifyDataSetChanged();
}
However, I would go a bit far and find the number of items and try to notify only for the newly inserted ones(in case there is something already).
This can be done like this:
void addItems(List<CarItem> carItems){
int position = Array_cars.size();
Array_cars.addAll(carItems);
notifyItemRangeChanged(position, Array_cars.size() - position);
}
EDIT
Look at this example below:
RecycleView
Here is the xml layout for the recyclerview activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aleky.carrental.cars">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rv"
android:clickable="false"
/>
</RelativeLayout>
</RelativeLayout>
You have added match_parent height of "RecyclerView" please change to wrap_content.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aleky.carrental.cars">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rv"
android:clickable="false"
/>
</RelativeLayout>
</RelativeLayout>
I have custom dialog to show which has instruction about how to use the app.I am using ViewPager for this inside my custom dialog layout.
I am getting error
java.lang.IllegalArgumentException: No view found for id for fragment FragmentForInstruction1.
I have created a method which is called in onCreate(Bundle savedInstanceState) {} method .The method inflates the layout for dialog.
private void showCustomDialogForInstruction() {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.dialog_layout_for_instruction_message, null, false);
layout.setAlpha(0.2f);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(dialogLayout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
ViewPager viewPager=(ViewPager) dialog.findViewById(R.id.pagerInstruction);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new FragmentForInstruction1());
adapter.addFrag(new Fragme`enter code here`ntForWelcomePage2());
adapter.addFrag(new FragmentForWelcomePage3());
adapter.addFrag(new FragmentForWelcomePage4());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new OnPageChangeListener()
{
#Override
public void onPageSelected(int pos)
{
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2)
{
}
#Override
public void onPageScrollStateChanged(int arg0)
{
}
});
Button done = (Button) dialog.findViewById(R.id.done);
done.setText("Got It");
done.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
Button neverShow = (Button) dialog.findViewById(R.id.nevershow);
neverShow.setText("Never Show Again");
neverShow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return false;
}
});
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.show();
}
my view pager class:
public class ViewPagerAdapter extends FragmentPagerAdapter
{
private final List<Fragment> mFragmentList = new ArrayList<Fragment>();
public ViewPagerAdapter(FragmentManager manager)
{
super(manager);
}
#Override
public Fragment getItem(int position)
{
return mFragmentList.get(position);
}
#Override
public int getCount()
{
return mFragmentList.size();
}
public void addFrag(Fragment fragment)
{
mFragmentList.add(fragment);
}
}
and i call the method in MainActivity :
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferencesNeverShowAgain ;
boolean neverShowAgain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferencesNeverShowAgain = PreferenceManager.getDefaultSharedPreferences(this);
neverShowAgain = sharedPreferencesNeverShowAgain.getBoolean("NeverShowAgain", false);
if(!neverShowAgain){
showCustomDialogForMessage();
}
}
}
and the layout for dialog is:
<?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="wrap_content"
android:background="#drawable/dialog_shape"
android:orientation="vertical" >
<!-- layout title -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#00000000"
android:gravity="center"
android:orientation="vertical" >
<ViewFlipper
android:id="#+id/flipper"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/top_edge_rounded"
android:flipInterval="2000"
android:padding="20dp" >
<TextView
android:id="#+id/dialog_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00000000"
android:gravity="center"
android:text="Input Height"
android:textColor="#color/textColor"
android:textStyle="normal" />
<TextView
android:id="#+id/title1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00000000"
android:gravity="center"
android:text="Input Height"
android:textColor="#color/accent"
android:textStyle="normal" />
</ViewFlipper>
<View
android:id="#+id/tri"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#drawable/triangle"
android:rotation="180" />
</LinearLayout>
<!-- layout dialog content -->
<ScrollView
android:layout_width="match_parent"
android:layout_height="300dp" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<android.support.v4.view.ViewPager
android:id="#+id/pagerInstruction"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/layoutIndicater"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:gravity="center"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
</ScrollView>
<!-- layout dialog buttons -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_margin="10dp"
android:background="#drawable/all_rounded_edge_plum_for_dialog" >
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_alignParentTop="true"
android:background="#color/textColor" />
<View
android:id="#+id/ViewColorPickerHelper"
android:layout_width="1dp"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#color/textColor" />
<Button
android:id="#+id/nevershow"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_toLeftOf="#id/ViewColorPickerHelper"
android:background="?android:attr/selectableItemBackground"
android:padding="5dp"
android:text="Close"
android:textColor="#color/textColor" />
<Button
android:id="#+id/done"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_toRightOf="#id/ViewColorPickerHelper"
android:background="?android:attr/selectableItemBackground"
android:padding="5dp"
android:text="Done"
android:textColor="#color/textColor" />
</RelativeLayout>
</LinearLayout>
FragmentForInstruction1 code:
public class FragmentForInstruction1 extends Fragment{
#Override
#Nullable
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragmentinstructionpage1, container,false);
return view;
}
}
and its layout is:
<?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:background="#color/backgroundColor"
android:gravity="center" >
<TextView
android:id="#+id/titleWelcomeFragment1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#color/colorPrimary"
android:textSize="30sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/messageWelcomeFragment1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#color/colorPrimary"
android:textSize="20sp"
android:textStyle="normal"
android:paddingLeft="20dp"
android:paddingRight="20dp"/>
</LinearLayout>
You should create an adapter that extends FragmentPagerAdapter:
private class CustomPagerAdapter extends FragmentPagerAdapter {
public CustomPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentForInstruction1();
case 1:
return new FragmentForInstruction2();
case 2:
return new FragmentForInstruction3();
case 3:
return new FragmentForInstruction4();
default:
return new FragmentForInstruction1();
}
}
#Override
public int getCount() {
return 4;
}
}
While crating an instance of it, pass the getChildFragmentManager() instead of getSupportFragmentManager():
viewPager.setAdapter(new CustomPagerAdapter(getChildFragmentManager()));
In my app, I have requirement of Multi Payne layout. In this layout, the first fragment is a ListView which shows the list of items. On click of the list item, a detail view will open up on the right hand side of the list item. But, in my case, when I run my app on tablet, the detail view appears along with ListView by default. While, I want that it should appear on click of the list item.
Below is my code:
Activity Class:
public class OrderActivity extends FragmentActivity implements
OnOrderSelectedListener {
private static final String TAG = "OrderActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate called");
setContentView(R.layout.order_details);
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
OrderListFragment orderListFragment = new OrderListFragment();
orderListFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, orderListFragment).commit();
}
}
#Override
public void onOrderSelected(int position) {
Log.d(TAG, "onOrderSelected called");
OrderDetailFragment detailsFrag = (OrderDetailFragment) getSupportFragmentManager()
.findFragmentById(R.id.order_detail_fragment);
if (detailsFrag != null) {
if (!detailsFrag.isVisible()) {
detailsFrag.setUserVisibleHint(true);
detailsFrag.updateOrderView(position);
}
} else {
OrderDetailFragment newFragment = new OrderDetailFragment();
Bundle args = new Bundle();
args.putInt(OrderDetailFragment.ARG_POSITION, position);
newFragment.setArguments(args);;
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
LIst Fragment
public class OrderListFragment extends ListFragment {
private static final String TAG = "OrderListFragment";
OnOrderSelectedListener mOnOrderSelectedListener;
public interface OnOrderSelectedListener {
public void onOrderSelected(int position);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate called");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView called");
return inflater.inflate(R.layout.order_list, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG, "onActivityCreated called");
ArrayList<Data> mDataList = new ArrayList<Data>();
Data mData1 = new Data("1", "11001", "08/07/2013", "GAUGE_RUN",
"Dispatched", "Terminal:", "Rail Terminal:", "New York",
"Washington DC");
Data mData2 = new Data("1", "11002", "08/07/2013", "GAUGE_RUN",
"Dispatched", "Terminal:", "Rail Terminal:", "New York",
"Washington DC");
mDataList.add(mData1);
mDataList.add(mData2);
setListAdapter(new OrderAdapter(getActivity(),
R.layout.order_list_item, mDataList));
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart called");
if (getFragmentManager().findFragmentById(R.id.order_detail_fragment) != null) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.d(TAG, "onAttach called");
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
mOnOrderSelectedListener = (OnOrderSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.d(TAG, "onListItemClicked");
mOnOrderSelectedListener.onOrderSelected(position);
getListView().setItemChecked(position, true);
}
}
Detail Fragment
public class OrderDetailFragment extends Fragment {
public final static String ARG_POSITION = "position";
int mCurrentPosition = -1;
private static final String TAG = "OrderDetailFragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView called");
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
}
return inflater.inflate(R.layout.acceptance_details, container, false);
}
#Override
public void onStart() {
Log.d(TAG, "onStart called");
super.onStart();
Bundle args = getArguments();
if (args != null) {
updateOrderView(args.getInt(ARG_POSITION));
} else if (mCurrentPosition != -1) {
updateOrderView(mCurrentPosition);
}
}
public void updateOrderView(int position) {
Log.d(TAG, "updateOrderView called");
/*
* TextView article = (TextView)
* getActivity().findViewById(R.id.article);
* article.setText(Ipsum.Articles[position]); btnNext = (Button)
* getActivity().findViewById(R.id.btnNext);
* btnNext.setOnClickListener(this); mCurrentPosition = position;
*/
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.d(TAG, "onSaveInstanceState called");
super.onSaveInstanceState(outState);
outState.putInt(ARG_POSITION, mCurrentPosition);
}
}
Activity Layout
<?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"
android:background="#android:color/white"
android:orientation="horizontal" >
<com.dzo.dispatchcrude.driverapp.ui.HeaderBar
android:id="#+id/headerBar"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_alignParentTop="true" >
</com.dzo.dispatchcrude.driverapp.ui.HeaderBar>
<LinearLayout
android:id="#+id/linOrderView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/headerBar"
android:baselineAligned="false"
android:orientation="horizontal" >
<fragment
android:id="#+id/order_list_fragment"
android:name="com.dzo.dispatchcrude.driverapp.ui.OrderListFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="#+id/order_detail_fragment"
android:name="com.dzo.dispatchcrude.driverapp.ui.OrderDetailFragment"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="30dp"
android:layout_weight="2" />
</LinearLayout>
</RelativeLayout>
List Fragment layout
<?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/android:list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:dividerHeight="1dp" />
</LinearLayout>
Order Detail Fragment
<?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="wrap_content"
android:layout_margin="20dp"
android:background="#drawable/corner_shape"
android:orientation="vertical" >
<TextView
android:id="#+id/txtHeaderType"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginBottom="-5dp"
android:background="#drawable/upper_corner"
android:gravity="center"
android:text="#string/acceptance_details"
android:textColor="#android:color/white"
android:textSize="30sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtHeaderSource"
android:layout_width="match_parent"
android:layout_height="70dp"
android:background="#drawable/rectangle"
android:gravity="center"
android:textSize="25sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="#+id/txtTruck"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:paddingLeft="15dp"
android:text="#string/truck"
android:textColor="#color/text_color"
android:textSize="20sp"
android:typeface="sans" />
<Spinner
android:id="#+id/truckSpinner"
style="#android:style/Widget.Spinner"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_margin="10dp"
android:layout_weight="3"
android:background="#drawable/bg_edit_text"
android:gravity="center"
android:spinnerMode="dropdown" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/divider_color" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="#+id/txtTrailor"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:paddingLeft="15dp"
android:text="#string/trailor"
android:textColor="#color/text_color"
android:textSize="20sp" />
<Spinner
android:id="#+id/trailorSpinner"
style="#android:style/Widget.Spinner"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_margin="10dp"
android:layout_weight="3"
android:background="#drawable/bg_edit_text"
android:gravity="center"
android:spinnerMode="dropdown" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/divider_color" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="#+id/txtTrailor2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:paddingLeft="15dp"
android:text="#string/trailor2"
android:textColor="#color/text_color"
android:textSize="20sp" />
<Spinner
android:id="#+id/trailor2Spinner"
style="#android:style/Widget.Spinner"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_margin="10dp"
android:layout_weight="3"
android:background="#drawable/bg_edit_text"
android:gravity="center"
android:spinnerMode="dropdown" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/divider_color" />
<Button
android:id="#+id/btnAccept"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginBottom="25dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="25dp"
android:background="#drawable/input_button"
android:gravity="center"
android:text="#string/accept"
android:textColor="#android:color/white"
android:textSize="30sp"
android:textStyle="bold" />
</LinearLayout>
I did gone through Fragments Basic Demo given on the Android developer's site, but couldn't figure out my mistake.
try this
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listview.setItemChecked(0,false);